Sunday, September 18, 2011

Forms authentication failed for the request. Reason: The ticket supplied was invalid.

When was the last time you saw this message ??? (just kidding)

If you drill down to the EventViewer logs you"ll probably see this code

Event code: 4005 Event message: Forms authentication failed for the request. Reason: The ticket supplied was invalid.

Now most people think that this is due to the machine keys in the machine.config file but actually this is due the expiration of a valid ticket which was for a short duration.

After the expiration, the users would need to again sign-on and this makes the user experience even worse. To fix this issue, you need to increase the validity of the ticket by using the sample below

FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, "usercookie", DateTime.Now, DateTime.Now.AddMinutes(120), false);

Difference between Thread and ThreadStart delegate

I have been working since .Net 1.1, the way we create/spawn threads is

1. Create a ThreadStart delegate for parameter less target method or Create a ParameterizedThreadStart delegate for target accepting parameters. 2. The next step was to create a Thread object and pass this delegate. 3. Lastly call the Start method to execute the thread.

This was the norm till .Net 2.0. What seems confusing now is that, from ver. 2.0 we can directly pass the target to the Thread's constructor and call the Start method !!!

Well this is due to the enhancement which .Net 2.0 onwards have to offer. Instead of going the way we did above in 1.1, the compiler now invokes the appropriate delegate based on the target passed.

So technically speaking both the approaches below are the same.

1. ThreadStart ts = new ThreadStart(Somework); // .Net 1.1 way of creating threads Thread t = new Thread(ts); t.Start();

2. Thread t = new Thread(Somework); // .Net 2.0 onwards way of creating threads t.Start();

Happy coding :)

Sunday, July 10, 2011

How to access files, folders and other local resources through .net

Applications these days may require to access local resources such as folders on disk, creating/deleting files, etc. I came across one such scenario wherein the application had to create a file on remote location and then periodically delete the file(2 days after file creation).

In this scenario, assume without the application in picture, an user creates a file. This seems pretty much simple though, but what I want to tell here is the sequence of events.

1. An user navigates to the location ( a folder on remote machine)
2. Create a file
3. Save the file.

These 3 events though straightforward, make an important assumption, and that is, the user is having access to create file.

When it comes to your .Net application, the application is running under the user of a lesser privilege (that's CAS for you) or Code Access Security. So most of the times it won't have the privilege to create a file.

To fix this either you have to grant the application account with the required privilege OR you can MAKE the application run on the privilege of a specific user.

So under which username does the .Net app really work ??-- Its Network Service for remote apps and ASPNET on local machines.

As discussed you can grant these users, depending on the scenario, access to the required folders and you're done. But theres a trap... All the .Net apps will now have access to this folder since all of them run by Network Service/ASPNET accounts.

It may happen that you have to restrict the access to such folders, then, you have only one option...execute the application under the context of a specific user who has access to only that location. To get this done, you need to explore WindowsImpersonation class. Below is the link with code sample

WindowsImpersonation class

With this class you can provide the username/password of the specific user account you want the application to execute and then reset the identity so that the rest of the application code works under the restricted .Net account.

Happy Coding :)

Friday, May 27, 2011

How to Format Date in CustomCalendarExtender control

The default date format for the CustomCalendarExtender is MM/dd/yyyy which is typically US date format. To change this format, you need to set the Format property of the control.

For UK based date format you can set this to dd/MM/yyyy which would display date as 19/03/2011 instead of 03/19/2011 (default format)


Happy Coding :)

Implementing Transactions in WCF

In synchronous communication (request-response-acknowledge) we generally refer to the response HTTP code to determine a successful transaction. But in some cases it might happen that an acknowledgement be sent to the server which will store this value in the database.

A typical scenario would be of file download process wherein the client needs to send the acknowledgement which stored in database for future use. For this you need to implement Transaction in WCF. To do this, you can use the TransactionScope class or you can use the OperationBehaviour attribute in WCF as below

[OperationBehavior(TransactionScopeRequired = true)]

This would require your web-method to execute as a part of transaction. Having done that, you can now return a Boolean value (True/False) as a result depending on the status of the download process. This value can then be stored in the database in Boolean/Bit format for future reference.

Happy Coding :)

Sunday, April 3, 2011

Configuring your web application for Windows domain users

To provide authentication mechanism on Intranet websites is pretty easy. Use LDAP and all the users accessing your application on the Intranet get authenticated automatically. But how to achieve this in the internet scenario ??

It might happen that your application needs to be SCALABLE to allow your Windows domain users to access the website from internet. To achieve this, you just need to tweak the webconfig a bit with the entries shown below




Happy Coding :)

Solution for System.IO.IOException: The device is not ready. error

Many times our applications refer a file on disk. At the time of development, most of the developers refer to the file by it's absolute path.

The trap here is, the absolute path on the development environment most of the times differ from the path on the deployment server. So though you're able to build and ship the DLLs you will always encounter a runtime error. Thats simply because the AppDomain is not able to locate the file from the path you mentioned. Moreover, the path does not exist in itself :P

So to get rid of this scenario always use Server.MapPath which would resolve the file path on the server. Also refer the url below for code snippets.
Server.MapPath example

Happy Coding :)

Saturday, February 19, 2011

How to use different target framework in Visual Studio 2010

In VS 2010 there is one beautiful feature wherein you can execute your legacy applications along with your new apps. This is possible because of the multi-targeting feature available in VS 2010.

Now you can decide which .Net Framework to use for your code through VS 2010.
Just Go to Solution Explorer -> Properties -> Build -> Target Framework.

You're done with it !!!

How to fetch value from dynamically created control

There are some cases wherein you can not create the controls to display data at compile time. For example, displaying values from a Hashtable in a TextBox control, you never know how many key-pairs you are going to deal with (provided the Hashtable contains dynamic data). The logic for displaying the data is pretty much simple. You create an array of TextBoxes or any other control to display the data and you are done with it.

But the main problem lies in fetching the data which might have got changed from the UI. If you try to find out the TextBox controls from Page.FindControl() you won't be able to do so, thats because there isn't any markup for the FindControl() to look for and thats why it will always be null.

So to tide over your problem you can simple fetch the value from just one line

Request.Form[yourcontrolID]

The Request object as we all know is base of the web architecture. So whatever is being communicated between client and a Server has to have its presence in the Request object. Technically speaking whatever controls you can find in the html markup of you page on the client side will be available in this Request object.

Happy Coding :)

Saturday, January 8, 2011

Compatibility between data types in Java and .Net

Recently I came across an interesting scenario where a Java app was consuming a .Net webservice. The challenge here was to consume a DataSet returned from a webmethod written in .Net to the calling Java UI.

One approach is to return the data in plain XML which can be done by GetXML() of the dataset but this was not acceptable. So I did a search on some similar scenarios and found out one link which lists the compatibility between different data types .. sor of a rule book you can use when you have Java UI/.Net webservice to a .Net UI/Java webservice.

http://msdn.microsoft.com/en-us/netframework/gg413252

Happy coding :)

Tree node event for fetching the selected node

Back after one year of CHANGE !!!

A few days ago one of my friend had a question about tree node, he wanted to copy the text of selected node else the app should not copy. So I did some R&D on events available with tree node. Its the OnSelectedNodeChanged..


Here is sample code for the same :)
 *********ASPX Code****************


   
   


   

   

       
   

       
            OnTreeNodeExpanded="TreeView1_TreeNodeExpanded"
            onselectednodechanged="TreeView1_SelectedNodeChanged">
       

   

   



***************************************

*****Code behind***********


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind_tree();
        }
    }
    public void Bind_tree()
    {
        DataTable dt = Get_District();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            TreeNode no = new TreeNode();
            no.Text = dt.Rows[i]["District"].ToString();
            no.Value = dt.Rows[i]["District"].ToString();
            Get_allNodes(no);
            this.TreeView1.Nodes.Add(no);
        }
    }
    public void Get_allNodes(TreeNode no)
    {
        DataTable dt = Get_Arealist();
        DataRow[] rows = dt.Select("District='" + no.Value + "'");
        for (int i = 0; i < rows.Length; i++)
        {
            TreeNode child = new TreeNode();
            child.Text = rows[i]["Area"].ToString();
            child.Value = rows[i]["Area"].ToString();
            no.ChildNodes.Add(child);
            Get_allNodes(child);
        }
    }


    // You can get the data from your own database.
    // I get the datatable like this in order to run the sample more conveniently.
    public DataTable Get_District()
    {
        DataTable dt = new DataTable();
        DataRow dr;
        string Name = "District_1,District_2,District_3";
        string ID = "1,2,3";
        string[] list1 = Name.Split(',');
        string[] list2 = ID.Split(',');
        dt.Columns.Add(new DataColumn("District"));
        dt.Columns.Add(new DataColumn("ID"));
        for (int i = 0; i < list1.Length; i++)
        {
            dr = dt.NewRow();
            dr["District"] = list1[i];
            dr["ID"] = list2[i];
            dt.Rows.Add(dr);
        }
        return dt;
    }

    // You can get the data from your own database.
    // I get the datatable like this in order to run the sample more conveniently.
    public DataTable Get_Arealist()
    {
        DataTable dt = new DataTable();
        DataRow dr;
        string Name = "Area_1,Area_2,Area_3,Area_4,Area_5";
        string Dis = "District_1,District_1,District_1,District_3,Area_1";
        string ID = "1,2,3,4,5";
        string[] list1 = Name.Split(',');
        string[] list2 = Dis.Split(',');
        string[] list3 = ID.Split(',');
        dt.Columns.Add(new DataColumn("Area"));
        dt.Columns.Add(new DataColumn("District"));
        dt.Columns.Add(new DataColumn("ID"));
        for (int i = 0; i < list1.Length; i++)
        {
            dr = dt.NewRow();
            dr["Area"] = list1[i];
            dr["District"] = list2[i];
            dr["ID"] = list3[i];
            dt.Rows.Add(dr);
        }
        return dt;
    }
    protected void TreeView1_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
    {
        TreeNodeCollection ts = null;
        if (e.Node.Parent == null)
        {
            ts = ((TreeView)sender).Nodes;
        }
        else
            ts = e.Node.Parent.ChildNodes;
        foreach (TreeNode node in ts)
        {
            if (node == e.Node)
            {
                node.Expand();
            }
            else
            {
                node.Collapse();
            }
        }

    }
    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        TreeNodeEventArgs xm = new TreeNodeEventArgs(this.TreeView1.SelectedNode);
        TreeView1_TreeNodeExpanded(sender, xm);
        string value = this.TreeView1.SelectedNode.Text;
        this.Label1.Text = value;
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Ming", "Getvalue('" + value + "')", true);
    }



Happy Coding :)

Monday, January 4, 2010

How to debug Windows service

In web apps we generally press F5 or attach the process for debugging but what to do when it comes to Windows services ???

You"ll come across docs which tell you to do loads of steps for that, but I prefer the most easy way ;)

The process of attaching debugger can be done in just ONE simple line. Use

System.Diagnostics.Debugger.Launch()

The Launch() is a static method of Debugger class. It initializes the debugger.

Now where to put this line ?? Well I prefer in the OnStart() of the Windows service which acts as a starting point of the service.

So you are all set with debugging the Windows service. Happy Debugging :)

How to disable the default progress image of Infragistics webgrid

Hi, today I faced a unique challenge and that was to disable the default progress image on the Infragistics webgrid. Now if you try to sort the column by clicking on its header you see a small image in the middle of the grid...thats the progress image am talking about.

In my case the requirement was to show a custom progress-bar image, so I had to disable the default one.
Heres what I did.

1. Call a method from the InitializeLayout() of the grid on the server-side
Eg:- e.Layout.ClientSideScript.InitializeLayoutHandler =

2. Now the method signature in this case takes two arguments by default, thats comes pre-defined from Infragistics. The first parameter is the grid-name and the second is the columnID. So if your method name is DisableImage, then its signature in the javascript file will look like this

function DisableImage(gridName, colID)
{ }

3. Now what code should I use ??? This is the most important part. Use the code below as-is and your problem is solved

var oGrid = igtbl_getGridByID(gridName);
oGrid.DisableProgressIndicator();

Wholla done !!!!

Friday, December 25, 2009

How to enable connection pool in MS Access

I found out a property in the connection string with which you can enable connection pool while using MS Access as your database

Provider=Microsoft.Jet.OLEDB.4.0;OLE DB Services=-1;Datasource=Filename.mdb

The property in the red color will enable connection pooling. The reason to suggest this is it improves the performance remarkably.

Distributed transaction error in SQL Server 2005

I have seen problems like below popping up in the SQL Server 2005



Now the message sounds a bit confusing, the reason why I say so is you will be able to connect to the database and test the connection as well. But when you execute any query through your app you"ll get this message.... sounds interesting isn't it ??

The actual reason to this scenario is because SQL Server 2005 by default does not allow remote connections. To enable remote connections follow the steps below

1. Start > All Programs > Microsoft SQL Server 2005 > Configuration Tools> Surface Area Configuration
2. Select Surface area Configuration for Sercies and Connections
3. Click Root Sql Express > Database Engine > Remote Connection .
Select Local and Remote Connection
Select Using both TCP/IP only
Click OK/Apply

Tuesday, November 25, 2008

Drawbacks in webservices (.Net) asmx files

Hi,
Heres some crisp analysis about web services implemented on .Net platform. Over a period of time using this technology, I found these observations

1. An ASMX page contains a complete set of information that describes how the data will be formatted, how to wrap the data in a SOAP header, and how to prepare it to be sent. However, it doesn’t tell you how to deliver it over the transports and to use a specific type of security.

2. ASMX provides the way for interoperability but doesn’t fulfill some of the basic requirements; for example, it does not provide or guarantee end-to-end security or reliable communication

3. Another limitation of ASMX is the tight coupling with the HTTP runtime and the dependence on IIS to host it.

4. ASMX service is instantiated on a per-call basis