Wednesday, June 17, 2015

Shopping Cart with Form Web Application with Asp.Net (Part 1)

In this project, we will design a website that displays information and allow user to add products into shopping cart. We willl design four pages that hold product information.

Firstly we will add a class that's name is Product.cs.(Add New Item -> Class).This file contains information about the products.Let Visual Studio create the App_Code folder for Product.cs.

Define a constructor for the Product class  which takes all of its member variables as parameter.

Product class should be like below.


public class Product
{
    public int ProductID;
    public string Type;
    public string Vendor;
    public string Model;
    public string ImageUrl;

    public int globalvar;
    public  static ArrayList proCopy;
    public static int id;
    public Product(int ProductID, string Type, string Vendor, string Model, string ImageUrl)
    {
        this.ProductID = ProductID;
        this.Type = Type;
        this.Vendor = Vendor;
        this.Model = Model;
        this.ImageUrl = ImageUrl;
        
    }
    public Product()
    { 
    
    }

    public void AddIndex(int n)
    {
        id = n;
    
    }

    public int getIndex()
    {
        return id;
    }
    public void copyArray(System.Collections.ArrayList array)
    {
        proCopy = array;
        
    }
    public System.Collections.ArrayList getArray()
    {
        return proCopy;
    }
   
}
Design Default.aspx
In Default.aspx page check if the user logged in or not.We use cookie check.The cookie should contain only first name and last name of the user. If no such cookie is defined, then should be displayed a message then link to the Login.aspx.
Fig. 1 – Default.aspx when user is not logged in.


When Login button is clicked, first name and last name will be written into a cookie named UserInfo for one month and will redirect to the left of Default.aspx.
 In Login.aspx.cs click method.

 protected void btnLogin_Click(object sender, EventArgs e)
    {
        //Create new cookie
        HttpCookie cookie = new HttpCookie("UserInfo");
        
        // add name and lastname to the cookie
        cookie["UserInfo"] = txtFirstName.Text+" "+txtLastName.Text;
        if (txtFirstName.Text == null || txtLastName.Text == null)
        {
            //lblLogin.Text = "Please specify valid Name and LastName";
        }
        else
        {
          //Define cookie for one month

            cookie.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(cookie);

            Response.Redirect("Default.aspx");
        }
    }
In Default.aspx.cs file we get cookie data with Request.Cookies["UserInfo"]. If cookie is null, redirect to login page.If cookie store data of user info, allow the see product information.

 protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie cookie = Request.Cookies["UserInfo"];




        if (cookie == null )  // if no cookies
        {
            lblExistingCookie.Text = "You are not login  Please login ";
            hyperlink1.Visible = true;
            lnkBtnCart. Visible = false;
            btnLogout.Visible = false;
            linkSamC2.Visible = false;
            linkSamE2.Visible = false;
            linkToshiba.Visible = false;
            linkLenova.Visible = false;
            linkAcer.Visible = false;
            lblHyper.Visible = false;

        }
        else
        {
            
            //  lblExistingCookie.Visible = true;
            hyperlink1.Visible = false;
            lblExistingCookie.Text = "Welcome " + cookie["UserInfo"] + "!";
            lnkBtnCart. Visible = true;
            btnLogout.Visible = true;
            linkSamC2.Visible = true;
            linkSamE2.Visible = true;
            linkToshiba.Visible = true;
            linkLenova.Visible = true;
            linkAcer.Visible = true;
            lblHyper.Visible = true;

        }

        if (!Page.IsPostBack) // first load create five product
        {


            //create Product objects
            
            Product part1 = new Product(1,"Phone","Samsung","C270","samsung.jpg");
            Product part2 = new Product(2,"Phone","Samsung","E250i","samsungE2.jpg");
            Product part3 = new Product(3,"Laptop","Toshiba","L500","toshiba.jpg");
            Product part4 = new Product(4,"Laptop","Lenova","G550","lenova.jpg");
            Product part5 = new Product(5,"Netbook","Acer","FO200","acer.jpg");
        
            //Add objects to the session state

            Session["Product1"] = part1; 
            Session["Product2"] = part2;
            Session["Product3"] = part3;
            Session["Product4"] = part4;
            Session["Product5"] = part5;
        }
        if(btnLogout.Visible == true)
        {
            linkSamC2.Visible = true;
            linkSamE2.Visible = true;
            linkToshiba.Visible = true;
            linkLenova.Visible = true;
            linkAcer.Visible = true;
            lblHyper.Visible = true;

           
        }
    }
Default.aspx file when user entered with name and last name
We Design Login.aspx and Default.aspx page. Then we continue to design ProductInfo.aspx page that display information of product.Then design Cart.aspx. It will done for display all products that are added to shopping cart. See You..

Sunday, June 14, 2015

Download multiple files as a Zip file with Asp.Net

While doing project, you may need load system to multiple files. After saving it, you may  need to download them to your PC. You can download them as  a Zip by using Asp.Net.

Initially in View, define button that triggers to download files.

<a href="@Url.Action("ControllerMethod", "ControllerName", new {id = 12})" class="btn btn-success"><i class="fa fa-download"></i> Export File </a>

  • In View, like above, we define button which trigger the method in Controller. In @Url.Action firstly define Controlller method name, after that,  define Controller name. If we want to  send parameter to controller method, wecan specify it like this 'new {id=12} '. Use <i class="fa fa-download"></i>  to get an download icon object on button.

In Controller:

      You can reach parameter value with id which we can specify like this in View. To get Zip file we should include System.IO.Compression namespace and add System.IO.Compression.dll to project.
We will use ZipArchive.CreateEntry method to create an empty entry in the zip archive.
To get more please visit link.

 
public ActionResult ControllerMethod(int id)
        {


            using (var compressedFileStream = new MemoryStream())
            {

                using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                {

                    //get list of file
                    var listOfFile = _servis.GetListOfFiles(id);

                    int i = 1;

                   //loop all  the files which export
                   
             foreach (var file in listOfFile )
                 {
                 //get file name
                  string fileName = file.fileName;
                                            
                        var zipEntry11 = zipArchive.CreateEntry(fileName);

                        if (file != null)
                        {
                          //get file content
                          using (var originalFileStream = new MemoryStream(file.fileContent.ToArray()))
                            {

                            using (var zipEntryStream = zipEntry11.Open())
                            {
                            await originalFileStream.CopyToAsync(zipEntryStream);
                            }
                           }
                        }
                        i++;
                    }

                }

                //Add multiple file in a zip file
                return File(compressedFileStream.ToArray(), "application/zip",    "FileName.zip");
            }
        }


Saturday, June 6, 2015

ViewBag with Multiple SelectList in Asp.Net Mvc

     ViewBag used as a bag to move data from Controller toView. In my daily software life, use it frequently. In ViewBag you can store string, integer,. vs values or list. In View you can want to select multiple item from the list. Now i want to share how to select multiple items from list which store in ViewBag.

In Controller, get all personels with the _service.GetPersonel() method.To select multiple personels, should define Multiple before SelectList. If you select only one personel, can define new SelectList(). In ViewBag we shsould store personels' name and surname in Text, idtPersonel in Value.






  • In Controller

  •  public ICollection<int> idtPersonels{ get; set; }
    
    
            ViewBag.Personeller =  new MultiSelectList( (_service.GetPersonels())
              .Select(x => new SelectListItem
                            {
                                Text = x.Name+ " " + x.Surname+ " " + x.ID,
                                Value = x.idtPersonels.ToString()
                            }), "Value", "Text");



    In View, users store selected personels in idtPersonels. To use multiple property of  DropDownListFor , create class and call select2 and make  @multiple property  true. Please visit what is Select2 to get more info. 





  • In View

  •  <div class="form-group">
                                                            
          @Html.DropDownListFor(m => m.idtPersonels, (MultiSelectList)ViewBag.Personeller , new { @class = "form-control select2", @multiple = true })
                             
      </div>




    After select multiple personels in View, We can reach these selected personels like this.





  • In Controller

  •  public ActionResult GetPersonel(FormCollection form)
    {   
        //in form["idtPersonels"] store id like : {12,45,85}, and we must split them
       
     string[] listOfPersonel =           form["idtPersonels"].ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
    }