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!

Stable Sort with C#

Hi Guys before couple of days only i came to know that  the Sort methods used by the .NET collections are unstable. These sort methods, which include System.Array.Sort and System.Collections.Generic.List<T>.Sort, use the Quick Sort algorithm, which is relatively fast but in this case, unstable. However, there may be instances where you require a stable sort, so a custom solution is required. Let me explain you by an example:
Program.CS
[sourcecode language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace GenericSortingDemo
{
class Program
{
static void Main(string[] args)
{
// 19 – May – 1977
Employee empHemang = new Employee(5, "Hemang Shah", DateTime.Parse("05/19/1977"));
// 19 – May – 1987
Employee empDarshak = new Employee(2, "Darshak Shah", DateTime.Parse("05/19/1985"));
// 30 – Jan – 1987
Employee empDevang = new Employee(1, "Devang Udeshi", DateTime.Parse("01/30/1987"));
// 30 – Jan – 1987
Employee empNilesh = new Employee(4, "Nilesh Thakkar", DateTime.Parse("01/30/1987"));
// 19 – Aug – 1987
Employee empKiran = new Employee(3, "Kiran Patil", DateTime.Parse("05/19/1987"));
Console.WriteLine("********************ArrayList***********************");
ArrayList empArrayList = new ArrayList();
empArrayList.Add(empHemang);
empArrayList.Add(empDevang);
empArrayList.Add(empNilesh);
empArrayList.Add(empDarshak);
empArrayList.Add(empKiran);
Console.WriteLine("ArrayList – Before sorting");
foreach (Employee emp in empArrayList)
{
Console.WriteLine(emp.ToString());
}
empArrayList.Sort(new MySorter());
Console.WriteLine(Environment.NewLine);
Console.WriteLine("ArrayList – After sorting");
foreach (Employee emp in empArrayList)
{
Console.WriteLine(emp.ToString());
}
Console.WriteLine(Environment.NewLine);
Console.WriteLine("********************Generics***********************");
// Genercis
List<Employee> lstEmployees = new List<Employee>();
lstEmployees.Add(empHemang);
lstEmployees.Add(empDevang);
lstEmployees.Add(empNilesh);
lstEmployees.Add(empDarshak);
lstEmployees.Add(empKiran);
Console.WriteLine("List<Employee> – Before sorting");
foreach (Employee emp in lstEmployees)
{
Console.WriteLine(emp.ToString());
}
// sort employees in asc order
lstEmployees.Sort(delegate(Employee emp1, Employee emp2)
{ return emp1.EmployeeBirthDate.CompareTo(emp2.EmployeeBirthDate); });
Console.WriteLine(Environment.NewLine);
Console.WriteLine("List<Employee> – After sorting");
foreach (Employee emp in lstEmployees)
{
Console.WriteLine(emp.ToString());
}
}
}
public class Employee
{
public Employee(int employeeID,string employeeName,DateTime employeeBirthDate)
{
EmployeeID = employeeID;
EmployeeName = employeeName;
EmployeeBirthDate = employeeBirthDate;
}
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public DateTime EmployeeBirthDate { get; set; }
public override string ToString()
{
return "Employee ID : " + EmployeeID + " Employee Name : " + EmployeeName + " Employee BirthDate : " + EmployeeBirthDate;
}
}
public class MySorter : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
Employee emp1 = x as Employee;
Employee emp2 = y as Employee;
DateTime dtEmpl = emp1.EmployeeBirthDate;
DateTime dtEmp2 = emp2.EmployeeBirthDate;
int num = dtEmpl.CompareTo(dtEmp2);//by default ascending order
return num;
}
#endregion
}
}
[/sourcecode]

Output

clip_image002
In their original order [Before sorting], Devang (1/30/1987) appears before Nilesh (also 1/30/1987). But because both objects have the same BirthDate, and the List<T>.Sort and Array.Sort method is unstable, the order of equal objects is reversed. Nilesh appears before Devang after sorting.
Q. Why it happens technically?
Ans: The Sort methods used by the .NET collections are unstable. These sort methods, which include System.Array.Sort and System.Collections.Generic.List<T>.Sort, use the Quick Sort algorithm [We all must have learnt in college days 🙂 DS lectures], which is relatively fast but in this case, unstable. However, there may be instances where you require a stable sort
[Source: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx], so a custom solution is required. – And the custom solution is “Stable Insertion Sort” – is the best way to do stable sorting [Source: http://www.csharp411.com/c-stable-sort/]
Happy Stable Sorting!

Setting up Dual wallpaper on dual monitors

if you are using dual monitors and you would like to set up dual wallpapers on both the monitors. Then it’s not directly possible. I know that there is something called NView from NVIDIA. But i didn’t liked it too much. It’s my personal view.
After googling a bit i found nice tool called “wallmaster” which is free and source is also available at codeplex :
http://wallmaster.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=23483
WallMaster 0.1.3 Download

Remote desktop in the same session

Challenge:

I want to access my machine from another machine using Remote desktop with the same credentials at both the places. But when i do remote desktop from another machine using “mstsc” and my Machine Name then it gives me new session. But i want my same old session as i have so many programs runing on it and so many files are open. Pls note that i am doing this using Windows Server 2003.

Solution:

I googled it bit. But in the mean time one of my colleague told me to use “mstsc /console” to access the same session. And it’s working :). Then i read a bit and found that in Windows XP it will always give you console mode — means if user is same then same session will be given. While in Windows Server 2003 you have to use “mstsc /console”. Here are the steps:
1. Go to Run(Window + R).
2. type “mstsc /console”. [Without quotes]
3. Which will open Remote Desktop connection dialgobox. Provide computer as your machine name/ip address on which you would like to connect.
4. Provide the credentials[pls note that credentials should be the same means if on A machine X user is logged in then from B machine X user should log in].
5. That’s it!
Happy Remoting! 🙂

Object dosen't support this property or method with showModalDialog

Challenge:

We’re trying to open Modal Window from Modal Window on button click which is inside update panel:
[sourcecode language=”csharp”]
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Button1, page.GetType(), "OpenModalDialog", "<script type=text/javascript>window.showModalDialog(‘http://www.gooogle.com, null, ‘dialogHeight:100px;dialogWidth:280px;status:no’); </script>", false);
}
[/sourcecode]
But it was giving an error Object dosen’t support this property or method

Solution:

Pls  check that pop-up blocker is not active. [Tools | Pop-Up Blocker|Turn-off Pop-up Blocker].

Exceeded storage allocation. The server response was: 5.7.0 Our system detected an illegal attachment on your message.

If you are genearting zip file runtime in memory and sending mail at run time. and you faced the error as shown below:
Exceeded storage allocation. The server response was: 5.7.0 Our system detected an illegal attachment on your message.
Then to fix it, you have to do the following change in your code(Pls note I’ve used SharpZipLib and Memory Stream for sending an email at run time using gmail server):
[sourcecode language=”csharp”]
MemoryStream zipFileStream = new MemoryStream();
zipOutputStream = new ZipOutputStream(zipFileStream);
..
..
..
//read from stream and add to zipoutputstream code should go here

..
// Seek to begining — IF YOU DON’ ADD BELOW LINE IT Will give above error
zipFileStream.Seek(0, SeekOrigin.Begin);
mailMessage.Attachments.Add(new Attachment(zipFileStream, "myzipfile.zip"));
[/sourcecode]
if you’ve seen the above code. Below line says MemroyStream to seek to Begining of the stream, So when SMTP Server scans the file before sending it gets perfect file.
zipFileStream.Seek(0, SeekOrigin.Begin);
Happy Mailing!