Saturday, December 12, 2009

Sql Server Data Base Back Up Using C#

private void btnBackUp_Click(object sender, EventArgs e)
{

bool bBackUpStatus = true;
Cursor.Current = Cursors.WaitCursor;

string path="D:\\SQLBackup";
//string path = Environment.GetFolderPath(System.Environment.SpecialFolder.System);

string path1,path2=path ;

string date = System.DateTime.Today.Day.ToString() + System.DateTime.Today.Month.ToString() + System.DateTime.Today.Year .ToString();

string backupname = "\\wcBackUp1.bak";
if (Directory.Exists(@path))
{
path = path + "\\" + date;
path1 = path + "\\";
if (Directory.Exists(@path))
{
path = path + "\\" + backupname;
}
else
{
Directory.CreateDirectory(@path);
path = path + "\\" + backupname;
}

//if (System.IO.File.Exists(@path))
//{
// if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
// {

// System.IO.File.Delete(@path);
// }
// else
// bBackUpStatus = false;
//}
}
else
{
Directory.CreateDirectory(@path2);
path = path + "\\" + date;
path1 = path + "\\";
if (Directory.Exists(@path))
{
path = path + "\\" +backupname;
}
else
{
Directory.CreateDirectory(@path);
path = path + "\\" + backupname;
}

if (System.IO.File.Exists(@path))
//@"c:\SQLBackup\wcBackUp1.bak"))
{
scount++;
//if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
//{

// System.IO.File.Delete(@path1);
//}
//else
// bBackUpStatus = false;
}
}

if (scount == 0)
{
//Connect to DB
SqlConnection connect;
string con = Helper.ConnectionString.ToString();
connect = new SqlConnection(con);
connect.Open();
//----------------------------------------------------------------------------------------------------
//Execute SQL---------------
SqlCommand command;
command = new SqlCommand(@"backup database HealthManagement to disk ='" + path + "'", connect);
command.ExecuteNonQuery();
//-------------------------------------------------------------------------------------------------------------------------------
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("BackUp Already Taken For Today","Back", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

}

Friday, December 4, 2009

Dynamic Crystal Report using C#

DOWNLOAD
  1. Create a C# project or add a Form to your existing project. Now you can add Checkboxes that correspond to columns of a particular table that should be displayed in the Crystal Report and CrystalReportViewer control to the form.
Screenshot - pic4.jpg For this demonstration, I have created a database called db1.mdb (in bin\Debug) using Access and created a table called Customer.

Screenshot - pic5.jpg
  1. Add a DataSet (*.xsd file) to your project using add -> New Items in solution explorer. After that, add a DataTable to the DataSet.
    Add columns to DataTable and name them Column1, Column2, and so on. The number of columns depends on how many columns should be displayed in the Crystal report.
  2. Add a Crystal Report into the project and using the Report Wizard, choose ADO.NET DataSets of the Project data source as the data source of the Crystal Report and select Customer data table of DataSet1 as the selected table of the Crystal Report. Then select fields to be displayed in your report. Then remove Column1…, Column5 objects in Section 2 of the Crystal Report. 
    Screenshot - pic8.jpg
  3. Now add parameters called col1, col2col5 (the number of parameters should be equal to the number of columns displayed in the Crystal Report.) using Field Explorer. Screenshot - pic9.jpg
  4. Add the following method to your Form for Create SQL SELECT query and assign values to parameters of the Crystal Report according to user selected columns that should be displayed on your report.






    Collapse
    /// <summary>
    /// This method is used to 
    /// 1. create SELECT query according to the selected column names and 
    /// 2. create parameters and assign values for that parameter
    /// that correspond to the crystal report.
    /// NOTE: This parameter is used to display Column names of the 
    /// Crystal Report according to the user selection.
    /// </summary>
    /// <returns></returns>
    private string CreateSelectQueryAndParameters()
    {
    ReportDocument reportDocument;
    ParameterFields paramFields;
        
    ParameterField paramField;
    ParameterDiscreteValue paramDiscreteValue;
    
    reportDocument = new ReportDocument();
    paramFields = new ParameterFields();
                   
    string query = "SELECT ";
    int columnNo = 0;                
    
    if (chbCode.Checked)
    {
    columnNo++;
    query = query.Insert(query.Length, "Code as Column" +
    columnNo.ToString());
    
    paramField = new ParameterField();
    paramField.Name = "col" + columnNo.ToString();
    paramDiscreteValue = new ParameterDiscreteValue();
    paramDiscreteValue.Value = "Customer Code";
    paramField.CurrentValues.Add(paramDiscreteValue);
    //Add the paramField to paramFields
    paramFields.Add(paramField);
    }
    if (chbFirstName.Checked)
    {
    columnNo++;
    if (query.Contains("Column"))
    {
    query = query.Insert(query.Length, ", ");
    }
    query = query.Insert(query.Length, "FirstName as Column" +
    columnNo.ToString());
            
    paramField = new ParameterField();
    paramField.Name = "col" + columnNo.ToString();
    paramDiscreteValue = new ParameterDiscreteValue();
    paramDiscreteValue.Value = "First Name";
    paramField.CurrentValues.Add(paramDiscreteValue);
    //Add the paramField to paramFields
    paramFields.Add(paramField);
    }
    if (chbLastName.Checked)
    {
    columnNo++; //To determine Column number
    if (query.Contains("Column"))
    {
    query = query.Insert(query.Length, ", ");
    }
    query = query.Insert(query.Length, "LastName as Column" +
    columnNo.ToString());
                           
    paramField = new ParameterField();
    paramField.Name = "col" + columnNo.ToString();
    paramDiscreteValue = new ParameterDiscreteValue();
    paramDiscreteValue.Value = "Last Name";
    paramField.CurrentValues.Add(paramDiscreteValue);
    //Add the paramField to paramFields
    paramFields.Add(paramField);
    }
    if (chbAddress.Checked)
    {
    columnNo++;
    if (query.Contains("Column"))
    {
    query = query.Insert(query.Length, ", ");
    }
    query = query.Insert(query.Length, "Address as Column" +
     columnNo.ToString());
                           
    paramField = new ParameterField();
    paramField.Name = "col" + columnNo.ToString();
    paramDiscreteValue = new ParameterDiscreteValue();
    paramDiscreteValue.Value = "Address";
    paramField.CurrentValues.Add(paramDiscreteValue);
    //Add the paramField to paramFields
    paramFields.Add(paramField);
    }
    if (chbPhone.Checked)
    {
    columnNo++;
    if (query.Contains("Column"))
    {
    query = query.Insert(query.Length, ", ");
    }
    query = query.Insert(query.Length, "Phone as Column" +
    columnNo.ToString());
    
    paramField = new ParameterField();
    paramField.Name = "col" + columnNo.ToString();
    paramDiscreteValue = new ParameterDiscreteValue();
    paramDiscreteValue.Value = "Phone";
    paramField.CurrentValues.Add(paramDiscreteValue);
    //Add the paramField to paramFields
    paramFields.Add(paramField);
    }
    
    //if there is any remaining parameter, assign empty value for that 
    //parameter.
    for (int i = columnNo; i < 5; i++)
    {
     columnNo++;
     paramField = new ParameterField();
     paramField.Name = "col" + columnNo.ToString();
     paramDiscreteValue = new ParameterDiscreteValue();
     paramDiscreteValue.Value = "";
     paramField.CurrentValues.Add(paramDiscreteValue);
     //Add the paramField to paramFields
     paramFields.Add(paramField);
     }
               
     crystalReportViewer1.ParameterFieldInfo = paramFields;
        
     query += " FROM Customer" ;
     return query;
     }
    //






  5. Add the following method to the button click event to display a report when the user presses the button:






    Collapse
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.OleDb;
    
    using CrystalDecisions.CrystalReports.Engine;
    using CrystalDecisions.ReportSource;
    using CrystalDecisions.Shared;
    using CrystalDecisions.Windows.Forms;
    
    namespace app5
    {
    public partial class Form1 : Form
    {
    CrystalReport1 objRpt;
    
    public Form1()
    {
     InitializeComponent();
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
      objRpt = new CrystalReport1();
    
      string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=|DataDirectory|\\db1.mdb"; 
               
     //Get Select query String and add parameters to the 
     //Crystal report.
     string query = CreateSelectQueryAndParameters();
    
     //if there is no item select, then exit from the method.
     if (!query.Contains("Column"))
      {
       MessageBox.Show("No selection to display!");
       return;
       }
    
     try
     {
      OleDbConnection Conn = new OleDbConnection(connString);
    
      OleDbDataAdapter adepter = 
      new OleDbDataAdapter(query, connString);
      DataSet1 Ds = new DataSet1();
    
      adepter.Fill(Ds, "Customer");
                    
      objRpt.SetDataSource(Ds);
      crystalReportViewer1.ReportSource = objRpt;
      }
     catch (OleDbException oleEx)
      {
      MessageBox.Show(oleEx.Message);
      }
     catch (Exception Ex)
      {
      MessageBox.Show(Ex.Message);
      }
      }






Sending Mail in Asp.net using C#

DOWNLOAD
using System.Net;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage msgobj;
            SmtpClient serverobj = new SmtpClient();
            serverobj.Credentials = new NetworkCredential(TextBox1.Text, TextBox2.Text);
            serverobj.Port = 587;
            serverobj.Host = "smtp.gmail.com";
            serverobj.EnableSsl = true;
            msgobj = new MailMessage();
            msgobj.From = new MailAddress(TextBox1.Text, "hi", System.Text.Encoding.UTF8);
            msgobj.To.Add(TextBox3.Text);
            msgobj.Subject = TextBox4.Text;
            msgobj.Body = TextBox5.Text;
            // msgobj .Attachments .Add (new Attachment (MapPath ("pocketpc.gif"));
            msgobj.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            serverobj.Send(msgobj);
            Label5.Visible = true;
            Label5.Text = "Mail send Successfully";
        }
        catch
        {
            Label5.Visible = true;
            Label5.Text = "mail sending failed";
        }
    }
}

Monday, November 2, 2009

Repeater control with paging

public partial class _Default : System.Web.UI.Page
{
    public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rptPages.ItemCommand +=
           new RepeaterCommandEventHandler(rptPages_ItemCommand);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadData();
    }
    private void LoadData()
   {
      SqlConnection cn = new SqlConnection("Data Source=AJTECH4;Initial Catalog=vamsi;Integrated Security=True");
      cn.Open();
      SqlDataAdapter da = new SqlDataAdapter("select * from repeatertask", cn);
      DataTable dt = new DataTable();
      da.Fill(dt);
      cn.Close();
      PagedDataSource pgitems = new PagedDataSource();
      DataView dv = new DataView(dt);
      pgitems.DataSource = dv;
      pgitems.AllowPaging = true;
      pgitems.PageSize = 3;
      pgitems.CurrentPageIndex = PageNumber;
      if (pgitems.PageCount > 1)
      {
         rptPages.Visible = true;
         ArrayList pages = new ArrayList();
         for (int i = 0; i < pgitems.PageCount; i++)
         pages.Add((i + 1).ToString());
         rptPages.DataSource = pages;
         rptPages.DataBind();
      }
      else
         rptPages.Visible = false;
      rptItems.DataSource = pgitems;
      rptItems.DataBind();
   }
   void rptPages_ItemCommand(object source,
                             RepeaterCommandEventArgs e)
   {
      PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
      LoadData();
   }
}
 

Thursday, October 29, 2009

Adding ComboBox to datagrid view in windows

 dataGridView1 .AutoGenerateColumns =false ;

           SqlConnection con = new SqlConnection("User Id=sa; Password=server;Database=vamsi");
           SqlDataAdapter da = new SqlDataAdapter("Select * from details", con);
           DataSet ds = new DataSet();
           da.Fill(ds, "details");
           dataGridView1.DataSource = ds.Tables[0];
           DataGridViewColumn column1 = new DataGridViewComboBoxColumn();
            column1 .DataPropertyName ="No";
            column1 .Name ="Number";
            column1.ReadOnly = true;
            dataGridView1 .Columns.Add (column1);
            DataGridViewColumn column2 =new DataGridViewTextBoxColumn();
            column2.DataPropertyName ="Name";
            column2.Name ="Name";
            dataGridView1 .Columns.Add (column2);
            DataGridViewColumn column3 =new DataGridViewTextBoxColumn();
            column3.DataPropertyName ="Age";
            column3.Name ="Age";
            dataGridView1.Columns.Add (column3);
            DataGridViewColumn column4 =new DataGridViewTextBoxColumn();
            column4.DataPropertyName ="City";
            column4.Name ="City";
            dataGridView1 .Columns.Add (column4);
            this .Controls.Add (dataGridView1);

passing multiple values using query string


                     NavigateUrl='<%# "MyTest.aspx?id=" + DataBinder.Eval(Container.DataItem, "id")
                     +"&AssignedTask="+ DataBinder.Eval(Container.DataItem,"assignedtask")
                     +"&WorkStatus="+ DataBinder.Eval(Container.DataItem,"workstatus")
                     +"&description="+ DataBinder.Eval(Container.DataItem,"description")
                     +"&remarks="+ DataBinder.Eval(Container.DataItem,"remarks") %>'
                     Runat="server" EnableTheming="False"  Font-Underline="False" ToolTip='<%# DataBinder.Eval(Container.DataItem,"id")+" " %>'
                     ForeColor="Black" Text='edit' Font-Bold="False" Font-Strikeout="False">
                

Monday, October 26, 2009

Inserting images into database and retrieving images

public partial class Form1 : Form
{
MemoryStream ms;
DataSet dsRetrieve = new DataSet();
DataSet dsBindData = new DataSet();
string strUrl = "";

private void Form1_Load(object sender, EventArgs e)
{
BLDataSave objBLDataSave=new BLDataSave ();
dsBindData = objBLDataSave.DataBind();
gvDataBind.DataSource = dsBindData.Tables[0].DefaultView;
}

private void btnSave_Click(object sender, EventArgs e)
{
MLDataSave objMLDataSave = new MLDataSave();
objMLDataSave.sno = int .Parse (txtSno.Text);
objMLDataSave.sname = txtSname.Text;
objMLDataSave.classess = int .Parse (txtClass.Text);
ms = new MemoryStream();
pictureBox1.Image.Save(ms,ImageFormat.Jpeg);
byte[] data = new byte[ms.Length];
ms.Position = 0;
ms.Read(data, 0, Convert.ToInt32(ms.Length));
objMLDataSave.photo = data ;
if (btnSave.Text == "Save")
{
BLDataSave objBLDataSave = new BLDataSave();
if (objBLDataSave.DataSave(objMLDataSave) > 0)
{
MessageBox.Show("inserted successfully");
Form1_Load(sender, e);
}
else
MessageBox.Show("insertion failed");
}

}
private void btnRetrieve_Click(object sender, EventArgs e)
{
MLDataSave objMLDataSave = new MLDataSave();
objMLDataSave.id = int.Parse(txtRetrieve.Text);
BLDataSave objBLDataSave = new BLDataSave();
dsRetrieve = objBLDataSave.DataRetrieve(objMLDataSave);
if (dsRetrieve.Tables[0].Rows.Count > 0)
{
txtSno.Text = dsRetrieve.Tables[0].Rows[0]["sno"].ToString();
txtSname.Text = dsRetrieve.Tables[0].Rows[0]["sname"].ToString();
txtClass.Text = dsRetrieve.Tables[0].Rows[0]["class"].ToString();
byte[] logo = (byte[])dsRetrieve.Tables[0].Rows[0]["photo"];
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
fs.Write(logo, 0, logo.Length);
fs.Flush();
fs.Close();
pictureBox1.Image = Image.FromFile(strfn);
lblId.Text = dsRetrieve.Tables[0].Rows[0]["id"].ToString();
}
else
{
MessageBox.Show("Entered sno is not available ");
}

btnSave.Text = "Update";
}
private void btnbrowse_Click(object sender, EventArgs e)
{
OpenFileDialog opg = new OpenFileDialog();
opg.Title = "Select Image";
opg.Filter = "Images (*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG)|*.BMP;*.JPG;*.GIF;*.PNG;*.JPEG*";
opg.FilterIndex = 1;
opg.RestoreDirectory = true;
if (opg.ShowDialog() == DialogResult.OK)
strUrl = "";
strUrl = opg.FileName;
if (strUrl != "")
{
Bitmap bmp = new Bitmap(opg.FileName);
pictureBox1.Image = Image.FromFile(strUrl);
}
}
private void txtRetrieve_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == false && Convert.ToInt32(e.KeyChar) != 8)
{

MessageBox.Show("Enter Numerics Only");
e.Handled = true;
}
}

Sunday, October 25, 2009

Hi

Hi ,This is vamsi Iam a .Net Programmer,I will be posting usefull posts on .Net