Pages

Monday, 20 February 2012

How to insert video files into sql server using asp.net.How to play the inserted video files in asp.net


string filePath = @"D:\\Movies\sample.avi";//get the file name here

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);

BinaryReader reader = new BinaryReader(fs);

byte[] BlobValue = reader.ReadBytes((int)fs.Length);

fs.Close();
reader.Close();

SqlConnection BlobsDatabaseConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");SqlCommand SaveBlobeCommand = new SqlCommand();
SaveBlobeCommand.Connection = BlobsDatabaseConn;
SaveBlobeCommand.CommandType = CommandType.Text;
SaveBlobeCommand.CommandText = "INSERT INTO BlobsTable(BlobFileName, BlobFile)" + "VALUES (@BlobFileName, @BlobFile)";
SqlParameter BlobFileNameParam = new SqlParameter("@BlobFileName", SqlDbType.NChar);
SqlParameter BlobFileParam = new SqlParameter("@BlobFile", SqlDbType.Binary);
SaveBlobeCommand.Parameters.Add(BlobFileNameParam);
SaveBlobeCommand.Parameters.Add(BlobFileParam);
BlobFileNameParam.Value = filePath.Substring(filePath.LastIndexOf("\\") + 1);
BlobFileParam.Value = BlobValue;
try
{
    SaveBlobeCommand.Connection.Open();
    SaveBlobeCommand.ExecuteNonQuery();
    MessageBox.Show(BlobFileNameParam.Value.ToString() + " saved to database.","BLOB Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    SaveBlobeCommand.Connection.Close();
}
Retrieve the video from the server...

string SavePath = @"D:\\DownMovies";//save in this path
SqlConnection SaveConn = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI");
SqlCommand SaveCommand = new SqlCommand();
SaveCommand.CommandText = "Select BlobFileName, BlobFile from BlobsTable where BlobFileName = @BlobFileName";
SaveCommand.Connection = SaveConn;
SaveCommand.Parameters.Add("@BlobFileName", SqlDbType.NVarChar).Value = "My Movie.wmv";

long CurrentIndex = 0;

int BufferSize = 100;
long BytesReturned;

byte[] Blob = new byte[BufferSize];

SaveCommand.Connection.Open();


SqlDataReader
reader = SaveCommand.ExecuteReader(CommandBehavior.SequentialAccess);

while
(reader.Read())
{
    FileStream fs = new FileStream(SavePath + "\\" + reader["BlobFileName"].ToString(), FileMode.OpenOrCreate, FileAccess.Write);
    BinaryWriter writer = new BinaryWriter(fs);
    CurrentIndex = 0;
    BytesReturned = reader.GetBytes(1, //the BlobsTable column indexCurrentIndex, // the current index of the field from which to begin the read operationBlob, // Array name to write tha buffer to0, // the start index of the array to start the write operationBufferSize // the maximum length to copy into the buffer); 
    while (BytesReturned == BufferSize)
    {
        writer.Write(Blob);
        writer.Flush();        CurrentIndex += BufferSize;
        BytesReturned = reader.GetBytes(1, CurrentIndex, Blob, 0, BufferSize);
    }
reader.Close();
SaveCommand.Connection.Close();


How to select the data and show it on your page


using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public class VideoHandler : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string connectionString = 
          ConfigurationManager.ConnectionStrings[
          "uploadConnectionString"].ConnectionString;

        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("SELECT Video, Video_Name" + 
                         " FROM Videos WHERE ID = @id", connection);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = 
                           context.Request.QueryString["id"];
        try
        {
            connection.Open();
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    context.Response.ContentType = reader["Video_Name"].ToString();
                    context.Response.BinaryWrite((byte[])reader["Video"]);
                }
            }
        }
        finally
        {
            connection.Close();
        }
    }
 
    public bool IsReusable 
    {
        get {
            return false;
        }
    }
}

how to play video file using C# code


using System.IO;
using System.Data.SqlClient;

public partial class UploadVideo : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    byte[] buffer;
    //this is the array of bytes which will hold the data (file)

    SqlConnection connection;
    protected void ButtonUpload_Click(object sender, EventArgs e)
    {
        //check the file

        if (FileUpload1.HasFile && FileUpload1.PostedFile != null 
            && FileUpload1.PostedFile.FileName != "")
        {
            HttpPostedFile file = FileUpload1.PostedFile;
            //retrieve the HttpPostedFile object

            buffer = new byte[file.ContentLength];
            int bytesReaded = file.InputStream.Read(buffer, 0, 
                              FileUpload1.PostedFile.ContentLength);
            //the HttpPostedFile has InputStream porperty (using System.IO;)
            //which can read the stream to the buffer object,
            //the first parameter is the array of bytes to store in,
            //the second parameter is the zero index (of specific byte)
            //where to start storing in the buffer,
            //the third parameter is the number of bytes 
            //you want to read (do u care about this?)

            if (bytesReaded > 0)
            {
                try
                {
                    string connectionString = 
                      ConfigurationManager.ConnectionStrings[
                      "uploadConnectionString"].ConnectionString;
                    connection = new SqlConnection(connectionString);
                    SqlCommand cmd = new SqlCommand
                    ("INSERT INTO Videos (Video, Video_Name, Video_Size)" + 
                     " VALUES (@video, @videoName, @videoSize)", connection);
                    cmd.Parameters.Add("@video", 
                        SqlDbType.VarBinary, buffer.Length).Value = buffer;
                    cmd.Parameters.Add("@videoName", 
                        SqlDbType.NVarChar).Value = FileUpload1.FileName;
                    cmd.Parameters.Add("@videoSize", 
                        SqlDbType.BigInt).Value = file.ContentLength;
                    using (connection)
                    {
                        connection.Open();
                        int i = cmd.ExecuteNonQuery();
                        Label1.Text = "uploaded, " + i.ToString() + " rows affected";
                    }
                }
                catch (Exception ex)
                {
                    Label1.Text = ex.Message.ToString();
                }
            }

        }
        else
        {
            Label1.Text = "Choose a valid video file";
        }
    }
}
//create a sqlcommand object passing the query and the sqlconnection object
//when declaring the parameters you have to be sure 
//you have set the type of video column to varbinary(MAX)

View The PDF file In Browser using C# code

private void ReadPdfFile()
    {
        
string path = @"C:\Swift3D.pdf";
        WebClient client = 
new WebClient();
        Byte[] buffer =  client.DownloadData(path);

        
if (buffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length",buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }

    }

Tuesday, 14 February 2012

Downloading File From the Grid View

if (e.CommandName == "View")
        {
            ImageButton lb = (ImageButton)e.CommandSource;
            GridViewRow gvr = (GridViewRow)lb.NamingContainer;
            string id = (string)gvdetails.DataKeys[gvr.RowIndex].Value;
            Session["applciationid"] = id;
            DataSet ds = obj.GetDisbursmentDetais(id);
            Session["DocumentLocation"] = ds.Tables[0].Rows[0]["DocuemtnFile"].ToString();
            string filename = Server.MapPath(Session["DocumentLocation"].ToString());
            FileInfo fileInf = new FileInfo(filename);
            if (fileInf.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInf.Name);
                Response.AddHeader("Content-Length", fileInf.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Flush();
                Response.TransmitFile(fileInf.FullName);
            }
            else
            {
               Label1.Text="<script>"+Environment.NewLine+"alert('NO File is there')</script>";
            }
        }

Getting the record from the gridview

if (e.CommandName == "View")
        {
            ImageButton lb = (ImageButton)e.CommandSource;
            GridViewRow gvr = (GridViewRow)lb.NamingContainer;
            string id = (string)gvdetails.DataKeys[gvr.RowIndex].Value;
            Session["applciationid"] = id;
            DataSet ds = obj1.GetCompanyUserDetails(id);
            string usertype = ds.Tables[0].Rows[0]["Applicanttype"].ToString();

            if (usertype == "Individual")
            {
                Session["applciationid"] = id;
                Response.Redirect("default.aspx");
            }
            if (usertype == "Company")
            {
                Session["applciationid"] = id;
                Response.Redirect("default.aspx");

            }
        }

Thursday, 9 February 2012

Create Stored Procedure For Select record

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER proc [dbo].[Get_Ind_UsedCarLoan]
(@pApplicationId int)
as
begin
select  VehicleName,
 VehicleNumber,
 YearOfManufacture,
 ValuationAmount,
 LoanAmount,
 Insurance,
 Suraksha,
 Others,
 TotalLoanAmount,
 ProccesingFee,
 StampDuty,
 SurakshaDeduction ,
 InsuranceDeduction ,
 AdvanceEmi ,
 Rta ,
 Valuation ,
 OthersDeduction ,
 NetDirsuburcementAmount ,
 LoanAmountDetails ,
 Tenure ,
 EmiAmount ,
 Tenure1 ,
 RateOfInterest ,
 LoadingAmount ,
 ExistingHypothecatedTo,
 ExistingLoanOutstanding,Notepad from Individual_UsedCarLoan where ApplicationId=@pApplicationId
end

Create a Stored Procedure For Updating The Record

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER proc [dbo].[Update_Ind_UsedCarLoan]
(@pApplicationId int,
@pVehicleName varchar(50),
@pVehicleNumber varchar(50),
@pYearOfManufacture varchar(50),
@pTenure1  varchar(50),
@pRateOfInterest  varchar(50),
@pLoadingAmount  varchar(50),
@pExistingHypothecatedTo varchar(50),
@pExistingLoanOutstanding varchar(50),@pNotepad varchar(max)
)
as
begin
update Individual_UsedCarLoan set  VehicleName=@pVehicleName,
 VehicleNumber=@pVehicleNumber,
 YearOfManufacture=@pYearOfManufacture,
   Tenure1=@pTenure1 ,
 RateOfInterest =@pRateOfInterest,
 LoadingAmount =@pLoadingAmount,
 ExistingHypothecatedTo=@pExistingHypothecatedTo,
 ExistingLoanOutstanding=@pExistingLoanOutstanding,Notepad=@pNotepad  where ApplicationId=@pApplicationId
end

Create a Stored Procedure For Inserting a Record

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER proc [dbo].[Insert_Ind_Homeloan]
(
@pApplicationId int,
@pValuationAmount varchar(50),
@pLoanAmount varchar(50) ,
@pSuraksha  varchar(50),
@pPropertyInsurance varchar(50) ,
@pOthers  varchar(50),
@pTotalLoanAmount  varchar(50),
@pProccesingFee  varchar(50),
@pStampDuty  varchar(50),
@pSurakshaDeduction  varchar(50),
@pPropertyInsuranceDeduction  varchar(50),
@pValuationFee  varchar(50),
@pLegalFee  varchar(50),
@pNetLoanAmount  varchar(50),
@pLoanAmountDetails  varchar(50),
@pTenure  varchar(50),
@pEmiAmount  varchar(50),
@pEmi  varchar(50),
@pRateOfInterest  varchar(50),
@pLoadingAmount  varchar(50),
@pExistingHypothecatedTo  varchar(50),
@pExistingLoanOutstanding varchar(50),
@pNotepad varchar(max)
)
as
begin
insert into Individual_HomeLoan values(@pApplicationId,
@pValuationAmount,
@pLoanAmount,
@pSuraksha,
@pPropertyInsurance,
@pOthers,
@pTotalLoanAmount,
@pProccesingFee,
@pStampDuty,
@pSurakshaDeduction,
@pPropertyInsuranceDeduction,
@pValuationFee,
@pLegalFee,
@pNetLoanAmount,
@pLoanAmountDetails,
@pTenure,
@pEmiAmount,
@pEmi,
@pRateOfInterest,
@pLoadingAmount,
@pExistingHypothecatedTo,
@pExistingLoanOutstanding,
@pNotepad

)
end




Retriving Fields From the DataBase Using Stored Procedure

SqlCommand cmd = new SqlCommand("Get_Ind_NewCarLoan", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1 = new SqlParameter("@pApplicationId", SqlDbType.Int);
        p1.Value = 1;
        cmd.Parameters.Add(p1);
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        con.Open();
        DataSet ds = new DataSet();
        da.Fill(ds, "Get_Ind_NewCarLoan");
        cmd.ExecuteNonQuery();
        if (ds.Tables[0].Rows.Count  > 0)
        {
            txtShowRoomName.Text=ds.Tables[0].Rows[0]["ShowRoomName"].ToString();
 txtVehicleName.Text=ds.Tables[0].Rows[0]["VehicleName"].ToString();
 txtVehicleNumber.Text=ds.Tables[0].Rows[0]["VehicleNumber"].ToString();
 txtYearOfManufacture.Text=ds.Tables[0].Rows[0]["YearOfManufacture"].ToString();
 txtExShowRoomPrice.Text=ds.Tables[0].Rows[0]["ExShowRoomPrice"].ToString();
 txtLifeTax.Text=ds.Tables[0].Rows[0]["LifeTax"].ToString();
 txtInsuranceVehicle.Text=ds.Tables[0].Rows[0]["InsuranceVehicle"].ToString();
 txtOnRoadPrice.Text=ds.Tables[0].Rows[0]["OnRoadPrice"].ToString();
 txtLoanAmount.Text=ds.Tables[0].Rows[0]["LoanAmount"].ToString();
 txtInsurance.Text=ds.Tables[0].Rows[0]["Insurance"].ToString();
 txtSuraksha.Text=ds.Tables[0].Rows[0]["Suraksha"].ToString();
txtOthers.Text=ds.Tables[0].Rows[0]["Others"].ToString();
 txtTotalLoanAmount.Text=ds.Tables[0].Rows[0]["TotalLoanAmount"].ToString();
 txtShowRoomAddress.Text=ds.Tables[0].Rows[0]["ShowRoomAddress"].ToString();
 txtProccesingFee.Text=ds.Tables[0].Rows[0]["ProccesingFee"].ToString();
 txtStampDuty.Text=ds.Tables[0].Rows[0]["StampDuty"].ToString();
 txtSuraksha1 .Text=ds.Tables[0].Rows[0]["SurakshaDeduction"].ToString();
 txtInsurance1 .Text=ds.Tables[0].Rows[0]["InsuranceDeduction"].ToString();
 txtAdvanceEmi.Text=ds.Tables[0].Rows[0]["AdvanceEmi"].ToString();
 txtOthers1 .Text=ds.Tables[0].Rows[0]["OthersDeduction"].ToString();
 txtNetDirsuburcementAmount.Text=ds.Tables[0].Rows[0]["NetDirsuburcementAmount"].ToString();
 txtLoanAmountDetails.Text=ds.Tables[0].Rows[0]["LoanAmountDetails"].ToString();
 txtTenure.Text=ds.Tables[0].Rows[0]["Tenure"].ToString();
 txtEmiAmount.Text=ds.Tables[0].Rows[0]["EmiAmount"].ToString();
 string s1 = ds.Tables[0].Rows[0]["Tenure1"].ToString();
 if (s1 == "ADVANCE"|| s1=="advance")
 {
     ddlTenure.SelectedIndex = 0;
 }
 else if(s1=="arears"||s1=="AREARS")
 {
     ddlTenure.SelectedIndex = 1;
 }
 txtRateOfInterest.Text=ds.Tables[0].Rows[0]["RateOfInterest"].ToString();
 txtLoadingAmount.Text=ds.Tables[0].Rows[0]["LoadingAmount"].ToString();
 txtNotepad.Text=ds.Tables[0].Rows[0]["Notepad"].ToString();
 con.Close();
 ImgBtnUpdate.Visible = false ;
 imgbtnSave.Visible = true;

        }

Thursday, 2 February 2012

How to Place a Connection String In Web.Config File

<connectionStrings>
    <add name="conn" connectionString="Data Source=TIRUPATI\SQLEXPRESS;Initial Catalog=Rightway;Integrated Security=True"/>
  </connectionStrings>

Updating the Record

protected void  imgbtnUpdate_Click(object sender, ImageClickEventArgs e)
{
    if (imgFileUpload.HasFile)
    {
        string fileExt = Path.GetExtension(imgFileUpload.PostedFile.FileName);
        if (fileExt.ToLower() == ".jpeg" || fileExt.ToLower() == ".jpg" || fileExt.ToLower() == "gif" || fileExt.ToLower() == ".png")
        {
            try
            {
                string s = @"~\images\EventsImages\" + imgFileUpload.FileName;
                imgFileUpload.PostedFile.SaveAs(Server.MapPath(s));
                SqlCommand cmd = new SqlCommand("UpdateServices", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter  p1 = new SqlParameter("@pImageService", SqlDbType.VarChar);
                p1.Value = s.ToString();
                cmd.Parameters.Add(p1);
                p1 = new SqlParameter("@pSno", SqlDbType.Int);
                p1.Value = Convert.ToInt32(Session["Sno"].ToString());
                cmd.Parameters.Add(p1);
                p1 = new SqlParameter("@pContentService", SqlDbType.VarChar);
                p1.Value = Editor1.Content;
                cmd.Parameters.Add(p1);
                p1 = new SqlParameter("@pTitleService", SqlDbType.VarChar);
                p1.Value = txtTitle.Text;
                cmd.Parameters.Add(p1);
                con.Open();
                cmd.ExecuteNonQuery();


                lblstatus.Text = "<script>" + Environment.NewLine + "alert('Advertisment Posted Successfully')</script>";

                GetServiceName();
                con.Close();
                imgbtnAdd.Visible = true;
                imgbtnUpdate.Visible = false;
                panel1.Visible = false;
                panel2.Visible = true;
            }

            catch (Exception ex)
            {
                lblMessage.Text = "<script>" + Environment.NewLine + "alert('Advertisment Can Not Be Added')</script>";


            }
        }
    }
    else
    {
        SqlCommand cmd = new SqlCommand("UpdateServices", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1 = new SqlParameter("@pImageService", SqlDbType.VarChar);
        p1.Value = Session["ImageService"].ToString();
        cmd.Parameters.Add(p1);
        p1 = new SqlParameter("@pSno", SqlDbType.Int);
        p1.Value = Convert.ToInt32(Session["Sno"].ToString());
        cmd.Parameters.Add(p1);
        p1 = new SqlParameter("@pContentService", SqlDbType.VarChar);
        p1.Value = Editor1.Content;
        cmd.Parameters.Add(p1);
        p1 = new SqlParameter("@pTitleService", SqlDbType.VarChar);
        p1.Value = txtTitle.Text;
        //p1.Value = Session["TitleService"].ToString();
        cmd.Parameters.Add(p1);
        con.Open();
        cmd.ExecuteNonQuery();
       
        lblstatus.Text = "<script>" + Environment.NewLine + "alert('Advertisment Posted Successfully')</script>";

        GetServiceName();
        con.Close();
        imgbtnAdd.Visible = true;
        imgbtnUpdate.Visible = false;
        panel1.Visible = false;
        panel2.Visible = true;
    }
}

Delete The Record from the Grid View

 protected void deletebtn_Click(object sender, ImageClickEventArgs e)
    {
        if (Session["TitleService"].ToString() == "Events" || Session["TitleService"].ToString() == "Brand Promotions" || Session["TitleService"].ToString() == "Merchandising Services" || Session["TitleService"].ToString() == "Road Shows")
        {
            lbldelete.Text = "Service Can Not Be Deleted";
        }
        else
        {
            SqlCommand cmd = new SqlCommand("DeleteService", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter p1;
            p1 = new SqlParameter("@pSno", SqlDbType.Int);
            p1.Value = Convert.ToInt32(Session["Sno"].ToString());
            cmd.Parameters.Add(p1);
            con.Open();
            cmd.ExecuteNonQuery();
            GetServiceName();
            con.Close();
            lblstatus.Text = "<script>" + Environment.NewLine + "alert('Advertisment Deleted Successfully')</script>";
            panel2.Visible = true;
        }
    }

How To Edit the Row In Data Grid View

protected void GalleryView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            int id = Convert.ToInt32(e.CommandArgument);
            Session["Sno"] = id.ToString();
            SqlCommand cmd = new SqlCommand("Select TitleService from RW_Gallerys where Sno='" + id.ToString() + "'", con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read() == true)
            {
                Session["TitleService"] = dr[0].ToString();
            }
            dr.Close();
            SqlDataAdapter da = new SqlDataAdapter("select ImageServices from RW_GallerysImage where Sno='" + id.ToString() + "'", con);

            DataSet ds = new DataSet();
            da.Fill(ds, "RW_Gallerys");
            GalleryList.DataSource = ds.Tables[0];
            GalleryList.DataBind();
            panel1.Visible = false;
            panel2.Visible = true;
            AddImages.Visible = true;

        }
    }

How To Upload Multiple Images In to DataBase

if (imgFileUpload.HasFile)
            {
                HttpFileCollection hfc = Request.Files;

                if (hfc.Count > 0)
                {
                    for (int i = 0; i < hfc.Count; i++)
                    {
                        HttpPostedFile hpf = hfc[i];
                        if (hpf.ContentLength > 0)
                        {

                            string ext = System.IO.Path.GetExtension(hpf.FileName);
                            if (ext == ".jpg" || ext == ".bmp" || ext == ".gif" || ext== ".pdf" || ext == ".doc" || ext == ".docx")
                            {

                                buffer = new byte[hpf.ContentLength];

                                float bytes = hpf.InputStream.Read(buffer, 0, (int)hpf.ContentLength);
                                float size = bytes / 1024;
                                string s = @"~\images\galleryTestImages\" +hpf.FileName;
                                hpf.SaveAs(Server.MapPath(s));
                                string s1="insert into RW_GallerysImage values("+Convert.ToInt32(Session["Sno"].ToString())+",'"+s.ToString()+"')";
                                SqlCommand cmd = new SqlCommand(s1,con);
                                //cmd.CommandType = CommandType.StoredProcedure;
                                //SqlParameter p1 = new SqlParameter("@pImagePath",SqlDbType.VarChar);
                                //p1.Value = s.ToString();
                                //cmd.Parameters.Add(p1);

                                //p1 = new SqlParameter("@pTitleService",SqlDbType.VarChar);
                                //p1.Value = txtTitle.Text;
                                //cmd.Parameters.Add(p1);
                                con.Open();
                                cmd.ExecuteNonQuery();
                                //cmd2.ExecuteNonQuery();

                                lblstatus.Text = "<script>" + Environment.NewLine +"alert('Advertisment Posted Successfully')</script>";
                                GetServiceName();
                                con.Close();
                                panel2.Visible = true;
                                panel1.Visible = false;
                                txtTitle.Text = "";
                               
                            }
                        }
                    }

                }
            }

How TO Upload The Images

 if (flMemberImage.HasFile)
            {

                string ext = System.IO.Path.GetExtension(flMemberImage.FileName);

                if (ext == ".jpg" || ext == ".bmp" || ext == ".png")
                {

                    imagepath = @"~\memberimage\" + flMemberImage.FileName;
                    flMemberImage.SaveAs(Server.MapPath(imagepath));
                    obj.addBachatGhatMember(Convert.ToInt32(Session["villageid"]), Session["VillagName"].ToString(), txtMemberName.Text, editor.Content, imagepath);
                    lblMessge.Text = "<script>" + Environment.NewLine + "alert('Member  added sucessfully')</script>";
                    // Panel1.Controls.Add(lblMessge);
                    panel1.Controls.Add(lblMessge);
                    clear();
                    getMemberByVillageId();
                }
                else
                {
                    lblMessge2.Text = "<script>" + Environment.NewLine + "alert('Member  can not be added')</script>";
                    //Panel2.Controls.Add(lblMessge2);
                    panel2.Controls.Add(lblMessge2);
                    getMemberByVillageId();
                    clear();
                }
            }
            else
            {
                obj.addBachatGhatMember(Convert.ToInt32(Session["villageid"]), Session["VillagName"].ToString(), txtMemberName.Text, editor.Content, "N");

                lblMessge3.Text = "<script>" + Environment.NewLine + "alert('Member  added sucessfully')</script>";
                panel3.Controls.Add(lblMessge3);
            }

Wednesday, 1 February 2012

Inside MVC Architecture

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?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. 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 CS files
    • Global.asax
    • Web.config

ASP.NET MVC Execution Life Cycle

Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]: