Sunday, September 30, 2012

Scenario of processing an MVC request

The simple scenario of processing an MVC request is described in the following steps:
  1. The user enters in the browser some URL that is sent to the server, e.g., http://localhost/Product/List.
  2. The user request is analyzed by the framework in order to determine what controller should be called.
  3. The Controller takes the parameters that the user has sent, calls the model to fetch some data, and loads the model object that should be displayed.
  4. The Controller passes the model object to the view.
  5. The View gets data from the model, puts it into the HTML template, and sends the response back to the user browser.
  6. The browser shows the HTML that is received from the server. 

Saturday, June 2, 2012

How to get all weekday[friday] for a month in C#

Sometimes I need Fridays of a month to do some calculation. I generally follow the following rules.
Lets say you have two combo box, one contains Year and another contains Months name.
When you select your desired year and month from the combo list, you want to get the days which contains Friday. Here is a simple code:

int selYr = Convert.ToInt32(comboYear.SelectedItem.ToString());
int selMn = comboMonth.SelectedIndex;
int[] holiday = new int[5];
int hIdx = 0;

int totalDays = DateTime.DaysInMonth(selYr, selMn);

DateTime currentDate;

for (int i = 1; i <= totalDays; i++)
          currentDate = new DateTime(selYr, selMn, i);
          if (currentDate.DayOfWeek == DayOfWeek.Friday)
                    holiday[hIdx++] = i;

After run this code block holiday array will contain that month's day of Friday. i.e. if you select 2012 as Year and May as Month then holiday will contain [4,11,18,25,0]. If you select June then holiday will contain [1,8,15,22,29]. 

Monday, May 28, 2012

Display Data into DataGridView using DataTable in C#

By the following code we can display data into Data Grid View using datatable.

private void btnShow_Click(object sender, EventArgs e)
        this.Cursor = Cursors.WaitCursor;
        if (myConnection.State.Equals(ConnectionState.Closed))
                myConnection.Open( ); // Here
myConnection is a SQL Connection object

    string selectQry = "SELECT P.PECODE, P.PENAME, P.PDEPNM, P.PSECNM, ";
    selectQry += "D.DDSGDS, P.SHFTNM ";
    selectQry += " WHERE (P.PCOMCD = '" + ComCode + "') ";
    selectQry += " ORDER BY P.PECODE";
    SqlCommand dbcommand = new SqlCommand(selectQry, myConnection);

    dataGridView1.DataSource = null;
    DataTable datatable = new DataTable();

            DataColumn dcol0 = new DataColumn("PECODE", typeof(System.String));
            DataColumn dcol1 = new DataColumn("PENAME", typeof(System.String));
            DataColumn dcol2 = new DataColumn("PDEPNM", typeof(System.String));
            DataColumn dcol3 = new DataColumn("PSECNM", typeof(System.String));
            DataColumn dcol4 = new DataColumn("DDSGDS", typeof(System.String));
            DataColumn dcol5 = new DataColumn("SHFTNM", typeof(System.String));           


            DataRow drow;
            dbreader = dbcommand.ExecuteReader();

            while (dbreader.Read())
                drow = datatable.NewRow();

                drow["PECODE"] = dbreader[0];
                drow["PENAME"] = dbreader[1];
                drow["PDEPNM"] = dbreader[2];
                drow["PSECNM"] = dbreader[3];
                drow["DDSGDS"] = dbreader[4];
                    drow["SHFTNM"] = dbreader[5];
            dbreader.Close( );

            dataGridView1.DataSource = datatable;

            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.ReadOnly = true;
            dataGridView1.RowHeadersVisible = false;

            this.Cursor = Cursors.Default;

Create Report Using DataSet in C#

In the following example we will see how we can send data to report file using dataset.

SqlCommand dbcommand = new SqlCommand("sp_OperatorProcessShow", myConnection);
dbcommand.CommandType = CommandType.StoredProcedure;
dbcommand.Parameters.Add(new SqlParameter("@CompCode", CompanyCode));

// I have used Stored Procedure and supplied parameter

DataSetOP myDS = new DataSetOP(); // DataSetOP is the DataSet Name
DataTable dtMyTable = myDS.Tables["tblOperatorProcs"]; // tblOperatorProcs is the DataTable
DataRow myNewRow;
int count = 0;

SqlDataReader dbreader = dbcommand.ExecuteReader();

while (dbreader.Read())
      myNewRow = dtMyTable.NewRow();

      myNewRow[0] = dbreader[0];
      myNewRow[1] = dbreader[1];
      myNewRow[8] = dbreader[8]; // Add as many record as you need


if (count > 0)
                CROprProcs myDataReport = new CROprProcs(); //
CROprProcs is a Crystal Report file
                myDataReport.SetParameterValue("CompName", compName);
                crystalReportViewer1.ReportSource = myDataReport;
                MessageBox.Show("No Data Found");

How to Read Remote PC file and Show in your PC window

Sometimes you may need to read a file which exists in Server PC and want to show in your Client PC. To make it simple Lets say i want to read an Excel file which exists in a remote machine and want to show in my client machine.

By following code we can do that easily.

FileInfo finfo = new FileInfo(@"\\\D$\Leave information.xls");
bool exists = finfo.Exists;

if (finfo.Exists)

         MessageBox.Show("File Not Found");

// Here my remote PC address is and The Excel file located in D drive 

You may place the above code into any button click event 

Thursday, December 15, 2011

Export DataGridView data into Excel Sheet Using C#

Sometimes you may need to Export Grid View data into Excel Sheet. Using following code u can do that.

using System.IO;

//------------------------- SAVE FILE OPTION -----------------------------
    string fileName = "";
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.CheckPathExists = true;
    saveFileDialog.AddExtension = true;
    saveFileDialog.ValidateNames = true;
    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    saveFileDialog.DefaultExt = ".xls";
    saveFileDialog.Filter = "Microsoft Excel Workbook (*.xls)|*.xls";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
                fileName = saveFileDialog.FileName;

                Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();

                int rowCount = dataGridView1.Rows.Count;
                int colCount = dataGridView1.Columns.Count;

                // Storing header part in Excel
                for (int i = 1; i < colCount + 1; i++)
                    ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;

                // Storing Each row and column value to excel sheet               
                for (int i = 0; i < rowCount; i++)
                    this.Text = "Processing: " + dataGridView1.Rows[i].Cells[0].Value.ToString();
                    for (int j = 0; j < colCount; j++)
                        ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                string fileLocation = fileName;

                if (File.Exists(fileLocation))
                        ExcelApp.ActiveWorkbook.Saved = true;
                        MessageBox.Show("Excel file created-- " + fileLocation);
                    catch (IOException ioe)
                        MessageBox.Show("Close the Excel file and Export again...");
                    ExcelApp.ActiveWorkbook.Saved = true;

                    MessageBox.Show("Excel file created-- " + fileLocation);

You may need to 'ADD' Office reference into your project. By following steps you can add MS office reference. 
First click Project -> Add Reference

Then Go to COM Tab and select Microsoft Excel 11.0 Object Library[or what you have in your PC]
Click OK.

Again Go to Add Reference -> COM Tab and select  Microsoft Office 11.0 Object Library and click OK.
Then You will see some additional object in your Project's Reference tree namely Excel, Microsoft.Office.Core

How to Restrict Non-Numeric Key Press in Text Field

Sometimes you may need to do code in such way that the user may not enter dot[.] or any alphabetic character. Only Integer value should be entered into TextField. In such case you may capture the Key pressed by the User and allow only Numeric values.

The following code only takes numeric value without decimal point for textBox1

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);