Would like to set Session Timeout?

Challenge:

Before so many months back i have been assigned for a task where we need to set a session timeout for our whole application. Some enthu guys will tell it is 2 mins. job just go in web.config and do the configuration and it’s done. But let me tell you it’s not that much easy :(. Because there are two things which affects on session timeout Forms Authentication Timeout and Session Timeout
Forms Authentication Timeout Configuration
[sourcecode language=”xml”]
<system.web>
<authentication mode="Forms">
<forms timeout="50000000"/>
</authentication>
</system.web>
[/sourcecode]
Session Timeout Configuration
[sourcecode language=”xml”]
<pre><configuration>
<system.web>
<sessionState mode="InProc"
cookieless="true"
timeout="20"/>
</sessionState>
</system.web>
</configuration></pre>
[/sourcecode]

Solution

Unfortunately at tha time i haven’t written blog on it[I’m sorry for that]. But Here is the link where someone else did that already[Thanks to him!]:
http://dotnethitman.spaces.live.com/Blog/cns!E149A8B1E1C25B14!210.entry
http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx
http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.all

Good To Know on ASP.NET Application Restarts

You all may heard about ASP.NET Application restart. If no then it’s really good to know. Today i got few good links which i would like to share with you guys as well:
http://fuchangmiao.blogspot.com/2007/11/aspnet-application-restarts.html
http://blogs.msdn.com/b/johan/archive/2007/05/16/common-reasons-why-your-application-pool-may-unexpectedly-recycle.aspx
http://blogs.msdn.com/b/johan/archive/2008/02/18/monitoring-application-pool-and-application-restarts.aspx
Hope this articles clear all your questions on ASP.NET application restart. If not feel free to drop a comment here.

Generic List Sorting

Generic List has powerful sorting method which too less .Netters are aware of. Today, I would like to show it’s power to you guys!
Here we go..
Suppose, you have a Class called Employee and created collection of employees using Generic List as shown below:
[sourcecode language=”csharp”]
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public Employee(int employeeId, string employeeName)
{
EmployeeID = employeeId;
EmployeeName = employeeName;
}
public override string ToString()
{
return EmployeeID + " :- " + EmployeeName;
}
}
List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee(2, "Sachin T"));
employeeList.Add(new Employee(1, "Anil K"));
[/sourcecode]
Now, if you need to sort your employees collection by EmployeeID how will you do it? – I know i know you will write your logic and do so many things..But hold on how it will be if we can do it in just one line? sounds cool na? Here you go:
[sourcecode language=”csharp”]
Console.WriteLine(">>>>>>>>>>Before Sorting<<<<<<<<<<");
foreach (Employee employee in employeeList)
{
Console.WriteLine(employee.ToString());
}
// Sorting – Anonymous method
employeeList.Sort(delegate(Employee employee1, Employee employee2)
{ return employee1.EmployeeID.CompareTo(employee2.EmployeeID); });
Console.WriteLine(">>>>>>>>>>After Sorting<<<<<<<<<<");
foreach (Employee employee in employeeList)
{
Console.WriteLine(employee.ToString());
}
/* Output
>>>>>>>>>>Before Sorting<<<<<<<<<<
2 :- Sachin T
1 :- Anil K
>>>>>>>>>>After Sorting<<<<<<<<<<
1 :- Anil K
2 :- Sachin T
Press any key to continue . . .
*/
[/sourcecode]

Links

http://weblogs.asp.net/dwahlin/archive/2007/04/23/The-Power-of-Anonymous-Methods-in-C_2300_.aspx

Embed Almost any Document on Your Website

Challenge:

one of my friend asked me that how can i embed any document on a webpage? gotcha? Nope? okay let me elaborate functionality in a brief.

1. User can post/upload articles on portal in any format. e.g. .PPT,.PPTX,.DOC,.XLS,.XLSX, PDF.

2. Once uploaded after that user can preview his/her uploaded articles in read only format and in same format on Webpage only. No download required.

This is the big challenge! After searching a bit we found a good site and implemented it. I know you guys are eager to know. how? Okay here you go..

Solution:

There is a nice site called http://embedit.in which supports all our requirements – really great stuff by site developers!

It supports embedding document using three ways:

1. Uploading document manually :- Visit http://embedit.in/ and upload your document.

2. using embedit API :- Visit http://embedit.in/api and you can do all operations programmatically. Wow!! And you can sign in using any of the below option. No new form you need to fill up 🙂

image

3. SiteWide :-  Use Sitewide to automatically convert all the links to documents in your website to embeds. You just need to put Javascript reference in your HTML content and rest will be managed by Embedit guys! isn’t is great? So, hurry visit : http://embedit.in/sitewide and have fun!

Our Main Hero is SiteWide – which helped us in fulfilling our requirement.

I know you are eager to see it in action before using it.here you go..

image

image

Looks great na? would like to see within your browser? see this example page : http://embedit.in/sitewide/example

Thanks to my friend for throwing this challenge to me and thanks to Google for searching out embedit.in for me and thanks to embedit.in for developing such a nice functionality!

Happy embedding! 🙂

Webliography

http://go4webapps.com/2010/04/29/embedit-in-embed-any-document-file-or-webpage-in-your-blog-profile-or-website/

http://www.blogsolute.com/embed-documents-word-ppt-pdf-psd-xls/2838/

VS 2008/2010 Certification Path

Hello All, After getting loads of FAQ’s on my blog entries Milestone MCPD Exam Cleared and New Milestone MCTS Web 70-528. Today i got few diagrams from MS Site. Which contains great piece of information and answers so many questions of newbie – who would like to give certification exams. So, here we go..

VS 2008 Certifications Path

VS2008_Certification_Path

Source Link: http://download.microsoft.com/download/B/6/6/B66B006F-50AB-493E-BEBE-FD3B1BF548F6/VisualStudio2008_CertPath.pdf

VS 2010 Certifications Path

VS2010_Certification_Path

Source Link: http://download.microsoft.com/download/B/D/D/BDD81000-E7E6-4B7A-A213-8579369FB0AF/VisualStudio2010_CertPath.pdf

If you still have any question feel free to drop me a comment here!

Happy Certificating! 🙂

Resources

http://www.microsoft.com/learning/en/us/certification/view-by-technology.aspx

http://www.microsoft.com/learning/en/us/certification/cert-vstudio.aspx#tab3

Session lost in Iframe

Challenge:

I have one page called “Parent.aspx” which is hosted on parent domain let’s say : http://www.parent.com/parent.aspx and it contains child page “ChildPage.aspx” using IFRAME and hosted on another domain let’s say : http://www.child.com/childpage.aspx . Now if childPage is using session then it won’t work.
Why? Read What MS Says:
SYMPTOMS
If you implement a FRAMESET whose FRAMEs point to other Web sites on the networks of your partners or inside your network, but you use different top-level domain names, you may notice in Internet Explorer 6 that any cookies you try to set in those FRAMEs appear to be lost. This is most frequently experienced as a loss of session state in an Active Server Pages (ASP) or ASP.NET Web application. You try to access a variable in the Session object that you expect to exist, and a blank string is returned instead.
You also see this problem in a FRAMEs context if your Web pages alternate between the use of Domain Name System (DNS) names and the use of Internet Protocol (IP) addresses.
CAUSE
Internet Explorer 6 introduced support for the Platform for Privacy Preferences (P3P) Project. The P3P standard notes that if a FRAMESET or a parent window references another site inside a FRAME or inside a child window, the child site is considered third party content. Internet Explorer, which uses the default privacy setting of Medium, silently rejects cookies sent from third party sites.

Solution:

You can add a P3P compact policy header to your child content, and you can declare that no malicious actions are performed with the data of the user. If Internet Explorer detects a satisfactory policy, then Internet Explorer permits the cookie to be set.
Visit the following MSDN Web site for a complete list of satisfactory and unsatisfactory policy codes:
Privacy in Internet Explorer 6
http://msdn.microsoft.com/workshop/security/privacy/overview/privacyie6.asp (http://msdn.microsoft.com/workshop/security/privacy/overview/privacyie6.asp)
A simple compact policy that fulfills this criteria follows:
P3P: CP=”CAO PSA OUR”
This code sample shows that your site provides you access to your own contact information (CAO), that any analyzed data is only “pseudo-analyzed”, which means that the data is connected to your online persona and not to your physical identity (PSA), and that your data is not supplied to any outside agencies for those agencies to use (OUR).
Now, let’s see solution of it. There are many ways to solve it:
1.  Using Server-Side Code:
You can set this header if you use the Response.AddHeader method in an ASP page. In ASP.NET, you can use the Response.AppendHeader method
Source : http://petesbloggerama.blogspot.com/2007/08/aspnet-loss-of-session-cookies-with.html
[sourcecode language=”csharp”]
An easy fix is to add the header in Global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("p3p", "CP=\"CAO PSA OUR\"");
}
[/sourcecode]
2. You can use the IIS Management Snap-In (inetmgr) to add to a static file:
Follow these steps to add this header to a static file:

  1. Click Start, click Run, and then type inetmgr.
  2. In the left navigation page, click the appropriate file or directory in your Web site to which you want to add the header, right-click the file, and then click Properties.
  3. Click the HTTP Headers tab.
  4. In the Custom HTTP Headers group box, click Add.
  5. Type P3P for the header name, and then for the compact policy string, type CP=…, where “…” is the appropriate code for your compact policy.

Alternatively, Internet Explorer users can modify their privacy settings so that they are prompted to accept third party content. The following steps show how to modify the privacy settings:

  1. Run Internet Explorer.
  2. Click Tools, and then click Internet Options.
  3. Click the Privacy tab, and then click Advanced.
  4. Click to select the Override automatic cookie handling check box.
  5. To allow ASP and ASP.NET session cookies to be set, click to select the Always allow session cookies check box.
  6. To receive a prompt for any type of third party cookie, click Prompt in the Third-party Cookies list.

3. Use IBM’s P3P Editor[http://www.alphaworks.ibm.com/tech/p3peditor/] For more info follow nice articles given below:
http://everydayopenslikeaflower.blogspot.com/2009/08/how-to-create-p3p-policy-and-implement.html
http://www.knowledgegenes.com/home.aspx?kgid=9103&nid=52

References

http://support.microsoft.com/kb/323752/en-us
http://petesbloggerama.blogspot.com/2007/08/aspnet-loss-of-session-cookies-with.html
http://forum.developers.facebook.com/viewtopic.php?pid=204805 — Good Thread to Read
Happy IFraming! 🙂

How to use System.Diagnostics.Stopwatch?

Stopwatch is a good guy provided by MS to accurately measure elapsed time.
[sourcecode language=”csharp”]
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
// Your Time Consuming Code goes here..
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
[/sourcecode]
Happy Coding! 🙂

How to get CPU Usage/Memory Usage/Physical Memory

Here are the few functions which will help you out in getting CPU Usage, Memory Usage and Physical Memory Using C#.NET[Proprietor: Yogesh Patel]:
[sourcecode language=”csharp”]
/// <summary>
/// Gets CPU Usage in %
/// </summary>
/// <returns></returns>
private double getCPUUsage()
{
ManagementObject processor = new ManagementObject("Win32_PerfFormattedData_PerfOS_Processor.Name=’_Total’");
processor.Get();
return double.Parse(processor.Properties["PercentProcessorTime"].Value.ToString());
}
/// <summary>
/// Gets memory usage in %
/// </summary>
/// <returns></returns>
private double getMemoryUsage()
{
double memAvailable, memPhysical;
PerformanceCounter pCntr = new PerformanceCounter("Memory", "Available KBytes");
memAvailable = (double) pCntr.NextValue();
memPhysical = getPhysicalMemory();
return (memPhysical – memAvailable) * 100 / memPhysical;
}
/// <summary>
/// Gets total physical memory
/// </summary>
/// <returns></returns>
private double getPhysicalMemory()
{
ObjectQuery winQuery = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);
double memory = 0;
foreach (ManagementObject item in searcher.Get())
{
memory = double.Parse(item["TotalPhysicalMemory"].ToString());
}
return memory;
}
[/sourcecode]
Please note that on INTERNET there are so many functions available but this is most accurate and perfect. We are using it on our production servers.

How to Debug XSLT on the fly

Challenge:

one of my friend asked me how to Debug XSLT at runtime. Means if i have one XML and XSLT and my code does parsing of  XML at run time using XSLT using XSLCompiledTransform Class with some parameters which are coming dynamic. Here’s the way to do it:

Solution:

Basic requirement is that you MUST be using XSLCompiledTransform for Transformation. If you are not using it then use it. It’s really great class.
1. Locate your Transformation code.
2. locate your XslCompiledTransform class’s instantiation code e.g.
// Enable XSLT debugging. true is the guy who does the magic
XslCompiledTransform xslt = new XslCompiledTransform(true);
3. Now go to  your Transform method and put breakpoint.
xslt.Transform(sourceFile, null, outputStream); //PUT Breakpoint on me!
4. Run your code in DEBUG mode and when BreakPoint comes at Transform method press F11 for stepping in to the code.
Happy Debugging!
NOTE : Please disable debugging (XslCompiledTransform xslt = new XslCompiledTransform();) once your code is ready for deployment

Reference :

http://msdn.microsoft.com/en-us/library/ms255603(VS.80).aspx

TreeView.FindNode with PopulateOnDemand feature

Challenge:

If you are using Tree View with PopulateOnDemand feature – for those who are new to PopulateOnDemand feature – It Indicates whether the node is populated dynamically for example if you have tree structure as below:

imageNow, Normally you can bind above tree view on page load directly with all child nodes. But if you have huge data then it will affect performance. So, to avoid performance issue we use PopulateOnDemand feature as name suggests Nodes will be populated on demand only[on click of + sign]. Now our new data binding code will load all root nodes only and set it’s PopulateOnDemand property to true as shown here:

Markup code

<asp:TreeView ID="LinksTreeView" Font-Names="Arial" ForeColor="Blue" OnTreeNodePopulate="PopulateNode"
           SelectedNodeStyle-Font-Bold="true" SelectedNodeStyle-ForeColor="Chocolate" runat="server">
       </asp:TreeView>

Code-Behind

protected void Page_Load(object sender, EventArgs e)
    {  
        if (!IsPostBack)
        {
            // bind first level tree
            TreeNode treeNode1 = GetTreeNode("1");
            treeNode1.Expanded = false;
            LinksTreeView.Nodes.Add(treeNode1);

            TreeNode treeNode2 = GetTreeNode("2");
            treeNode2.Expanded = false;
            LinksTreeView.Nodes.Add(treeNode2);

            TreeNode treeNode3 = GetTreeNode("3");
            treeNode2.Expanded = false;
            LinksTreeView.Nodes.Add(treeNode3);

            // collapse all nodes and show root nodes only
            LinksTreeView.CollapseAll();
        }
    }

private static TreeNode GetTreeNode(string nodeTextValue)
    {
        TreeNode treeNode = new TreeNode(nodeTextValue, nodeTextValue);
        treeNode.SelectAction = TreeNodeSelectAction.SelectExpand;
        treeNode.PopulateOnDemand = true;
        return treeNode;

    }

protected void PopulateNode(Object sender, TreeNodeEventArgs e)
    {

        // Call the appropriate method to populate a node at a particular level.
        switch (e.Node.Text)
        {
            case "1":
                // Populate the first-level nodes.
                e.Node.ChildNodes.Add(GetTreeNode("1.1"));
                e.Node.ChildNodes.Add(GetTreeNode("1.2"));
                e.Node.ChildNodes.Add(GetTreeNode("1.3"));
                break;
            case "2":
                // Populate the second-level nodes.               
                e.Node.ChildNodes.Add(GetTreeNode("2.1"));
                e.Node.ChildNodes.Add(GetTreeNode("2.2"));
                e.Node.ChildNodes.Add(GetTreeNode("2.3"));
                break;
            case "3":
                // Populate the third-level nodes.               
                e.Node.ChildNodes.Add(GetTreeNode("3.1"));
                e.Node.ChildNodes.Add(GetTreeNode("3.2"));
                e.Node.ChildNodes.Add(GetTreeNode("3.3"));
                break;
            case "1.1":
                // Populate the first-level nodes.
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.2"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.3"));
                break;
            case "1.1.1":
                // Populate the first-level nodes.
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1.1"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1.2"));
                e.Node.ChildNodes.Add(GetTreeNode("1.1.1.3"));
      
          break;
            default:
                // Do nothing.
                break;
        }
    }

Great! Now we are ready just run your application and see the power of PopulateOnDemand feature. Whenever you expand any node[by clicking on plus sign] it will call PopulateNode Method because in tree view’s markup we have binded it.

Now, the main problem is here. Suppose you have a requirement in which you have to find 1.1.1.1 Node –which is at path 1/1.1/1.1.1/1.1.1.1. You will shout and say use TreeView’s FindNode method and provide path like this :

LinksTreeView.FindNode(“1/1.1/1.1.1/1.1.1.1”);

can you pls give a try and check does it works? it won’t because I’ve already tried 🙂 let me tell you why – Because 1.1.1.1 node is not loaded yet and it’s parent node 1.1.1 is also not loaded yet and so on still 1.1. Just 1 has been loaded. So, let’s see how we can solve this challenge:

Solution:

After goggling a bit and braining a lot i found the following way:

Main aim is to load 1.1.1.1 but it’s the last node and to load it all it’s parent’s should be first loaded. Here’s the simple way of doing it:

LinksTreeView.FindNode(“1”).Expand(); // it will find node and call expand method so it will load 1.1 which is first child of 1

LinksTreeView.FindNode(“1/1.1”).Expand();  //loads 1.1.1

LinksTreeView.FindNode(“1/1.1/1.1.1”).Expand(); //loads 1.1.1.1

LinksTreeView.FindNode(“1/1.1/1.1.1/1.1.1.1”).Expand(); //Cheers we reached there!

Now, above code is bit hard-coded and i am against of hard-coding so wrote one generic method which works for any level of node finding[txtPath is one textbox which provides path to find]

protected void btnSelect_Click(object sender, EventArgs e)
   {  
       //It will not work because as it is populateondemand
       //this call will never find node because of populateondemand
       TreeNode foundNode = LinksTreeView.FindNode(txtPath.Text);
       if (foundNode == null)
       {
           // Now i am doing different way
           string selecteValuePath = txtPath.Text;
           string[] selectedValues = selecteValuePath.Split(LinksTreeView.PathSeparator);

           string findValueQuey = string.Empty;
           for (int counter = 0; counter < selectedValues.Length; counter++)
           {
               string fValuePath = string.Empty; ;
               if (counter == 0)
               {
                   // store 1
                   fValuePath = selectedValues[counter];
               }
               else if (counter < selectedValues.Length)
               {
                   // now path is 1/1.1
                   fValuePath = findValueQuey.ToString()
                       + LinksTreeView.PathSeparator
                       + selectedValues[counter];
               }

               //1/1.1/1.1.1/1.1.1.1
               foundNode = LinksTreeView.FindNode(fValuePath);

               if (foundNode != null)
               {
                   foundNode.Expand(); //loads child node
                   foundNode.Select();
                   // stored 1
                   // stored 1/1.1
                   findValueQuey = fValuePath;
               }               
           }
       }
       else
       {
           Response.Write("Node found : " + foundNode.Value);
       }
   }

Happy Node Finding!