Twitter Feed Popout byInfofru

Get Primary key on Row Command (GridView)

 Some days back I got a query from one of my fellow, regarding a very normal situation I mean that’s the day to day task that we as a developers are doing. Here is the scenarioScenario: Consider you have a data grid view which show a list of products from northwind database and you want a link button which will edit the same grid view entry but in a separate page and on separate form with the help of the primary key which you may want to send to another page using query string or else.So the task is to get the primary key of the row on which the link button is pressed.Solution:Well, we can achieve this task from variety of methods. Let me just give you a quick list of how we can do this.
1. Have Hidden Field in Link button column2. Pass PK in command argument3. Using Data key names.
Ok, for basics I have created two pages one if default.aspx which holds the grid and the other is editform.aspx which will get the primary key sent by Default.aspxOn editForm.aspx add the following code on page load. 
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load   If Not Request.QueryString("Id") Is Nothing Then 'check if there is nothing in query string       Response.Write("Product Id Is : " + Request.QueryString("Id").ToString()) 'print the id   End IfEnd Sub 
Now for the for the different approaches let's read belowApproach 1 (Hidden field)Write the following grid view on default.aspx 
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  DataSourceID="SqlDataSource1"><Columns><asp:BoundField DataField="ProductName" HeaderText="ProductName" /><asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /><asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /><asp:TemplateField><ItemTemplate><asp:HiddenField ID="hfKey" runat="server" Value='<%#Eval("ProductID") %>' /><asp:LinkButton ID="Edit" CommandName="edt" runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField></Columns></asp:GridView>  
Notice that, we have taken a hidden field just in the same column we have the link button and have it default value of out primary key field. Now on RowCommandEvent of the grid view write the following code 
 Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    If e.CommandName.ToLower() = "edt"  Then       Dim lb As LinkButton = CType(e.CommandSource, LinkButton) 'getting clicked link button       Dim strKey As String = CType(lb.Parent.FindControl("hfKey"), HiddenField).Value 'getting PK Value       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub  
I guess code does not need any explanation, so let's move on to the next approach.Approach 2We have a minor change the in Template Field of the Gridview we write in Default.aspx. replace that with the following code.  
<asp:TemplateField><ItemTemplate><asp:LinkButton ID="Edit" CommandName="edt" CommandArgument='<%#Eval("ProductId") %>' runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField>
So, we have remove the hidden field we have added in the last approacha and simply add the command argument to the link button, now to catch the command argument and send it to edit form write the following code onRowCommand Event   
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As  System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    If e.CommandName.ToLower() = "edt" Then       Dim strKey As String = e.CommandArgument  'Getting Pk Value from argument       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub  
Approach 3:Ok, for this you need to add DataKeyNames Property to main GridViewMarkup. In other word, it is an attribute of grid view which can accept multiple values using "," but in our case we are using one. So when we add this attribute our grid markup will look like as follows
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID ="SqlDataSource1"><Columns><asp:BoundField DataField="ProductName" HeaderText="ProductName" /><asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" /><asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" /><asp:TemplateField><ItemTemplate><asp:LinkButton ID="Edit" CommandName="edt" runat="server">Edit</asp:LinkButton></ItemTemplate></asp:TemplateField></Columns></asp:GridView>
 Notice that we have remove command argument from link button, now add the following code on the RowCommand Function.
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand    if e.CommandName.ToLower() = "edt" Then       Dim lb As LinkButton = CType(e.CommandSource, LinkButton)       Dim gvRow As GridViewRow = lb.BindingContainer 'Getting current row to get index       Dim strKey As String = GridView1.DataKeys(gvRow.RowIndex)(0).ToString()       Response.Redirect("EditForm.aspx?id=" + strKey) 'redirecting    End IfEnd Sub
In the above code we are getting the current row from which the link button is clicked because we need the index of the row to get the data key name value.So, now you have plenty of choices to select which approach you like to go with :) .Screen Cast :

Create dynamic controls with validation

Creating a dynamic control and render to a page is a simple task but what happen when you need to apply validation to that dynamic control.Here is the little snippet of that
TextBox objtext = new TextBox();Page.Form.Controls.Add(objtext);RequiredFieldValidator objReq = new RequiredFieldValidator();objtext.ID = "MyTextBox";objReq.ControlToValidate = objtext.ID;objReq.ErrorMessage = "Please tell us some thing";Page.Form.Controls.Add(objReq);

Pattern Matching of Hyper Link C#

Considering you have a string like"xyrsdsfdfshfds<a>sdjsgdjgsjdsd</a>yutrsgdhdg abcd yhsgjhgshdg<a href=''>xyz</a>";And you want to get all the links in the string which have hyper link specified. To get this job done try the following code.
string ptrn = "<a href='[^']+'>[^<]+</a>"; //<a href="http://[^"]+">([^<]+)</a> use that as wellstring strToCompare = "xyrsdsfdfshfds<a>sdjsgdjgsjdsd</a>yutrsgdhdg abcd yhsgjhgshdg<a href=''>xyz</a>";Regex objRegex = new Regex(ptrn);if (objRegex.IsMatch(strToCompare)){Response.Write(objRegex.Matches(strToCompare)[0].Value);// I am using this .. you can iterate in array and read all the values}

Map AdRotator to a folder

Few days before one of my fellow comes up with this challenge, the requirement is good but by using it you will lose control over two thing1. Navigate URL2. Impression PriorityIf you are ready to compromise on these two then the solution is here. Please bear in mind that this is not how to of Ad rotator control. It is related to advance use. To learn basics please visitAs you all know that Ad Rotator control accept an xml file to show advertisement. the scehma of the xml file is as follow. 
So to make it work dynamically, I mean by mapping to a folder we need to write an xml file each time the page load. (You can use some alternative approaches as well) First, we write to set the Adrotator on out aspx page.
<asp:AdRotator ID="AdRotator1" runat="server" /> 
 Then to generate a file using any folder I write the following function
private void bindFiles()        {            string strPath = "/images/"; //Folder Path            DirectoryInfo di = new DirectoryInfo(Server.MapPath(strPath));            if (di.Exists)            {                string filename = Server.MapPath("/upload/temp.xml");                               XmlTextWriter objtw = new XmlTextWriter(filename, System.Text.UTF8Encoding.UTF8);                objtw.WriteStartDocument();                objtw.WriteStartElement("Advertisements");                               FileInfo[] objFile = di.GetFiles("*.jpg"); //you can extract multiple format of images                foreach (FileInfo f in objFile)                {                    objtw.WriteStartElement("Ad");                    objtw.WriteStartElement("ImageUrl");                    objtw.WriteString(strPath + f.Name);                    objtw.WriteEndElement();                                       objtw.WriteStartElement("NavigateUrl");                    objtw.WriteString("#"); // Passing # means no action                    objtw.WriteEndElement();                                              objtw.WriteStartElement("AlternateText");                    objtw.WriteString(f.Name);                    objtw.WriteEndElement();                           objtw.WriteStartElement("Impressions");                    objtw.WriteString("1"); //As we don't know of any priotiry, keep it 1 for every one                    objtw.WriteEndElement();                           objtw.WriteEndElement();                }                       objtw.WriteEndElement();                objtw.WriteEndDocument();                               objtw.Flush();                objtw.Close();            }        } 
   And on the load event of page write the following stuff. 
if  (!Page.IsPostBack) {bindFiles();AdRotator1.AdvertisementFile = "/upload/temp.xml"; }
That's the whole story.

Delete button with Javascript confirm in Datagrid

It is often a good practice to show a confirmation alert to the user when they select to delete any record. So for that, here is the quick code consider the following grid view. 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"CellPadding="3" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"ForeColor="Black" GridLines="Vertical" Width="100%" onrowcommand="GridView1_RowCommand"><Columns><asp:BoundField DataField="CategoryID" HeaderText="CategoryID"InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" /><asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" /> <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" /><asp:TemplateField><ItemTemplate><asp:LinkButton ID="lbDelet" CommandName="del" runat="server" Text="Delete" OnClientClick="javascript:return confirm('Are you sure you want to delete ?');"></asp:LinkButton></ItemTemplate></asp:TemplateField></Columns><FooterStyle BackColor="#CCCCCC" /><PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" /><SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /><HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /><AlternatingRowStyle BackColor="#CCCCCC" /></asp:GridView 
Notice the last column which is template column and having a link button (ID = lbDelet). onClientClick is doing the main stuff.That's it cheers

Could not load file or assembly Microsoft.SqlServer.Management.Sdk.Sfc

Another sick error of the day, When you try to create connection string from SQLDatasource or even want to bind existing connection string. You might see a Message box saying
Could not load file or assembly 'Microsoft.SqlServer.Management.Sdk.Sfc, Version=, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
This error comes when you are trying to access SQL 2005 stuff from Visual Studio 2008.  So go to the link and download the following stuff
  • Microsoft SQL Server System CLR Types
  • Microsoft SQL Server 2008 Management Objects
  • Microsoft SQL Server 2008 Native Client

The Project Creation Wizard was not able to connect to the Windows SharePoint Services at [Server-Name]

This morning we had another TFS Error. I guess, I can write a book called "Team System Errors and Solutions" :).The Error occured during the creation of New Project
The Project Creation Wizard was not able to connect to the Windows SharePoint Services at [Server-Name]
The error is mainly because the sharepoint admin services (Sharepoint Central Administration Site) is no more working.So to remove the error I took following steps on the server
1. Goto IIS2. Click Application Pools3. Right Click -> Sharepoint Administration Site V3 (It is the application pool which is in used by Admin site)4. Click Properties5. Identity Tab and make sure the user which is in use by Application Pool is a valid TFS Service Acccount. If it is then re-enter user id and password
and it will work.

Localization in (Quick View)

In the past few days, I see some posts in forum ( regarding Localization which is actually very easy but there is no quick view to Localization in available. So I plan to write one for my blog.Localization is something by which you can provide your end user a functionality to read your content in multiple languages. To cut it short … you have content in languages as such English and French and you are managing the whole stuff on one page. That is the main concept of Localization.Now, to use the feature of localization provides you with a file called Resource File (.RESX). Remember the time of Visual Studio 2003 it is added with the page by default. This file is nothing more than a normal XML file having Key / Value pairs stored inside.The Resource files will be created under some special folders which are as follows.App_GlobalResourcesApp_LocalResourcesThe difference between two is visible by their name which is off the scope. The content of Global one is available throughout the website where as the local is limited to that specific page.
Step 1:Create both folders in your project as we will use them in future. To create1. Right click your project2. Then Folders3. And select both one by one.
First, we will look into Local Resources. To use the local resources file which is limited to the page level, let’s first decide what we want to do.Scenario: We want to create a login page for two languages English (US) and French.
Step 2:To do this, we need to design a page which looks like as follows (design view). The page name will be defult.aspxsnapshot_lc_1.jpg Source:<br /><asp:Label ID="lblTitle" runat="server" meta:resourcekey="lblTitle"></asp:Label><br /><br /><asp:Label ID="lblUserId" runat="server" meta:resourcekey="lblUserId"></asp:Label><asp:TextBox ID="txtUserId" runat="server" ></asp:TextBox><br /><asp:Label ID="lblPassword" runat="server" meta:resourcekey="lblPassword" ></asp:Label><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox><br /><br /><asp:Button ID="btnSubmit" runat="server" meta:resourcekey="btnSubmit"/><asp:Button ID="btnCancel" runat="server" meta:resourcekey="btnCancel" />
 Forget, those bad BR just want to give you the idea how localization work. Notice that we have not set text for any of our control specifically, Button and Labels instead we have one new thing here and that is meta:resourcekey=”btnSubmit”.Forget what it does, just continue with step 3. 
Step 3:1. Right - Click on App_LocalResources2. Click Add New Item3. From the list of template select Resource File4. Name the resource file as default.aspx.resx (because default.aspx is our page name, if it were supercool.aspx the resource file will be supercool.aspx.resx. Remember it is the default resource file for the page.)5. Make it look like following
snapshot_lc_2.jpgNow, you can see the relationship between meta:resourcekey=”btnSubmit” and resource file. Let me make it more easy, Notice the second entry from top. It isbtnSubmit.Text : Submit.It means by writing meta:resourcekey=”btnSubmit” on any control, runtime will bind all the properties specified in resource file to the that control.Just run the page we have created means default.aspx and you will see the text of all controls extracted from the default resource file. Now let’s create a new resource file for the same page but for different culture.
Step 4:1. Right - Click on App_LocalResources2. Click Add New Item3. From the list of template select Resource File4. Name the resource file as (this time we are creating resource file for our page in French. So we specify, the runtime engine understandable culture code. Please bear in mind the fr-FR is only for French to know more like this please visit Now make it look like following
snapshot_lc_3.jpgTo change the culture we need to add the following dropdown at the top of our page.
Step 5:Culture :<asp:DropDownList ID="ddlCulture" runat="server" AutoPostBack="True"><asp:ListItem Text="English" Value="en-US"></asp:ListItem><asp:ListItem Text="French" Value="fr-FR"></asp:ListItem></asp:DropDownList>And following code against this drop down.Protected Sub ddlCulture_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlCulture.SelectedIndexChangedSession("Culture") = ddlCulture.SelectedValue 'Storing culture selected in session        Response.Redirect(Request.RawUrl)End Sub
Now, we have created the drop down stuff let’s move on how to set the culture.Step 6: 

Protected Overrides Sub InitializeCulture()

        If Not Session("Culture") = "" Then            Dim selLang As String = Session("Culture")'getting the culture from session                       Page.UICulture = selLang 'setting page culture            Page.Culture = selLang               'Setting thread culture            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selLang)            Thread.CurrentThread.CurrentUICulture = New CultureInfo(selLang)        End If        MyBase.InitializeCulture()End Sub

Note : As you might notice there are two thing we are dealing with one is Culture and the other is CultureUI. Well, Culture is somthing like the Date Time / Currency of the page where is CultureUI is the UI settings for the control such as text and other proerties.
Till here, we have finished with the local resources files. Now let’s move forward and add a new resource file in App_GlobalResource, which is for the global access.
Step 7:1. Right - Click on App_GlobalResource2. Click Add New Item3. From the list of template select Resource File4. Name the resource file as MyGlobalResource.resx. (notice there is no special need for global resources)5. Now make it look like followingsnapshot_lc_4.jpgTo check Global Resources let us write following code on the click of submit button  Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.ClickResponse.Write(GetGlobalResourceObject("MyGlobalResource", "Success_Key")) '"MyGlobalResource" is the name of the classEnd Sub
That’s it, now if you press the submit button you will see the message we store in Global Resource file. Notice that, Global resource files are not culture specific and it is normally used to store things which are similar in all cultures as such images and all that.I have tried to make this post as much simple as I can, but I think it has gone quit long as the topic of Localization is not that easy to cover in 5 lines of post so I m thinking to create a video stuff for this .

Unable to start debugging on the web server. Debugging failed because integrated Windows authentication is not enabled. Please see Help for assistance.

Error : "Unable to start debugging on the web server. Debugging failed because integrated Windows authentication is not enabled. Please see Help for assistance." Fix : This error usually comes when you are using with IIS and try to debug the application. To fix it, you need to goto IIS - > Select your Virtual Directory -> Right-Click -> Properties -> Directory Security Tab -> Press the top most Edit button -> In the next form Check the lower most check box saying "Integrated Windows Authentication" and it will work.

Unable to create the Web site 'http://localhost/sitename'. An error occurred accessing your Windows SharePoint Services site files

Have you ever face the following error.
Unable to create the Web site 'http://localhost/sitename. An error occurred accessing your Windows SharePoint Services site files. Authors - if authoring against a Web server, please contact the Webmaster for this server's Web site. WebMasters - please see the server's application event log for more details.
Goto IIS -> Click Defalt Web Site -> Right Click -> Properties -> Check TCP Port If it is other then port 80 then you have to change it back to 80 and the stuff on.