Thursday, February 6, 2014

FileUploadControl using Ajaxcalls

We can submit the form data like files or any other data like textbox fields like this(Using simple ajax call):

var formdata = new FormData( );
//Here i am passing the form data like this
var ComposeEmailReq = { MailFrom: MailFrom, MailTo: MailTo, ReplyTo: ReplyTo, Subject: Subject, Body: Body, Forwardattachment: details,CC:cc,BCC:bcc};

            //file uploading using ajax.
            formdata.append("Details", JSON.stringify(ComposeEmailReq));
            for (var i = 0; i < $("#fupAttachments")[0].files.length; i++) {
                //we can appending the files like this
                formdata.append("Attachments", $("#fupAttachments")[0].files[i]);
            }

Thursday, July 18, 2013

How to Import data from excel sheet to datatable and bind to listview

Here what we are doing is we have to upload the file into our application and the import data into the data table and then delete the file from our application.
After uploading the document using Fileupload control we have to check weather the upload document is path existing or not,file format is correct or not

Note : excel sheet format should be like this
      Sno      Email
        1         1@1.1
        2         2@2.2

protected void btnImportto_Click(object sender, EventArgs e)
        {
            try
            {
                //Checking weather file exist or not
                if (uploadExcel.HasFile)
                {
                    //checking the weather existing file has extension .xlsx or .xls
                    if (Path.GetExtension(uploadExcel.FileName) == ".xlsx" ||                              Path.GetExtension(uploadExcel.FileName) == ".xls")
                 {
                        //getting path here
                        string filepath = Server.MapPath("~/");
                        //saving into paticular path
                        uploadExcel.SaveAs(filepath + uploadExcel.PostedFile.FileName);
                        //exact file path
                        string relativePath = Server.MapPath("~/" + uploadExcel.PostedFile.FileName);
                        lblStatusmsg.Text = "Upload status: File uploaded!";
                        //importing data from the excel sheet to our application
                        TestExcel(relativePath);
                    }
                    else
                    {
                        lblStatusmsg.Text = "The file you uploaded has invalid extension,Please upload xls or xlsx file";
                    }

                    string filepathtodelete = Server.MapPath("~/"+uploadExcel.PostedFile.FileName);
                    if (uploadExcel.HasFile)
                    {
                        //delete file from the respective path
                        File.Delete(filepathtodelete);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

private void TestExcel(string filePath)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbook book = null;
            Range range = null;
            try
            {
                app.Visible = false;
                app.ScreenUpdating = false;
                app.DisplayAlerts = false;
                string execPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                //Getting the Excel path

                book = app.Workbooks.Open(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                                  , Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                foreach (Worksheet sheet in book.Worksheets)
                {
                    Console.WriteLine(@"Values for Sheet " + sheet.Index);
                    // get a range to work with
                    range = sheet.get_Range("A1", Missing.Value);
                    // get the end of values to the right (will stop at the first empty cell)
                    range = range.get_End(XlDirection.xlToRight);
                    // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                    range = range.get_End(XlDirection.xlDown);
                    // get the address of the bottom, right cell
                    string downAddress = range.get_Address(false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
                    // Get the range, then values from a1
                    range = sheet.get_Range("A1", downAddress);
                    object[,] values = (object[,])range.Value2;
                    // View the values
                    Console.Write("\t");
                    Console.WriteLine();
                    for (int i = 2; i <= values.GetLength(0); i++)
                    {
                        for (int j = 1; j <= values.GetLength(1); j++)
                        {
                            //Console.Write("{0}\t", values[i, j]);
                            System.Data.DataTable dtbulk = new System.Data.DataTable();

                            if (Session["BulkReceipts"] == null)
                            {
                                //here we are creating the colums
                                //Here you can add the columns as your wish
                                dtbulk.Columns.Add("Active", typeof(bool));
                                dtbulk.Columns.Add("Receiptent");
                            }
                            else
                            {
                                dtbulk = (System.Data.DataTable)Session["BulkReceipts"];
                            }
                             //Here we getting paticular colum value or text              
                            String strContains = values[i, j].ToString( );
                            if (strContains.Contains("@"))//Checking weather mailid or not
                            {
                                dtbulk.Rows.Add(true, values[i, j]);
                                //dtbulk = (System.Data.DataTable)Session["Receipts"];
                                Session["BulkReceipts"] = dtbulk;
                                //dtbulk.Rows.Clear();
                            }
                        }
                    }
                    if (Session["BulkReceipts"] != null)
                    {
                        System.Data.DataTable dtbulk = (System.Data.DataTable)Session["BulkReceipts"];
                       //here i am adding the data to listview
                        lvReceiptents.DataSource = dtbulk;
                        lvReceiptents.DataBind();
                    }
                }
            }
            catch (Exception e)
            {
               //Console.WriteLine(e);
            }
            finally
            {
                range = null;
                if (book != null)
                    book.Close(false, Missing.Value, Missing.Value);
                book = null;
                if (app != null)
                    app.Quit();
                app = null;
            }
        }


How to bind the records to a list in MVC


  • The major advantage in MVC is there is no need to write Bulk amount of code. Here by writing the single line of code we can bind the records from database to list....

VIEW::viewlist.aspx:
<body>
    <table>
        <tr>
            <th></th>
            <%--<th>
                EmpID
            </th>--%>
            <th>
                Code
            </th>
            <th>
                Salary
            </th>
            <th>
                CustomerName
            </th>
        </tr>

    <% foreach (var item in Model) { %>
    
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Editcustomer","Customer", new { id =item.EmpID }, new object { })%> |
                <%: Html.ActionLink("Details", "Details", new { id = item.EmpID })%> |
                <%: Html.ActionLink("Delete", "DeleteCustomer", new { id = item.EmpID })%>                
            </td>
           <%-- <td>
                <%: item.EmpID %>
            </td>--%>
            <td>
                <%: item.Code %>
            </td>
            <td>
                <%: item.Salary %>
            </td>
            <td>
                <%: item.CustomerName %>
            </td>
        </tr>
    
    <% } %>

    </table>

    <p>
        <%: Html.ActionLink("Create New", "returntofillcustomer1", "Customer")%>
    </p>

</body>

Controller:: Customer

//Here we are binding the list of customers to list
public ActionResult Viewlist()
        {  
            //here we are returning the list of customers from the model class(from tb_EmpDetails)
            return View(Customer.GetCustomerDetails());
        }

Modelclass:: Customer.cs

//Here we are returning the employee list
 public static List<tb_EmpDetails> GetCustomerDetails( )
        {
            var customer1 = new CustomerEntities1( );//CustomerEntities1 is nothing but Database (.emdf) file
            //adding all the records from tb_EmpDetails to the list and returning the list
            return customer1.tb_EmpDetails.ToList( );
        }







Monday, July 8, 2013

How to insert data into table in MVC

After filling the form and click the submit, definately  the the form will post some data
View: fillcustomer1.aspx
<body>
    <% using (Html.BeginForm("FillCustomer1", "Customer", FormMethod.Post))
       {%>
        <%: Html.ValidationSummary(true) %>

        <fieldset>
            <legend>Fields</legend>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Code) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Code) %>
                <%: Html.ValidationMessageFor(model => model.Code) %>
            </div>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.CustomerName) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.CustomerName) %>
                <%: Html.ValidationMessageFor(model => model.CustomerName) %>
            </div>
         
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Salary) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Salary) %>
                <%: Html.ValidationMessageFor(model => model.Salary) %>
            </div>
         
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Viewlist","Customer")%>
    </div>
</body>

Now we have to insert the data into database:

Controller: Customer: in the below code CustomerEntities1  is nothing but our database(.emdx) file

        [Authorize] //Here we are just designing our action with authorize for form authentications
        [HttpPost]
        public ActionResult FillCustomer1(tb_EmpDetails emp_details)
        {
            //here we are using the .edmx(copy of database) file.....
            using (CustomerEntities1 customerdetails = new CustomerEntities1())
            {
                if (ModelState.IsValid)
                {
                    //here we are passing(adding) the  values to table using addtotable
                    customerdetails.AddTotb_EmpDetails(emp_details);
                    //after adding the values to table save the table
                    customerdetails.SaveChanges();
                    //redirecting from one action to another action
                    return RedirectToAction("Viewlist", "Customer");
                }
                else
                {
                    ModelState.AddModelError("", "Please enter fields properly");
                    //Content("<script language='javascript' type='text/javascript'>alert('Please enter fields properly');</script>");
                    return View();                      
                }
            }

        }


Friday, June 7, 2013

HOW TO DELETE ROWS FROM A TABLE WITHOUT USING WHERE CONDITION

If we want to delete top 1 row (or) top 2 (or) top 3 (or) top 5 ... etc

We use the query below

Syntax::  Delete top (no. of rows) from <table name>

example:: delete top (2) from tbEmployees

USE OF LOGGERS IN ASP.NET

The main purpose of creating logger file in our project is that, after deploying our project in to the server we are not able to check the errors or line by line debugging, In that time we have to know , what are the errors are coming when our project is running on the live(available in the website).

In that time if we use the below code in our project, then all the errors will be saved/stored in a text document in our system in a folder.

Why i wrote the path in web.config file means, when we are Hosting(up) our project in to server, in that time we will change only web.config file not the code.
You can save this log files in your database also.
-->We are creating our logger text file in E: Drive.(We can change the drive also)


<appSettings>
<add key="log" value="E:\\Logger.Log"/>
</appSettings>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.IO;

namespace Project
{
   public static class logger
    {
       public static void log(string className, string method, string message)
        {
            FileStream fs=null; StreamWriter sw=null;
            try
            {
                // Here we are calling the path from web.config file
                string str=ConfigurationManager.AppSettings["log"];
                fs = new FileStream(str, FileMode.Append);
                sw = new StreamWriter(fs);
                sw.WriteLine(DateTime.Now.ToString() + "\t" + className+ "\t" + method + "\t" + message);
                //Don't forgot to close Stream Writer before File Stream
                sw.Close();
                fs.Close();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                if(sw!=null)
                    sw.Close();
                if(fs!=null)
                    fs.Close();
            }
        }
    }
}


// how we will use this Logger method in our project

public class MessageDB
    {
public void InsertMessage(long UID, MessageType Type, string Message, string Remarks)
        {
// logger is the class name and log is the method name
           logger.log(" MessageDB","InsertMessage","Begin");          
            try
            {
               // our code
                    logger.log(" MessageDB", "InsertMessage", "End");
                }
            }
            catch (Exception ex)
            {
                logger.log("MessageDB", "InsertMessage", "Exception" + ex.Message);              
               throw ex;
            }
            finally
            {

            }
        }


// how the file is stored in our directory
In the text file format it will store.
Logger.Log // text file(Logger.Log is file name)
the text inside of the file will be stored like below

--> If we wont get any error in our project means the text look like blow
6/8/2013 10:37:15 AM     " MessageDB",   "InsertMessage",   "Begin"
6/8/2013 10:37:15 AM    " MessageDB",    "InsertMessage",    "END"

--> If we got any error in our project means the text look like blow
6/8/2013 10:37:15 AM Login login Start
6/8/2013 10:37:15 AM UserBiz AuthenticateUser start
6/8/2013 10:37:15 AM UserBiz AuthenticateUser end
6/8/2013 10:37:15 AM UserDB AutenticateUser start
6/8/2013 10:37:15 AM UserDB AuthenticateUser MessageCannot open database "EmployeeDataBase" requested by the login. The login failed.


PURPOSE OF STREAM WRITER IN C#.NET:-
StreamWriter writes text files. It enables easy and efficient text output. It is best placed in a using-statement to ensure it is removed from memory when no longer needed. It provides several constructors and many methods.
We first declare and initialize a new StreamWriter instance in a using construct. Please note how the System.IO namespace is included at the top of the file. The keyword using means different things in different places.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace StreamReadWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get the directories currently on the C drive.
            DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();

            // Write each directory name to a file. 
            using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
            {
                foreach (DirectoryInfo dir in cDirs)
                {
                    sw.WriteLine(dir.Name);

                }
            }

            // Read and show each line from the file. 
            string line = "";
            using (StreamReader sr = new StreamReader("CDriveDirs.txt"))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
    }
}