Sunday, March 27, 2011

Validate XML aganist an XSD in Asp.Net C#




Please visit my new Web Site https://coderstechzone.com



Most of the times when we are working with XML we need to validate the XML file from an XSD file. Here i am showing an code example how one can validate XML file using an XSD in Asp.Net C#.

To do that add an aspx page in your project.











Now under Page_Load event write the below code:
using System;
using System.Xml;
using System.Text;
using System.Xml.Schema;

public partial class Validate_XML_XSD : System.Web.UI.Page
{
    private StringBuilder sB = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string xmlPath = MapPath("MenuXML.xml");
            string xsdPath = MapPath("MenuXML.xsd");

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, XmlReader.Create(xsdPath));

            XmlReader Oreader = XmlReader.Create(xmlPath, settings);
            XmlDocument Odoc = new XmlDocument();
            Odoc.Load(Oreader);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

            Odoc.Validate(eventHandler);
            if (sB.ToString() == String.Empty)
                Response.Write("Validation completed successfully.");
            else
                Response.Write("Validation Failed: " + sB.ToString());
        }
    }

    public void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
        sB.Append("Error: " + args.Message);
    }  
}

Hope now you can validate XML file easily.

Creating XSD file from an XML file in Asp.Net within few seconds




Please visit my new Web Site https://coderstechzone.com



There are a lot of tools in the internet you will get to create XSD file from an XML file but you need to download then install or may be convert on-line. But there is good news that Asp.Net has built in menu to create XSD file from an XML file.













To do that first write the below XML file in VisualStudio:
<?xml version="1.0" encoding="utf-8" ?>
<Home>
  <Menu text="Books" url="MenuFromXml.aspx">
    <SubMenu text="Asp.Net" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="Ajax" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="MS SQL Server 2005" url="MenuFromXml.aspx"></SubMenu>
    <SubMenu text="JavaScript" url="MenuFromXml.aspx"></SubMenu>
  </Menu>
  <Menu text="Electronics"  url="MenuFromXml.aspx">
    <SubMenu text="Camera" url="MenuFromXml.aspx">
      <SubMenu text="Digital" url="MenuFromXml.aspx">
        <SubMenu text="Canon" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Kodak" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Sony" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Casio" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Fuji" url="MenuFromXml.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Film Camera" url="MenuFromXml.aspx"></SubMenu>
    </SubMenu>
    <SubMenu text="DVDs" url="MenuFromXml.aspx">
      <SubMenu text="Comedy" url="MenuFromXml.aspx">
        <SubMenu text="English" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="French" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="German" url="MenuFromXml.aspx"></SubMenu>
        <SubMenu text="Spanish" url="MenuFromXml.aspx"></SubMenu>
      </SubMenu>
      <SubMenu text="Kids Movies" url="MenuFromXml.aspx"></SubMenu>
      <SubMenu text="Romance Movies" url="MenuFromXml.aspx"></SubMenu>
      <SubMenu text="Action Movies" url="MenuFromXml.aspx"></SubMenu>
    </SubMenu>
  </Menu>
  <Menu text="Contact Us" url="MenuFromXml.aspx"></Menu>
</Home>

Now you found a menu named "XML" in VS Main menu. View:

Now click on Create schema will create the below XSD file:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Home">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="Menu">
          <xs:complexType>
            <xs:sequence minOccurs="0">
              <xs:element maxOccurs="unbounded" name="SubMenu">
                <xs:complexType>
                  <xs:sequence minOccurs="0">
                    <xs:element maxOccurs="unbounded" name="SubMenu">
                      <xs:complexType>
                        <xs:sequence minOccurs="0">
                          <xs:element maxOccurs="unbounded" name="SubMenu">
                            <xs:complexType>
                              <xs:attribute name="text" type="xs:string" use="required" />
                              <xs:attribute name="url" type="xs:string" use="required" />
                            </xs:complexType>
                          </xs:element>
                        </xs:sequence>
                        <xs:attribute name="text" type="xs:string" use="required" />
                        <xs:attribute name="url" type="xs:string" use="required" />
                      </xs:complexType>
                    </xs:element>
                  </xs:sequence>
                  <xs:attribute name="text" type="xs:string" use="required" />
                  <xs:attribute name="url" type="xs:string" use="required" />
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="text" type="xs:string" use="required" />
            <xs:attribute name="url" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Wow done wthin few seconds.

Bind DataSource into DataList example in Asp.Net




Please visit my new Web Site https://coderstechzone.com



The DataList control is a standard control of Asp.Net like others. It is used to display repeated list of data or items. You can bind any datasource in this DataList control like DataTable, SqlDataReader and XML etc. In most e-commerce site use DataList control to display products insted of repeater control. Here in this example i will show you how one can bind data to DataList control in runtime.

Table snapshot that we bound to the control:
DataList table structure


Now add an Aspx page in your project and write the below HTML markup code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataList.aspx.cs" Inherits="DataList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>DataList DataBinding Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DataList id="DataList1" runat="server">
            <ItemTemplate>
                Title: 
                <asp:Label id="Label6" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>'></asp:Label>
                <br />
                Published: 
                <asp:Label id="Label7" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Published") %>'></asp:Label>
                <br />
                Modified: 
                <asp:Label id="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ModifedDate") %>'></asp:Label>
            </ItemTemplate>
            <HeaderTemplate>
                <asp:Label id="Label1" runat="server" Font-Names="Tahoma" Font-Italic="True">List of Articles:</asp:Label>
                <hr />
            </HeaderTemplate>
            <FooterTemplate>
                <hr />
            </FooterTemplate>
            <SeparatorTemplate>
                <hr />
            </SeparatorTemplate>
        </asp:DataList>    
    </div>
    </form>
</body>
</html>

Now under Page_Load event write the below server side code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataList1.DataSource = PopulateData();
            DataList1.DataBind();
        }
    }

    public SqlDataReader PopulateData()
    {
        string conStr=@"Data Source=.\SQLExpress;Initial Catalog=TESTDB;User Id=sa;Password=Comm!pass@1;";
        SqlConnection Conn = new SqlConnection(conStr);
        string sQuery="SELECT * FROM Article";
        SqlCommand sqlCommand = new SqlCommand(sQuery, Conn);
        Conn.Open();
        SqlDataReader dataReader=sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
        return dataReader;
    }

Dont forget to add the "using System.Data.SqlClient;" namespace.

Now run the project & hope you will get below output:
DataList output
Hope now you bound the DataList control to display repeated data.

Wednesday, March 23, 2011

Center middle the content of a DIV based web page




Please visit my new Web Site https://coderstechzone.com



When browsing we found a lot of website midle centered. The question is how developer doing this. In forums i found many times this question. Its simple and easy to middle the content for div based design. To do that wrap up all div in one div and then apply some CSS to middle or center the web page.
I want to make the below example:











To do that add an aspx page in your project. Then add the below stylesheet/CSS under head HTML tag:
<style type="text/css">
        #main_container {width: 760px;margin:auto}
        #content
            {
                background-color:gray;
                font-weight:bold;
                color:White;
            }
    </style>

Now write the below code under BODY tag:
<form id="form1" runat="server">
        <div id="main_container">
            <div id="content">
                Main Body Here
            </div>
        </div>    
    </form>

Now run the page. Hope you found your content in middle or center of the browser.

Tricks for URL Rewriting using Request.PathInfo in Asp.Net




Please visit my new Web Site https://coderstechzone.com



To publish cleaner URL in your Asp.Net application you can use URL Rewriting. The most popular reason for URL Rewriting is let you have implemented pages based on query string like http://yourdomain/product.aspx?Brand=Lux. But now you want to change the URL to http://yourdomain/product.aspx/Lux for SEO purpose. There is a lot of way to implement this. One of the easy trick is you can achieve URL Rewriting by using Request.PathInfo of Asp.Net. Mind it this is not the best way for a huge site because this technique requires some of coding which is error prone. One another thing that if you have 10 brands & you use query string to populate Brand related product then google will index only one url but if you use URL like http://yourdomain/product.aspx/Lux then google will treat all ten individual pages. Nice thing am i right? Another reason for URL Rewriting is to server the pages those users have bookmarked old query string URL's. Let’s move for implementation. To do that first add a page in your project and named it BrandList.aspx.



Add a button in this page and write the below code under button click event:
Response.Redirect("Product.aspx/Lux");

Now add another page and name the page product.aspx. Now write the following server side code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Response.Write("Brand=" + GetBrand());
            // Now you can do anything sinch you have got the BrandName
        }
    }

    public string GetBrand()
    {
        if (Request.PathInfo.Length == 0)
            return Request["Brand"];
        else
            return Request.PathInfo.Substring(1);
    }

Now run the BrandList page and click on the button. Check your browser address you will find a SEO friendly URL. The previous bookmark users also get your product list.

Monday, March 21, 2011

Check user name login name email address availability using jquery ajax in Asp.Net page




Please visit my new Web Site https://coderstechzone.com



In most registration page we need to check the availability of user name or email address using Jquery/Ajax. Because it will be hectic job for user to rewrite the data after getting post back error that user name already taken or email address already taken. So it would be very helpful for user if he can check his name or login name or email address availability in time without losing any data. To do that in this article i will show you GMAIL like feature by using Jquery & Asp.Net Ajax. The test output screen look like this:

Check login Name Availability

Now add a handler by right clicking on solution name. Then click on Add New Item and then select Generic Handler. Name the handler to "user_Login.ashx".
Write the below code within the handler:
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

public class user_Login : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string user_name = context.Request["user_name"];     
        string output = "";
        output = CheckAvailability(user_name);
        context.Response.Write(output);
        context.Response.End();
    }

    public string CheckAvailability(string user_name)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand("Select User_Name from tblUsers where User_Name=@Name", con);
        com.Parameters.AddWithValue("@Name", user_name);
        string uName = (string)com.ExecuteScalar();
        con.Close();
        if (uName != null)
            return "1";
        else
            return "0";
    }
    
    public bool IsReusable 
    {
        get {return false;}
    }
}

Now add an aspx page & write the below HTML code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Check_USER_EMAIL.aspx.cs" Inherits="Check_USER_EMAIL" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Check user or email address availability</title>
    <script src="Script/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function() {
        $("#cmdCheck").click(function() {
        $.post("user_Login.ashx", { user_name: $("#<% =txtName.ClientID %>").val() }, function(output) {
        if (output == "1") 
        {                    
            $("#dv_Ajax_Response").html("Name already exist!");
        }
        else{                    
            $("#dv_Ajax_Response").html("Still available");
            }

        });
        });
    });

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <input type="button" id="cmdCheck" value="Available?" />
    <div id="dv_Ajax_Response" style="color:Red;font-weight:bold"></div>
    </div>
    </form>
</body>
</html>

Now run the page. Hope you can now check the availability of user name or user login or email address before submit the full registration page.
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash