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);
    }

    Saturday, May 30, 2015

    Moving Files To Disc


         This project is done for log files which make crowd to move  when they fill the space of disc.Did this project while working as intern.

         They complained about logs which filled the disc space and crash the system.This project which i did, automatially sorted logs by creation date. Then they fill them in files and zipped. Then move this zipped files to desired location.Thanks to this, you never lost log files, and can reach any of them by looking creation time.

        Also you can specify source and target disc name, and amount of files which will move. Developed with C# Windows Desktop . 

    In Visual Studio when you want to pass parameters to application from outside you can right click the project and  add General -> Settings File.

    Add Settings File

         After adding Settings File, enter parameter which use in projects.




    SourceFolder: Location of Moving File from it
    TargetFolder: Location of Moving File to it
    WarningAmountOfFileSize: how much disc size fill the disch and  trigger to move
    AmountOfPercentForMovingFull : Amount of percent of files which will move

    In Type specify the type of variables and for Scope choose the Application.


    In Program.cs in Main method you can reach the parameter:

      string directoryName = Settings.Default.TargetFolder;


    In main method specify below.



    
     
    public static void Main(string[] args)
            {
                Program myProgram= new Program();
    
                //prevent multiple instance of C# application
                
                if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
                {
                    Console.WriteLine("Only one instance allowed");
                    Environment.Exit(0);
                }
                else
                {
    
    
                    /*create target directory to store log files*/
    
                    DateTime dailyDate = DateTime.Now;
                   
    
                   String directoryTargetName =  myProgram.GetTargetDirectoryName(dailyDate);
                   
                    int count = 0;
                    //listing all files in disk
                    string[] a1 = Directory.GetFiles(@Settings.Default.SourceFolder);
    
    
                    //get free disk space
                    string sourceDriverName = Settings.Default.SourceFolder.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
    
                    string targetDriverName = Settings.Default.TargetFolder.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
    
                    /*Specify Target Directory and check its availability*/
    
    
                    string _directoryNameS = Settings.Default.TargetFolder + "\\" + directoryTargetName;
    
                    myProgram.CheckExistDirectory(_directoryNameS);
    
    
                    Boolean bFlag= myProgram.ControlOfCapacitySourceAndTargetDisc(sourceDriverName,targetDriverName);
                  
    
    
                    //Display all files
                    Console.WriteLine("-----Files -------");
                    foreach (string name in a1)
                    {
                        Console.WriteLine(name);
    
                    }
    
                    Console.WriteLine("----Sorted Array by creation date------");
    
                    //display sorting array
                    //sort file by creation date
    
                    IComparer fileComparer = new CompareFileByDate();
                    Array.Sort(a1, fileComparer);
    
                    foreach (string f in a1) // count file numbers
                    {
                        count++;
                        Console.WriteLine(f);
                    }
    
                    //Move directories to another disc
                    string destinationFile = @Settings.Default.TargetFolder; // destination disc
                    Console.WriteLine("**********************************************");
    
    
                    //calculate amount of moving from source to target disc
                    decimal AmountOfMoving = Convert.ToDecimal(count) * Settings.Default.AmountOfPercentForMovingFull;
                   
                    int countSon = Convert.ToInt32(AmountOfMoving);
    
    
                     // control of target disc's free space
                    decimal division = myProgram.GetDivision(sourceDriverName); // get division
                       
                    if (bFlag && division <= Settings.Default.WarningAmountOfFullSize) // what percent of disc is moving
                        {
                            Console.WriteLine("Warning,80 percent of disk is full");
                            Console.WriteLine("you must carry move files another free disk");
                            Console.WriteLine("%d of files are moving " + countSon);
    
                            foreach (string f in a1)
                            {
    
                                Console.WriteLine(f);
                                string lastDirectory = f.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
    
                                File.Move(f, _directoryNameS + "\\" + lastDirectory); // store in dateTime directory
    
                                countSon--;
                                if (countSon == 0)
                                {
                                    break;
                                }
    
                            }
                        }
                        else
                        {
                            Console.WriteLine("You have enough space for saving files..");
                        }
                   
                      
                   
    
                }
    
            }
    
    
    
    
    //Check the existence of directory
     
    
      public void CheckExistDirectory(String directoryName)
            {
    
                //check folder exists
    
                if (Directory.Exists(directoryName))
                {
                    Console.WriteLine("Warning !!! This directory is exists ..");
                }
    
                else
                {
    
                    Console.WriteLine("Created Directory successfully ..");
                    Directory.CreateDirectory(directoryName);
                }
            }
    
    
    
    
    
    
        
            /// Calculate Capacity of Discs
                    public Boolean ControlOfCapacitySourceAndTargetDisc(String sourceDriverName, String targetDriverName)
            {
    
                /*Calculate amount of logs in Source Driver*/
                DriveInfo dS = new DriveInfo(sourceDriverName);
                Console.WriteLine("Total size of Source Driver : " + dS.TotalSize);
                Console.WriteLine("Total free size of Source Driver: " + dS.TotalFreeSpace);
                decimal totalSizeS = dS.TotalSize;
                decimal totalFreeSizeS = dS.TotalFreeSpace;
                decimal amountOfUsing = totalSizeS - totalFreeSizeS;
    
                Console.WriteLine("önceki gidecek kısım : " + amountOfUsing);
                amountOfUsing = amountOfUsing * Settings.Default.AmountOfPercentForMovingFull; // taşınacak miktarın büyüklüğü
                Console.WriteLine("tasinacak kısım : " + amountOfUsing);
    
                /*Control of Target Driver Capacity*/
                DriveInfo dD = new DriveInfo(targetDriverName);
    
                Console.WriteLine("Total free space of Target Disc: " + dD.TotalFreeSpace);
                decimal totalFreeSizeD = dD.TotalFreeSpace;
    
                Console.WriteLine("gidecek kısım : " + amountOfUsing + "yer var var mı : " + totalFreeSizeD);
               
    
                if (amountOfUsing <= totalFreeSizeD)
                {
                    return true;
                }
                else 
                {
                    Console.WriteLine("Warninng !!!  You do not have enough target space for moving ");
                    return false;
    
                }
            
            }
    
    
    
    
    
      public class CompareFileByDate : IComparer
            {
                /// 
                /// Metod açıklaması
                /// 
                /// param1
                /// param2
                /// 
                public int Compare(Object a, Object b)
                {
                    FileInfo fia = new FileInfo((string)a);
                    FileInfo fib = new FileInfo((string)b);
    
                    DateTime cta = fia.CreationTime;
                    DateTime ctb = fib.CreationTime;
    
                    return DateTime.Compare(cta, ctb);
                }
            }