Thursday, July 19, 2007

How to Read/Write xml string in different way using C#.net

How to Read/Write xml string in different way using C#.net

Namespace

using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.IO;
using System.Text;

Example Value

string xmlProduct = "<product><details><code value ="MDI">100</code></details></product>"

Read XML


1) First way you can read string xml using dataset

StringReader productDetails = new StringReader(xmlProduct);
DataSet dsProduct = new DataSet();
dsProduct.ReadXml(productDetails);

2) If you have proper XML format value in file

DataSet dsProduct = new DataSet();
dsProduct.ReadXml("C:\Read.xml");

3) You can use XmlTextReader to read xml

string nodeText; int depth;
//In this way you can convert Xmlstring to memoryStream
byte[] data = Encoding.ASCII.GetBytes(xmlProduct);
MemoryStream memStream = new MemoryStream(data);
XmlTextReader textReader = new XmlTextReader(memStream);
XmlNodeType nodeType;

while (textReader.Read())
{
textReader.MoveToFirstAttribute();
nodeType = textReader.NodeType;
if (nodeType.CompareTo(XmlNodeType.Attribute) == 0)
{
nodeText = textReader.Value;
depth = textReader.Depth;
}
}

4) You can use CmlDocument object to read xml,This is the best way to read xml string to read node by node and all attributes.

XmlDocument xmlProductDoc = new XmlDocument();
xmlProductDoc.LoadXml(xmlProduct);

for (int i = 0; i < xmlProductDoc.GetElementsByTagName("product").Count;i++)
{
string xmlVal = xmlProductDoc.GetElementsByTagName("product").innerXml;
string xmlAttributeVal = xmlProductDoc.GetElementsByTagName("product").
Attributes ["value"].value;
}


Write XML

1) You can use XmlTesWriter to write xml file

XmlTextWriter myXmlTextWriter = new XmlTextWriter("books.xml", null);
myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("bookstore", null, "books.dtd", null);
myXmlTextWriter.WriteComment("This file represents inventory database");
myXmlTextWriter.WriteStartElement("bookstore");
myXmlTextWriter.WriteStartElement("book", null);
myXmlTextWriter.WriteAttributeString("genre", "autobiography");
myXmlTextWriter.WriteAttributeString("publicationdate", "1990");
myXmlTextWriter.WriteAttributeString("ISBN", "0-4567-123-9");
myXmlTextWriter.WriteElementString("title", null, "Baby book");
myXmlTextWriter.WriteStartElement("Author", null);
myXmlTextWriter.WriteElementString("first-name", "Ritesh");
myXmlTextWriter.WriteElementString("last-name", "Kesharwani");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("price", "8.9");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();
//Write the XML to file and close the myXmlTextWriter
myXmlTextWriter.Flush();
myXmlTextWriter.Close();

2) Basic way to write xml into file

Monday, July 16, 2007

How to select all run time generated Check Box.

How to select all run time generated Check Box.
Server Side Code in C#
//This function will fetch all the controls in the page
//you can make a filter based on control you want using
//"UnderlyingSystemType.Name" property
//Here recursive function used to get into controls inside controls
private void CheckBoxSelection(ControlCollection ctl, bool chkFlg)
{
CheckBox chkBox;
foreach (Control con in ctl)
{
if (con.GetType().UnderlyingSystemType.Name == "CheckBox")
{
chkBox = (CheckBox)Page.FindControl("UserControl").FindControl(con.ID);
chkBox.Checked = chkFlg;
}
if (con.HasControls())
{
CheckBoxSelection(con.Controls, chkFlg, chkIsModel);
}
}
}
//Same way you can get the controls value
private void GetSelectedCheckBoxValue(ControlCollection ctl)
{
ArrayList arrSelectedValue = new ArrayList();
CheckBox chk1;
foreach (Control con in ctl)
{
if (con.GetType().UnderlyingSystemType.Name == "CheckBox")
{
chk1 = (CheckBox)Page.FindControl("UserControl").FindControl(con.ID);
if (chk1.Checked)
arrSelectedValue.Add(con.ID);
}
if (con.HasControls())
{
GetSelectedCheckBoxValue(con.Controls);
}
}
}
Client Side Code in JavaScript supported by IE, Netscape and Mozilla
function CheckBoxSelection(flg)
{
// This line gives all the "Input" control in a page
var chk = window.document.getElementsByTagName("Input");
for (i =0;i<chk.length;i++)
{
// based on the ID prefix you can put condition
if (chk[i].id.indexOf("chk") != -1)
{
if (flg == "false")
{
chk[i].checked = false;
}
else
{
chk[i].checked = true;
}
}
}
}
Call Java script function from Code behind
rdoSelectAll.Attributes.Add("OnClick", "CheckBoxSelection('true')");
rdoClearAll.Attributes.Add("OnClick", "CheckBoxSelection('false')");
Note: rdoSelectAll and rdoClearAll is radio button controls
Generate runtime Check Box controls
private void GenerateModelTable(string[] modelNames)
{
Table tblModel = new Table();
for (int count = 0; count < modelNames.Length; count++)
{
TableRow trModel = new TableRow();
TableCell tcChkModel = new TableCell();
TableCell tcModel = new TableCell();
CheckBox chkModel = new CheckBox();
chkModel.ID = "chk" + "_" + modelNames[count];
tcChkModel.Controls.Add(chkModel);
tcModel.Text = modelNames[count];
trModel.Controls.Add(tcChkModel);
trModel.Controls.Add(tcModel);
tblModel.Controls.Add(trModel);
}
pnlModel.Controls.Add(tblModel);
}

Thursday, June 14, 2007

How to Handle browser “Back” button using ASP.NET

Handling browser "Back" button using ASP.NET
 
To disable browser "Back" button
 
1) Very first and simplest way to disable the browser back button is  
 
<script language="JavaScript">
  javascript:window.history.forward(0);                     
</script>
 
  Using this user can't use back button from browser to see previous page.
 
2)  Here if user redirect to error page then on the body onload we can call the following function so that user can not use back button at all, here we are redirecting same page again and again.
 
<script language="JavaScript">   
    function DisablingBackFunctionality()
    {
        var URL;
        var i ;
        var QryStrValue;
        URL=window.location.href ;
        i=URL.indexOf("?");
        QryStrValue=URL.substring(i+1);
        if (QryStrValue!='X')
        {
            window.location=URL + "?X";
        }
    }
</script>
  
To close the browser window
 
Following are the alternate to handle browser "Back" button, like if you have an error in your application and you are redirecting to error page now from this error page user should not use browser back button to see the previous page.
We have to close the window by giving some alert error message, below some script to do so
 
1) To close the browser use
 
window.close() OR  this.close()  OR  document.close()
 
2) To close the browser without prompt use
           
window.opener = top;
window.close(); OR this.close()  OR  document.close()
  
3) If you want to give some alert message to close the page and if user click "OK" then close the browser then call following function in body  onload="check_form()"
 
<script language="JavaScript">
      var submitted=false;
      function check_form()
{
            if (submitted == true)
{
  alert ("Form already submitted") ;
  return false;
            }
      else
{
            submitted = true ;
      document.frmError.submit();
window.status ="Session expired. Please restart";
      window.opener = top;
alert("Please close this window.");
      window.close();
      }
      }
</script>
 
4) If you want to close the browser automatically after few second then use following script in your aspx page
 
<script language="JavaScript">
 
   var bloodythief = 5;
    {
      alert("Window will close after 5 second.");
      window.setTimeout("window.close()",bloodythief*1000);
      window.opener = top;
    }
 
  </script>
 
 
5)If you want ot disable browser Referesh or F5 button then use following script in your aspx page
 
    <script>       
  window.history.forward(1);
        document.attachEvent("onkeydown", my_onkeydown_handler);
        function my_onkeydown_handler()
        {
            switch (event.keyCode)
      {
            case 116 : // 'F5'
            event.returnValue = false;
            event.keyCode = 0;
            window.status = "We have disabled F5";
            break;
            }
          }             
      </script>
 
Redirect to login page
 
6) All the above solution not seem to be compatable in other browser (Mozilla,Netscape etc), actually Window.close() function not works properly in others browser.To work in properly in other browser you have to close the parent window then open new window, it's kind of redirecting to login page if session expire.
 
This Supports all browsers.
 
<script language="JavaScript">
   
        function RedirectToLoinPage()
        {
            window.opener=self;
            var URL = window.location.href;
            if (URL.indexOf('Session') == -1)
            {
                alert('Not authorized to view this application.');
            }
            else
            {
                alert('Session expired.');
            }
            window.close();
            window.open('Login.aspx','Login','');
            }
</script>
 
8) Another way to close the browser in other browsers
 
<script language="JavaScript">
function closeMe()
{
var win=window.open("","_self");
win.close();
}
</script>
 
Imp: if the user has disabled JavaScript, then above java script won't work.
When user use "back" button to see previous page and submitting that page again then handle in the code behind also and redirect him to login page.
 
Session.Abandon() method to expire session and check in each page page_load event if (!Session.IsNewSession && Session["UserId"] == null) if session is null then redirect to login page.


Get the Yahoo! toolbar and be alerted to new email wherever you're surfing.