Posts Tagged 'C#'

Getting the controlname which caused postback

I am working on a site in which I use a lot of JQuery but there are some pages which I had to use Server Controls and there was a need to get which control caused the postback.  After a bit of searching I found this nice method which did the trick.


private string  getPostBackControlName()
{
 Control control = null;
 //first we will check the "__EVENTTARGET" because if post back made by       the controls
 //which used "_doPostBack" function also available in Request.Form collection.
 string ctrlname = Page.Request.Params["__EVENTTARGET"];
 if (ctrlname != null && ctrlname != String.Empty)
 {
 control = Page.FindControl(ctrlname);
 }
 // if __EVENTTARGET is null, the control is a button type and we need to
 // iterate over the form collection to find it
 else
 {
 string ctrlStr = String.Empty;
 Control c = null;
 foreach (string ctl in Page.Request.Form)
 {
 //handle ImageButton they having an additional "quasi-property" in their Id which identifies
 //mouse x and y coordinates
 if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
 {
 ctrlStr = ctl.Substring(0, ctl.Length - 2);
 c = Page.FindControl(ctrlStr);
 }
 else
 {
 c = Page.FindControl(ctl);
 }
 if (c is System.Web.UI.WebControls.Button ||
 c is System.Web.UI.WebControls.ImageButton)
 {
 control = c;
 break;
 }
 }
 }
 return control.ID;
}

Happy Programming!!!

Cheers,

Raja

Visual Studio 2008 keyboard shortcuts

Sometime back Bryan posted a blog in which he detailed his favorite shortcuts. While browsing through the net I found this good poster which details all the shortcuts.

Keyboard Shortcuts in Visual Studio (C#)

Hope this helps.

Happy Programming!!!

Cheers,

Raja

NetworkCredential in SMTP mail (Forms Authentication)

In the project I am currently working on we have to send email confirmation to the registered user giving them their User ID and Password (yup…..you saw that right password….not secured but that is the requirement :-(). we created a no-reply account and to our amazement all emails sent inside our domain were reaching fine but external domains were not. My hardware tech lead (Mihai) helped me out in checking exchange server(since I didnt have access to it). We saw that no mails to external domain was even queued in exchange. Then Mihai came up to me and asked me to check the credentials which was used for sending email and that was the missing piece :-). Prior to this application all our apps were windows authenticated so there was no need to specify the Network Credentials but in this app we have to use forms authentication since it is an internet site not an intranet site. So added the following line and it worked like charm 🙂


System.Net.NetworkCredential objAuthInfo = new NetworkCredential("<username>", "<password>");

objSMTP.Credentials = objAuthInfo;

Hope this helps.

Happy Programming!!!

Cheers,

Raja

Scrolling to a given row in WinForms DataGridView

We needed to feature to take the user directly to the row which they search by an ID. Even though we have the Row.Selected property for the DataGridView it selected to the row but did not scroll to it. So I used a little hack to scroll to the DataGridView:

I wrote a loop to get the specific data the user is searching for in the grid (dgvDisabilityInformation) and I used the underlying binding source (bsDisability in my case) to set the current position as given below.

for (int iCounter = 0; iCounter < dgvDisabilityInformation.Rows.Count; iCounter++) { objRow = dgvDisabilityInformation.Rows[iCounter]; objCell = objRow.Cells[0]; if (objCell.Value.ToString() == txtGotoRowID.Text.Trim()) { objRow.Selected = true; bsDisability.CurrencyManager.Position = objRow.Index; Found = true; break; } } [/sourcecode] Works like a charm 🙂 Hope this helps. Happy Programming!!! Cheers, Raja

Case and Exists in TSQL to LINQ To SQL

I had a pretty interesting scenario for which I needed a solution. I wanted to translate the following query to LINQ to SQL:


SELECT
 CaseNumber,
 FirstName,
 LastName,
 CASE WHEN Exists(Select 1 from Waiver.CaseHistory WHERE CaseNumber = t1.CaseNumber) THEN 'Yes'
   ELSE 'No' END
FROM
 Waiver.Cases t1

After a bit of searching I finally found a way to exactly do it. I have included that below:


var objQuery = from objWaiver in objDataContext.Cases
      select new
      {
       CN = objWaiver.CaseNumber,
       FN = objWaiver.FirstName,
       LN = objWaiver.LastName,
       HS = ((from objHistory in objDataContext.CaseHistories select objHistory.CaseNumber).Contains(objWaiver.CaseNumber) ? "Yes" : "No")
      };

Hope this helps.

Happy Programming !!!

Cheers,

Raja

DateTime.ParseExact method a life saver :-)

This is a pretty sweet method when it comes to checking the validity of formatted dates. Our users are so much used to typing in MMDDYY in the mainframe that they wanted this option in our application too. We could not just make them type in MMDDYY without checking for the validity of it. That is when DataTime.ParseExact helped us so much. All you do is something like this:


DateTime objDate = DateTime.ParseExact("051109", "MMddyy", System.Threading.Thread.CurrentThread.CurrentCulture);

Hope this helps.

Happy Programming!!!

Cheers,

Raja

Export To Excel

This is a pretty simple console application which I wrote for exporting query results into excel. We prepare a lot of reports which we send it as excel files. It was getting tedious for us to copy the results and then paste it in excel. So Ron asked me to create a utility to export the query results directly into Excel. I used the Office 2007 excel interop. Given below is the code for the utility:

using System;
using System.Data.SqlClient;
using System.Data;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;

namespace ExportToExcel
{
    class Program
    {
        //Usage:
        //ExportToExcel -c, ConnectionString,-q, Query, -d, Directory (exclude the last \),-f FileName (add .xls)
        static void Main(string[] args)
        {
            Console.WriteLine(“Initializing Variables…..”);
            ApplicationClass objExcel = new ApplicationClass();
            Workbook objWorkbook;
            Worksheet objWorksheet;
            DirectoryInfo objDirectoryInfo;
            try
            {
                if (args != null)
                {
                    object objMissingValue = Missing.Value;
                    if (args.Length != 8)
                    {
                        Console.WriteLine(“\nIncorrect number of arguments. (-c connectionstring -q query -d directory -f filename)”);
                        return;
                    }
                   
                    string ConnectionString = “”;
                    string Query = “”;
                    string Directory = “”;
                    string Filename = “”;

                    for (int counter = 0; counter <= args.Length - 1; counter++)                     {                         switch (args[counter])                         {                             case "-c":                                 ConnectionString = args[counter + 1];                                 break;                             case "-q":                                 Query = args[counter + 1];                                 break;                             case "-d":                                 Directory = args[counter + 1];                                 break;                             case "-f":                                 Filename = args[counter + 1];                                 break;                             default:                                 break;                         }                     }                     Console.WriteLine("Initializing Excel.....");                     objWorkbook = objExcel.Workbooks.Add(objMissingValue);                     objWorksheet = (Worksheet)objWorkbook.Worksheets.Add(objMissingValue, objMissingValue, objMissingValue, objMissingValue);                     objWorksheet.Name = "Query Data";                     Console.WriteLine("Opening Data Connection.....");                     SqlConnection objConn = new SqlConnection(ConnectionString);                     objConn.Open();                     SqlCommand objCommand = new SqlCommand(Query, objConn);                     SqlDataAdapter objAdapter = new SqlDataAdapter(objCommand);                     DataSet objDataset = new DataSet();                     Console.WriteLine("Filling Dataset.....");                     objAdapter.Fill(objDataset);                     System.Data.DataTable objDatatable;                     objDatatable = objDataset.Tables[0];                     int ColCounter = 0;                     int RowCounter = 0;                     int Column, Row;                     Row = 1;                     Column = 1;                     Console.WriteLine("Setting Header Information.....");                     //Settting the header                     while (ColCounter <= objDatatable.Columns.Count - 1)                     {                         objWorksheet.Cells[Row, Column] = objDatatable.Columns[ColCounter].ColumnName;                         Column++;                         ColCounter++;                     }                     Console.WriteLine("Generating Data.....");                     //Generating the data                                Row++;                     while (RowCounter <= objDatatable.Rows.Count - 1)                     {                         Column = 1;                         ColCounter = 0;                         while (ColCounter <= objDatatable.Columns.Count - 1)                         {                             objWorksheet.Cells[Row, Column] = objDatatable.Rows[RowCounter][ColCounter].ToString();                             Column++;                             ColCounter++;                         }                         Row++;                         RowCounter++;                     }                     Console.WriteLine("Checking for Directory Existence and Saving file.....");                     objDirectoryInfo = new DirectoryInfo(Directory);                     //Updated on 05/08/2009 by Raja                     //Checking for the existence of Directory before saving the file since Excel is not automatically creating the file                     //Starts here                     if (objDirectoryInfo.Exists) //all is well 🙂                         objWorkbook.SaveAs(Directory + "\\" + Filename, objMissingValue, objMissingValue, objMissingValue, objMissingValue, objMissingValue, XlSaveAsAccessMode.xlNoChange, objMissingValue, objMissingValue, objMissingValue, objMissingValue, objMissingValue);                     else                     {                         //oops....create the directory and then save the file                         objDirectoryInfo.Create();                         objWorkbook.SaveAs(Directory + "\\" + Filename, objMissingValue, objMissingValue, objMissingValue, objMissingValue, objMissingValue, XlSaveAsAccessMode.xlNoChange, objMissingValue, objMissingValue, objMissingValue, objMissingValue, objMissingValue);                     }                     //Ends here                     objWorkbook.Close(false, objMissingValue, objMissingValue);                     Console.WriteLine("Successfully exported the data to the given file");                                    }             }             catch (Exception ex)             {                 objExcel.Quit();                 objWorksheet = null;                 objWorkbook = null;                 objExcel = null;                 objDirectoryInfo = null;                 Console.WriteLine(ex.Message);             }                     }             } } [/sourcecode] As always I would appreciate your feedback. Hope this helps. Happy Programming!!! Cheers, Raja

Partial Methods

We all know about Partial Classes (in case you dont know read here) but I was intriqued when I look at LINQ to SQL generated designer.cs. I saw methods like

partial void OnLoaded();

partial  void OnCreated();

After a bit of researching I came to know that these are called as Partial Methods and their implementation is pretty neat. Check out this blog to get an overview about partial method implementation Or check out this blog for a detailed explanation about Partial methods.

Happy Programming!!!

Cheers,

Raja

How to Upload and Download Image/BLOB Data in SQL Server

There was a very interesting post over on SQL Authority on how to upload image data to SQL Server. The question was posed, “How do you then retrieve that data from SQL Server.”

You could build an application and retrieve the data through a GUI, but that would be a rather cumbersome process if you had multiple images to download.

Within SQL Server itself, this requires a multi-step process of created a BCP format file and then using BCP QueryOut to create the actual image files. Fast and efficient, but it could be better.

My preferred method would be to use CLR. Once you have registered the assembly, making sure to mark it for external access, this task can be accomplished in a single step.

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void usp_RetrieveBlobData(string query, string outpath)
    {
        using (SqlConnection connection = new SqlConnection("context connection=true"))
        {
            connection.Open();
            SqlCommand command = new SqlCommand(query, connection);
            SqlDataReader reader = command.ExecuteReader();

            using (reader)
            {
                while (reader.Read())
                {
                    FileStream fs = File.Create(outpath);
                    BinaryWriter bw = new BinaryWriter(fs);

                    byte[] file = (byte[])reader.GetSqlBinary(0);

                    bw.Write(file);

                    bw.Close();
                    fs.Close();
                }
            }
        }
    }
};

NOTE: You will also need to enable CLR on the server.

~Ron

Server side safe JSON

We are working on a project which involves a lot of JQuery and JSON. We wanted to make sure that the JSON does not fail to evaluate so I got the function given below (after a bit of searching) to make the string safe so that it successfully evaluates. There you go…..

// Make a string safe for JSON evaluation
private static string SafeJSON(string sIn)
{
    StringBuilder sbOut = new StringBuilder(sIn.Length); //using the StringBuilder Class for performance
    foreach (char ch in sIn) //Looping through the string (dont u think a counter is better???)
    {
        if (Char.IsControl(ch) || ch == '\'')
        {
            int ich = (int)ch;
            sbOut.Append(@"\u" + ich.ToString("x4"));
            continue;
        }
        else if (ch == '\"' || ch == '\\' || ch == '/')
        {
            sbOut.Append('\\');
        }
        sbOut.Append(ch);
    }
    return sbOut.ToString();
}

Hope this helps.

Happy Programming!!!

Cheers,

Raja