Sunday, December 09, 2007

Client Side Script Debugging in ASP.NET

Another good article for client side script debugging in ASP.NET

http://www.beansoftware.com/ASP.NET-Tutorials/Client-Script-Debugging.aspx

HTTP Handlers and HTTP Modules in ASP.NET

Good article posted by Mansoor Ahmed Siddiqui in 15Second on HTTP Handlers and HTTP Modules in ASP.NET, see below link

http://www.15seconds.com/issue/020417.htm

Monday, November 19, 2007

How to redirect parent iframe from child iframe

How to redirect parent iframe from child iframe
 
For example while working on child page (iFrame) if session timeout then error page should refect in complate application not only child page (iFrame), to achive this please see following solutions
 
Solution-1
 
On click of child iFrame page control write following lines of code in code behind
 
Response.Write("<script>window.open('Error.aspx','_parent');</script>");
 
Solution-2
 
Write java script function in child page (iFrame) to submit parent page and set some hidden variable Now in the parent page in page load events according to hidden variable value, redirect to error page.
 
Code in child page
 
Java script function in aspx file
 
//when the session is timeout, its redirected to the home page
function RedirectError(errorMsg)
{           
window.parent.document.getElementById('hdnErrorMsg').value=errorMsg;
window.parent.document.forms.frmHome.submit();
}
 
Note: "frmHome" is parent page and "hdnErrorMsg" hidden variable declared in child page
 
Call this java script function from child page code behind
 
C# code in code behind
 
try
{
      // Code logic
}
catch (System.Security.SecurityException ex)
{
StringBuilder activateHide = new StringBuilder();
activateHide.Append("<script language='javascript'>");                activateHide.Append("RedirectError('SessionTimeout');");
activateHide.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "Contents", activateHide.ToString());
}
 
Code in Parent page
 
In the parent page (Home.aspx) code bahind page_load event handle this in if..else loop
protected void Page_Load(object sender, EventArgs e)
{
if (hdnErrorMsg.Value != "")
{
Response.Redirect("Error.aspx?ErrorMsg=" + hdnErrorMsg.Value);
}
else
{
      // Code logic
}
}
 


Never miss a thing. Make Yahoo your homepage.

Thursday, October 11, 2007

How to get Zip files contents in C# using J# libraries

How to get Zip files contents in C# using J# libraries
Let's assume this example, how to know whether .xml file present inside requested zip file or not
Reference
Right click your project in Server Explorer and click on "Add Reference" -> Select the .Net tab -> Scroll down and select "vjslib" -> Click OK and you are there.
Namespace
using java.util;
using java.util.zip;
using java.io;
Source Code
private Boolean GetZipFiles(ZipFile zipfil)
{
Enumeration zipEnum = zipfil.entries();
while (zipEnum.hasMoreElements())
{
ZipEntry zip = (ZipEntry)zipEnum.nextElement();
if (zip.ToString().ToLower().IndexOf(".xml") != -1)
{
//folder have xml file inside
return true;
}
}
return false; //folder does NOT have xml file inside
}
How to Use
page_Load()
{
ZipFile zipfile = new ZipFile(@"C:\temp.zip");
GetZipFiles(zipfile)
}
Some more functionality using J# Library
Create a ZIP file
private void Zip(string zipFileName, string[]sourceFile)
{
FileOutputStream filOpStrm = new FileOutputStream(zipFileName);
ZipOutputStream zipOpStrm = new ZipOutputStream(filOpStrm);
FileInputStream filIpStrm = null;
  foreach (string strFilName in sourceFile)
{
    filIpStrm = new FileInputStream(strFilName);
    ZipEntry ze = new ZipEntry(Path.GetFileName(strFilName));
    zipOpStrm.putNextEntry(ze);
    sbyte[]buffer = new sbyte[1024];
    int len = 0;
    while ((len = filIpStrm.read(buffer)) >= 0)
    {      zipOpStrm.write(buffer, 0, len);    }
  }
  zipOpStrm.closeEntry();
  filIpStrm.close();
  zipOpStrm.close();
  filOpStrm.close();
}
Extract a ZIP file
private void Extract(string zipFileName, string destinationPath)
{
ZipFile zipfile = new ZipFile(zipFileName);
List < ZipEntry > zipFiles = GetZippedFiles(zipfile);
foreach (ZipEntry zipFile in zipFiles)
  {
    if (!zipFile.isDirectory())
    {
      InputStream s = zipfile.getInputStream(zipFile);
      try
      {
        Directory.CreateDirectory(destinationPath + "\\" +
        Path.GetDirectoryName(zipFile.getName()));
        FileOutputStream dest = new FileOutputStream(Path.Combine
          (destinationPath + "\\" + Path.GetDirectoryName(zipFile.getName()),
          Path.GetFileName(zipFile.getName())));
        try
        {
          int len = 0;
          sbyte[]buffer = new sbyte[7168];
          while ((len = s.read(buffer)) >  = 0)
          {
            dest.write(buffer, 0, len);
          }
        }
        finally
        {
          dest.close();
        }   }
      finally {
        s.close();
     }    }  }  }
Get the contents of a ZIP file
private List < ZipEntry > GetZipFiles(ZipFile zipfil)
{
  List < ZipEntry > lstZip = new List < ZipEntry > ();
  Enumeration zipEnum = zipfil.entries();
  while (zipEnum.hasMoreElements())
  {
    ZipEntry zip = (ZipEntry)zipEnum.nextElement();
    lstZip.Add(zip);
  }
  return lstZip;
}
Reference sites

1)
http://www.c-sharpcorner.com/UploadFile/neo_matrix/SharpZip04242007001341AM/SharpZip.aspx
2) http://aspalliance.com/articleViewer.aspx?aId=1269&pId=-1
 

Wednesday, October 10, 2007

How to do Iframe auto resize according to aspx page contain

How to do Iframe auto resize according to aspx page contain
 
Supose you have one Iframe "IFrmRightMenu" and inside you are setting target for different aspx page, In this case the content of aspx page can have different height and width, If you want to set Iframe size according to aspx page contain height and width then use below function in onload attribute of iframe.
 
Source code
 
<script language="javascript">
 
function autoIFrameResize(id)
{
   var newheight;
   var the_width=572; //Fixed width      
       
   if(navigator.appName == "Microsoft Internet Explorer")
{            newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
           
      if (newheight == 0)
      {
           newheight =584; //Fixed height           
       }
        else
        {
newheight = document.getElementById(id).contentDocument.height;
        }
        
document.getElementById(id).height= (newheight + 16) + "px";
      document.getElementById(id).style.width=the_width+"px";       
window.parent.document.getElementById("IFrmRightMenu").style.height= (newheight + 16) + "px";
    }
 
</script>
 
How to use
 
<iframe frameborder="no" width="100%" height="100%" onload="autoResize('iframe1');" scrolling ="no" style="visibility:hidden;" id=" iframe1"></iframe>
 
How to redirect to Parent page from Child page (IFrame)
 
Let say you have one aspx page with two iframe (LeftIframe and RightIframe in one aspx page), now if you click any button in "RightIframe" and you want to redirect some error page or your want to redirect in home page then you can't simply write Reponse.Redirect ("error.aspx") or Reponse.Redirect ("Home.aspx"), this will display the page in "RightIframe" only.
 
Use below line of code to redirect page to Home.aspx or Error.aspx
 
Response.Write("<script>window.open('Error.aspx','_parent');</script>") OR
Response.Write("<script>window.open('Home.aspx','_parent');</script>")
 


Check out the hottest 2008 models today at Yahoo! Autos.

Friday, September 14, 2007

How to Select-Unselect and Check-Uncheck TreeView nodes and controls using javascript

How to Select-Unselect and Check-Uncheck TreeView nodes and controls using javascript

In ASP.NET if you have treeview control with check box or other controls and your requirement to select-unselect and check-uncheck all treeview nodes and controls, then I have sample javascript function to achive this.This code is compatable with all browsers (IE,Mozilla,Netscape etc.)

Scree Shot



Source code Design (How to use)

<form id="form1" runat="server">
<div>
<a id="lnkExpandAll" href="javascript:ExpandCollapseAll('tvTest',true)">Expand all</a>
<a id="lnkCollapseAll" href="javascript:ExpandCollapseAll('tvTest',false)">Collapse all</a>
<a id="lnkCheckaAll" href="javascript:CheckUnCheckAll('tvTest',true)">Check all</a><a id="lnkUncheckAll" href="javascript:CheckUnCheckAll('tvTest',false)">UnCheck all</a>
</div>
<asp:TreeView ID="tvTest" runat="server">
<Nodes>
<asp:TreeNode Text="State" Value="State">
<asp:TreeNode Text="M.H" Value="M.H">
<asp:TreeNode ShowCheckBox="True" Text="Pune" Value="Pune"></asp:TreeNode>
<asp:TreeNode ShowCheckBox="True" Text="Mumbai" Value="Mumbai"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="M.P" Value="M.P">
<asp:TreeNode ShowCheckBox="True" Text="Jabalpur" Value="Jabalpur"></asp:TreeNode>
<asp:TreeNode ShowCheckBox="True" Text="Indore" Value="Indore"></asp:TreeNode>
</asp:TreeNode>
<asp:TreeNode Text="U.P" Value="U.P">
<asp:TreeNode ShowCheckBox="True" Text="Kanpur" Value="Kanpur"></asp:TreeNode>
<asp:TreeNode ShowCheckBox="True" Text="Patna" Value="Patna"></asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
</form>

JavaScript Code

<script language="javascript" type="text/javascript">

//This function will check and uncheck all check box depends upon mode true/false;
function CheckUnCheckAll(treeViewId,mode)
{
var treeView = document.getElementById(treeViewId);
var treeLinks = treeView.getElementsByTagName("input");

for (var iCounter=0; iCounter< treeLinks.length; iCounter++)
{
if (treeLinks[iCounter].type=="checkbox" && mode)
{
treeLinks[iCounter].checked=true;
}

if (treeLinks[iCounter].type=="checkbox" && !mode)
{
treeLinks[iCounter].checked=false;
}
}
}

//This function will expend/collapse tree node depends upon mode true/false;
function ExpandCollapseAll(treeViewId,mode)
{
var treeView = document.getElementById(treeViewId);
var treeLinks = treeView.getElementsByTagName("a");
var flag = true; var node; var level; var childContainer;

if (mode == true)
mode= 'none';
else
mode ='block';

for(var iCounter=0;iCounter<treeLinks.length;iCounter++)
{
if(treeLinks[iCounter].firstChild.tagName == "IMG")
{
node = treeLinks[iCounter];
level = parseInt(treeLinks[iCounter].id.substr(treeLinks[iCounter].id.length - 1),10);
childContainer = document.getElementById(treeLinks[iCounter].id + "Nodes");

if(flag)
{
if(childContainer.style.display == mode)
{
TreeView_ToggleNode(eval(treeViewId +"_Data"),level,node,'',childContainer);
//CheckUnCheckAll(treeViewId,mode);

}
flag = false;
}
else
{
if(childContainer.style.display == mode)
{
TreeView_ToggleNode(eval(treeViewId +"_Data"),level,node,'',childContainer);
//CheckUnCheckAll(treeViewId,mode);
}
}
}
}
}

</script>

Tuesday, September 11, 2007

How to Maintain Tree view state after page post back in ASP.NET 2.0

How to Maintain Tree view state after page post back in ASP.NET 2.0
In the web application if page get post back then it's very difficult to maintain tree view previous state. I am giving one sample code in C#.net to maintain tree view state when page get post back.
Here we can save tree view state into List control and Restore saved state when page again get post back or user clicks F5/refresh.
//to saves tree view state
private void SaveTreeViewState(TreeNodeCollection nodes, List<string> list)
{
Session["TreeViewState"] = null;
// Recursivley record all expanded nodes in the List.
foreach (TreeNode node in nodes)
{
if (node.ChildNodes != null)
{
if (node.Expanded.HasValue && node.Expanded == true
&& !String.IsNullOrEmpty(node.Text))
{
list.Add(node.Text);
}
if (node.ShowCheckBox == true
&& node.ChildNodes.Count == 0
&& node.Parent.Expanded == true)
{
if (node.Checked == true)
list.Add(node.ValuePath + "-T");
else
list.Add(node.ValuePath + "-F");
}
SaveTreeViewState(node.ChildNodes, list);
}
}
}
//to Restore treeview state after postback
private void RestoreTreeViewState(TreeNodeCollection nodes, List<string> list)
{
foreach (TreeNode node in nodes)
{
// Restore the state of one node.
if (list.Contains(node.Text)
list.Contains(node.ValuePath + "-T")
list.Contains(node.ValuePath + "-F"))
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0
&& node.Expanded.HasValue
&& node.Expanded == false)
{
if (node.Parent != null)
{
if (list.Contains(node.ChildNodes[0].ValuePath + "T")
list.Contains(node.ChildNodes[0].ValuePath + "-F"))
node.Expand();
}
else
{
node.Expand();
}
}
else if (node.ChildNodes != null && node.Expanded.HasValue
&& node.Expanded == false)
{
if (node.ShowCheckBox == true && list.Contains(node.Parent.Text)
&& list.Contains(node.Parent.Parent.Text))
{
if (list.IndexOf(node.ValuePath + "-T") != -1)
{
node.Checked = true;
}
else if (list.IndexOf(node.ValuePath + "-F") != -1)
{
node.Checked = false;
}
}
}
}
else
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0
&& node.Expanded.HasValue
&& node.Expanded == true)
node.Collapse();
}
// If the node has child nodes,restore their state, too.
if (node.ChildNodes != null && node.ChildNodes.Count != 0)
RestoreTreeViewState(node.ChildNodes, list);
}
}
How to Use
//You can use this in pageload event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["TreeViewState"] != null)
{
//Call method to restore tree view state
List<string> list = (List<string>)Session["TreeViewState"];
RestoreTreeViewState(tvFamilyModels.Nodes, list);
}
}
else
{
//Record the TreeView's current expand/collapse state.
List<string> list = new List<string>(100);
SaveTreeViewState(tvFamilyModels.Nodes, list);
Session["TreeViewState"] = list;
}
}