using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Examples
{
    public partial class XMLRead : Form
    {
        public XMLRead()
        {
            InitializeComponent();
        }

        DataSet ds = new DataSet();
        private void XMLRead_Load(object sender, EventArgs e)
        {
            ds.ReadXml(@"E:\tutorials\asp.net+c#\demo\Examples\Examples\Student.xml");
            dataGrid1.DataSource = ds;
            System.Diagnostics.Process.Start("iexplore", @"E:\tutorials\asp.net+c#\demo\Examples\Examples\Student.xml");
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Examples
{
    public partial class screensaver : Form
    {
        public screensaver()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Random rnd = new Random();
            this.BackColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));
        }

        private void screensaver_KeyPress(object sender, KeyPressEventArgs e)
        {
            Close();
        }
}
}
   



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Examples
{
    public partial class XMLWrite : Form
    {
        public XMLWrite()
        {
            InitializeComponent();
        }

        XmlTextWriter w;
        private void XMLWrite_Load(object sender, EventArgs e)
        {
            w = new XmlTextWriter(@"E:\tutorials\asp.net+c#\demo\Examples\Examples\Student1.xml",null);
            w.WriteStartElement("Teacher");
            w.WriteStartElement("Name");
            w.WriteString("Student1");
            w.WriteEndElement();
            w.WriteEndElement();
            w.Close();
            MessageBox.Show(@"E:\tutorials\asp.net+c#\demo\Examples\Examples\Student1.xml written successfully");
            System.Diagnostics.Process.Start("iexplore", @"E:\tutorials\asp.net+c#\demo\Examples\Examples\Student1.xml");

        }
    }
}


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Examples
{
    public partial class SysObjects : Form
    {
        public SysObjects()
        {
            InitializeComponent();
        }
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=jQuery;UID=sa;password=tiger123");
        SqlCommand cmd;
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                cmd = new SqlCommand(richTextBox1.Text,con);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    DataTable dt = new DataTable();
                    dt.Load(dr);
                    dataGrid1.DataSource = dt;                

                }
            }
            catch (Exception ex)
            {
            }

        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Examples
{
    public partial class Databases : Form
    {
        public Databases()
        {
            InitializeComponent();
        }
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=jQuery;UID=sa;password=tiger123");
        SqlCommand cmd;
        private void Databases_Load(object sender, EventArgs e)
        {
            fillTreeView();
        }
        private void fillTreeView()
        {
            try
            {
                con.Open();
                cmd = new SqlCommand("sp_helpdb", con);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    treeView1.Nodes.Add(dr["name"].ToString());
                 
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Permissions;
using System.Security;
using System.IO;


namespace Examples
{
    public partial class security : Form
    {
        public security()
        {
            InitializeComponent();
        }
     
        private void security_Load(object sender, EventArgs e)
        {

        }
        StreamWriter sw;
        private void button1_Click(object sender, EventArgs e)
        {
            sw = File.CreateText(@"E:\\demo.txt");
            sw.WriteLine("Hello");
            sw.Close();
        }
    }
}

update PFEP set supcusttype='1' where supcusttype is null
select supcusttype from PFEP where supcusttype is null
Introducing TRY...CATCH
Structured exception handing provides a powerful mechanism for controlling complex programs that have many dynamic runtime characteristics. It is a tried and true practice currently supported by many popular programming languages such as Microsoft Visual Basic .Net and Microsoft Visual C#. You will see in the examples below that utilizing this robust method will make your code more readable and maintainable. The TRY block contains transactional code that could potentially fail, while the CATCH block contains code that executes if an error occurs in the TRY block. If any errors occur in the TRY block, execution is diverted to the CATCH block and the error can be handled while error functions can be used to provide the detailed error information. TRY…CATCH has the following abbreviated syntax:
BEGIN TRY RAISERROR ('Houston, we have a problem', 16,1) END TRY BEGIN CATCH SELECT ERROR_NUMBER() as ERROR_NUMBER, ERROR_SEVERITY() as ERROR_SEVERITY, ERROR_STATE() as ERROR_STATE, ERROR_MESSAGE() as ERROR_MESSAGE END CATCH
Notice the use of functions in the script above that we are able to use in place of local and/or global variables. These functions should only be used in a CATCH BLOCK and are explained below:
  1. ERROR_NUMBER() returns the number of the error.
  2. ERROR_SEVERITY() returns the severity.
  3. ERROR_STATE() returns the error state number.
  4. ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
  5. ERROR_LINE() returns the line number inside the routine that caused the error.
  6. ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names or times.


----------------------------------------------



----------------------------------------------


create proc P_Insert_New_BookTitle_2K5
(@TitleName nvarchar(128),
 @Price money,
 @au_fname nvarchar(32),
 @au_name nvarchar(64),
 @CommissionRating int)
as
declare @err int,
  @tablename sysname,
  @errormessage nvarchar(2000)

BEGIN TRY

 begin transaction

 select @errormessage = 'insert into Titles table failed',
   @tablename = 'Titles'
 insert dbo.Titles (TitleName, Price)
 values (@TitleName, @Price)

 select @errormessage = 'insert into Authors table failed',
   @tablename = 'Authors'
insert dbo.Authors  (au_fname, au_lname, TitleID, 
                     CommissionRating)
values (@au_fname, @au_fname, @@IDENTITY, 
        @CommissionRating)

 commit transaction

END TRY


BEGIN CATCH
 
 ROLLBACK TRANSACTION

 -- Log the error 
 insert dbo.Application_Error_Log (UserName, tableName,     
            errorNumber, errorSeverity, errorState, errorMessage)
 values (suser_sname(), @tableName, ERROR_NUMBER(),  
            ERROR_SEVERITY(), ERROR_STATE(), ERROR_MESSAGE())  

 RAISERROR (@errormessage, 16,1)

END CATCH



----------------------------------------------

exec P_Insert_New_BookTitle_2K5 'Red Storm Rising',16.99, 'Tom','Clancy', 200
When we execute the stored procedure with the provided parameters, the insert into the Authors table fails because of an invalid Commission Rating value. When this happens, execution is diverted to the CATCH block, which rolls back our transaction and inserts a row into our Application_Error_Log using the SQL Server 2005 supplied functions.
<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>

<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Net.Mail" %>
<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
 
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
     
    void Application_Error(object sender, EventArgs e)
    {
        Exception err = Server.GetLastError();
     
        Session["error"] = err.InnerException.Message;
        Session["ErrorMessage"] = err.InnerException.Message;
        Session["Message"] = err.Message.ToString();
        Session["ExceptionType"] = err.GetType().ToString();

        Session["Source"] = err.Source.ToString();
        Session["TargetSite"] = err.TargetSite.ToString();

        Session["Timestamp"] = DateTime.Now.ToString();

        if (err is HttpException && err.InnerException != null)
        {

            err = err.InnerException; //Avoid the Unhandled Exception wrapper which is meaningless

        }

        MailMessage msg = new MailMessage();
        HttpContext ctx = HttpContext.Current;

        msg.To.Add(new MailAddress("xxxx@gmail.com"));
        msg.From = new MailAddress("xxxx@gmail.com");
        msg.Subject = "My app had an issue...";
        msg.Priority = MailPriority.High;

        //StringBuilder sb = new StringBuilder();
        //sb.Append(ctx.Request.Url.ToString() + System.Environment.NewLine);
        //sb.Append("Source:" + System.Environment.NewLine + ctx.Server.GetLastError().Source.ToString());
        //sb.Append("Message:" + System.Environment.NewLine + ctx.Server.GetLastError().Message.ToString());
        //sb.Append("Stack Trace:" + System.Environment.NewLine + ctx.Server.GetLastError().StackTrace.ToString());
        //msg.Body = sb.ToString();
        StringBuilder sb = new StringBuilder();
        sb.Append(ctx.Request.Url.ToString() + System.Environment.NewLine);
        sb.Append("Source:" + System.Environment.NewLine + err.Source.ToString());
        sb.Append("Message:" + System.Environment.NewLine + err.Message.ToString());
        sb.Append("ExceptionType:" + System.Environment.NewLine + err.GetType().ToString());
        sb.Append("TargetSite:" + System.Environment.NewLine + err.TargetSite.ToString());
        sb.Append("Timestamp:" + System.Environment.NewLine + DateTime.Now.ToString());
        msg.Body = sb.ToString();

        //CONFIGURE SMTP OBJECT
   
        SmtpClient smtp = new SmtpClient("smtp.gmail.com");
        smtp.EnableSsl = true;
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("xxxx@gmail.com", "xxxx");
        //SEND EMAIL
        smtp.Send(msg);

        //REDIRECT USER TO ERROR PAGE
        Server.Transfer("ErrorPage.aspx");
        //ExceptionManager.Publish(err);
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        Session["error"] = "";//initialize the session
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }
     
</script>






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ErrorPage.aspx.cs" Inherits="ErrorPage" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <h2>
        An Error Has Occurred</h2>
    <p>
        An unexpected error occurred on our website. The website administrator has been notified.</p>
    <ul>
        <li>
            <asp:HyperLink ID="lnkHome" runat="server" NavigateUrl="~/Default.aspx">Return to the homepage</asp:HyperLink></li>
    </ul>
       <%-- <asp:Label ID="lblError" runat="server" Text="Label"></asp:Label>
         <asp:Label ID="lblExtendedMessage" runat="server" Text="Label"></asp:Label>--%>
    </div>
    </form>
</body>
</html>
The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.
What is a Model?

  1. MVC model is basically a C# or VB.NET class
  2. A model is accessible by both controller and view
  3. A model can be used to pass data from Controller to view
  4. A view can use model to display data in page.

What is a View?

  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method

What is a Controller?

  • Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  • Controller is a heart of the entire MVC architecture
  • Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  • Controller can access and use model class to pass data to views
  • Controller uses ViewData to pass any data to view

MVC File Structure & File Naming Standards
MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.

  • Root [directory]
  • Controller [directory]
  • Controller CS files
  • Models [directory]
  • Model CS files
  • Views [directory]
  • View aspx/ascx files
  • Global.asax
  • Web.config


Browser Request (Step 1)
Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/
Job of Global.asax – MVC routing (Step 2)
The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [xyz.com]/home/index/:
Controller = home
Action = index()
ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string
Controller and Action methods (Step 3)
MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.
Call to View (Step 4)
Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.


  • There's no duplicated code.
  • The business logic is encapsulated; hence the controller code is transparent and safer.
  • The business logic can be used in several front ends like Web pages, Web services, Windows applications, services, etc.
  • Exception handling is well managed showing the user only digested error messages.
  • Testing every part of an application is easier as it can be done separately using automated methods.
  • Application changes are easier to apply as they are focused in one part of the architecture only.