Wednesday 23 November 2016

upload and crop images using handler and javascript

========================================================================
Html code
========================================================================

  <input type="file" style="right: -8px; bottom: 40px; width: 11px; position: absolute; display: block; opacity: 0;"id="file_upload" name="file_upload"  onchange="return SaveImage(this);">
                            <a href="javascript:openFileSelector()"  class="edit transition" /><i></i>
========================================================================
Upload Image and crop using Handler and javascript
========================================================================


    <script type="text/javascript">

        function openFileSelector() {
            document.getElementById("file_upload").click();
        }

        function SaveImage(input) {
 
            show_progress();
            setTimeout(function () {                          
         
                var fileUpload1 = $(input).get(0);                      
                var files1 = fileUpload1.files;
                if (files1.length > 0) {

                    var D_Name1 = fileUpload1.files[0].name;
                    if ((D_Name1 != null) || (D_Name1 != "")) {
                        var FileExtension1 = checkFileExtension(D_Name1);
                        if (FileExtension1 == 'png' || FileExtension1 == 'jpg' || FileExtension1 == 'jpeg') {
                                                     
                            var size = parseFloat($("#file_upload")[0].files[0].size / 1024).toFixed(2);
                                                   
                            if (size > 1024 || size < 5) {

                                swal("Your image size " + size + " KB.\n" + "Please upload image  between 5 KB - 1 MB Size ");
                                hide_progress();
                                return false;
                            }
                            else {

                               var data1 = new FormData();
                                for (var i = 0; i < files1.length; i++) {
                                    data1.append(files1[i].name, files1[i]);
                                }
                                $.ajax({
                                    type: 'POST',
                                    processData: false,
                                    contentType: false,
                                    cache: true,
                                    data: data1,
                                    async: false,
                                    url: "/Content/Handler/UploadImage.ashx?files=" + D_Name1,
                                    success: function (response) {

                                        if (response == null) {
                                            return false;
                                            hide_progress();
                                        }
                                        else {
                                            debugger
                                            var a = "/Content/Upload/ResizeImage/" + response;
                                            $('#abc').attr('src', a);
                                            $('#imguserprofile').attr('src', a);
                                            SaveImageName(response);
                                         }
                                    }
                                });
                            }
                         }
                                                           
                        else {
                            $("#endTimeLabel").text('');
                            swal(FileExtension1 + ' File type is not supported');
                            hide_progress();
                            return false;
                        }
                    }
                }
            }, 2000);
        }

        function checkFileExtension(_input) {
            var FileExtension = _input.substring(_input.lastIndexOf('.') + 1).toLowerCase();
            return FileExtension;
        }

        function SaveImageName(ImageName) {
       
            var url = "/LegalDocument/saveImageName/";
         
            $.ajax({
                url: url,
                data: { ImageName: ImageName },
                cache: false,
                type: "POST",
                async: false,
                success: function (data) {
                   hide_progress();
                },
                error: function (reponse) {
                    swal("error : " + reponse);
                    hide_progress();
                    }
            });
        }

     </script>

========================================================================
Create a ashx extention file like thise: Downloadattatchment.ashx
========================================================================

  public class UploadImage : IHttpHandler
    {
        string SetDoc = "";
        string filename = string.Empty;
        string Tempfilename = string.Empty;
        private static Random RNG = new Random();
        public string Create16DigitString()
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            while (builder.Length < 16)
            {
                builder.Append(RNG.Next(10).ToString());
            }
            return builder.ToString();
        }



        public void ProcessRequest(HttpContext context)
        {
            {
                context.Response.ContentType = "text/plain";
                context.Response.Expires = -1;
                try
                {

                    string TempName = "";
                    string filePath = "";
                    string files = context.Request.QueryString["files"];

                    HttpFileCollection postedFiles = context.Request.Files;
                    string[] a = postedFiles.AllKeys;
                    int TemppostedFiles = postedFiles.Count;
                    string[] SplitFiles = files.Split('*');

                    for (int i = 0; i < TemppostedFiles; i++)
                    {
                        string TempData = SplitFiles[i].ToString();
                        string temp = a[i].ToString();
                        for (int j = 0; j < TemppostedFiles; j++)
                        {
                            if (TempData == a[j].ToString())
                            {
                                TempName = DateTime.Now.ToString("yyyyddMMmmss");
                                filePath = context.Server.MapPath("~/Content/Upload/FullSizeUserImage/" + TempName + "_" + i + TempData);
                                postedFiles[i].SaveAs(filePath);
                                SetDoc = SetDoc + "#" + TempName + "_" + i + postedFiles[j].FileName;
                                System.Drawing.Image imgMediumSize = System.Drawing.Image.FromFile(filePath);
                                Image convertedImage = ResizeImage(imgMediumSize, 220, 196);
                                // imgMediumSize = resizeImageLeftSideProfilePic(imgMediumSize);
                                string pathMiddleSizeUserImage = context.Server.MapPath("~/Content/Upload/ResizeImage/" + TempName + "_" + i + TempData);
                                convertedImage.Save(pathMiddleSizeUserImage);
                                // imgMediumSize.Save(pathMiddleSizeUserImage);
                            }

                            //context.Response.Write(filename_img_165px_165px);
                        }
                    }
                    SetDoc = SetDoc.Remove(0, 1);
                    context.Response.Write(SetDoc);
                }
                catch (Exception)
                {
                    context.Response.Write(SetDoc);
                }
            }

        }
       
        static Image ResizeImage(Image image, int desWidth, int desHeight)
        {
            int x, y, w, h;

            if (image.Height > image.Width)
            {
               // w = (image.Width * desHeight) / image.Height;
                h = (image.Height * desWidth) / image.Width;
                w = desWidth;
                y = 0;
                x = 0;
            }
            else
            {
       
                h = desHeight;
             
                w = (image.Width * desHeight) / image.Height;
              // h = (image.Height * desWidth) / image.Width;
                y = 0;
                x = 0;
             
            }

            var bmp = new Bitmap(w, h);

            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(image, x, y, w, h);
            }

            return bmp;
        }
       
       
       
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Import database into Excel file in .net


Using these dll
1. ClosedXML.dll
2. DocumentFormat.OpenXml
======================================================================
  1st method  btn click
======================================================================

   protected void linkDonwloadDatabase_Click(object sender, EventArgs e)
        {
       
           DownloadDatabase("Supervisor", Convert.ToInt32(Session["SupervisorAccountId"]));
        }

======================================================================
2nd method
======================================================================
  public void DownloadDatabase(string AccountType, int AccountID)
        {
         
            DataSet ds = Get_ReportRecord(AccountType, AccountID);
            if (ds != null && ds.Tables.Count > 0)
            {
                AccountType = AccountType.ToUpper();
                if (AccountType == "SUPERADMIN")
                {
                    ds.Tables[0].TableName = "CountryManager";
                    ds.Tables[1].TableName = "Ministry وزارة";
                    ds.Tables[2].TableName = "MinistryAdmin منسق وزرارة";
                    ds.Tables[3].TableName = "EduDistrict منطقة تعليمية";
                    ds.Tables[4].TableName = "School مدرسة";
                    ds.Tables[5].TableName = "Supervisor مشرف";
                    ds.Tables[6].TableName = "Student طالب";
                }
                else if (AccountType == "COUNTRYMANAGER")
                {
                    ds.Tables[0].TableName = "Ministry وزارة";
                    ds.Tables[1].TableName = "MinistryAdmin منسق وزرارة";
                    ds.Tables[2].TableName = "EduDistrict منطقة تعليمية";
                    ds.Tables[3].TableName = "School مدرسة";
                    ds.Tables[4].TableName = "Supervisor مشرف";
                    ds.Tables[5].TableName = "Student طالب";
                }
                else if (AccountType == "MINISTRY")
                {
                    ds.Tables[0].TableName = "MinistryAdmin منسق وزرارة";
                    ds.Tables[1].TableName = "EduDistrict منطقة تعليمية";
                    ds.Tables[2].TableName = "School مدرسة";
                    ds.Tables[3].TableName = "Supervisor مشرف";
                    ds.Tables[4].TableName = "Student طالب";
                }
                else if (AccountType == "MINISTRYADMIN")
                {
                    ds.Tables[0].TableName = "EduDistrict منطقة تعليمية";
                    ds.Tables[1].TableName = "School مدرسة";
                    ds.Tables[2].TableName = "Supervisor مشرف";
                    ds.Tables[3].TableName = "Student طالب";
                }
                else if (AccountType == "EDUCATIONALDISTRICT")
                {
                    ds.Tables[0].TableName = "School مدرسة";
                    ds.Tables[1].TableName = "Supervisor مشرف";
                    ds.Tables[2].TableName = "Student طالب";
                }
                else if (AccountType == "SCHOOL")
                {
                    ds.Tables[0].TableName = "Supervisor مشرف";
                    ds.Tables[1].TableName = "Student طالب";
                }
                else if (AccountType == "SUPERVISOR")
                {
                    ds.Tables[0].TableName = "Student طالب";
                }


                using (XLWorkbook wb = new XLWorkbook())
                {
                    foreach (DataTable dt in ds.Tables)
                    {
                        //Add DataTable as Worksheet.
                        wb.Worksheets.Add(dt);
                    }
                    //Export the Excel file.
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Buffer = true;
                    HttpContext.Current.Response.Charset = "";
                    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=DataBase_" + DateTime.Now.ToString("dd-MM-yyyy") + "_" + AccountType + ".xlsx");
                    using (MemoryStream MyMemoryStream = new MemoryStream())
                    {
                        wb.SaveAs(MyMemoryStream);
                        MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                    }
                }
            }
        }

========================================================================
3nd method
=======================================================================

    public DataSet Get_ReportRecord(string AccountType, int globalid)
        {
            SqlParameter[] parameter = {
                                                new SqlParameter("@Accounttype", AccountType),
                                                 new SqlParameter("@Downloadtypeid", globalid),
                                           };
            DataSet ds = SqlHelper.ExecuteDataSet("GetReportData", parameter);
            return ds;
        }
======================================================================
SqlHelper  Class
======================================================================

 public class SqlHelper
    {
        public static string connectionString = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
        public static DataTable ExecuteNonQuery(string cmdText, params SqlParameter[] commandParameters)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand(cmdText, connection))
                {
                    try
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddRange(commandParameters);
                        using (var adapter = new SqlDataAdapter(command))
                        {
                            connection.Open();
                            DataTable dtResult = new DataTable();
                            adapter.Fill(dtResult);
                            return dtResult;
                        }
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }

        public static DataSet ExecuteDataSet(string cmdText, params SqlParameter[] commandParameters)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand(cmdText, connection))
                {
                    try
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddRange(commandParameters);
                        using (var adapter = new SqlDataAdapter(command))
                        {
                         
                         
                            connection.Open();
                            DataSet dsResult = new DataSet();
                            adapter.Fill(dsResult);
                            return dsResult;
                        }
                    }
                    finally
                    {
                        connection.Close();
                     
                    }
                }
            }
        }

        public static DataTable ExecuteReader(string cmdText, params SqlParameter[] commandParameters)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand(cmdText, connection))
                {
                    try
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddRange(commandParameters);
                        connection.Open();
                        var dataReader = command.ExecuteReader();
                        DataTable dtResult = new DataTable();
                        dtResult.Load(dataReader);
                        return dtResult;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }

        public static string ExecuteScalar(string cmdText, params SqlParameter[] commandParameters)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand(cmdText, connection))
                {
                    try
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddRange(commandParameters);
                        connection.Open();
                        string result = (string)command.ExecuteScalar();
                        return result;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }
    }

Upload Csv file in database using StreamReader in .net

 <td style="width: 112px;">@common.GetTranslations("File Name", LID)</td>
                                        <td>@Html.TextBox("Dfilename", "", new { type = "file", Class = "Dtext tht fs fel", @onchange = "ValidateCsv(this);" })</td>
                                        <td><input type="submit" value="@common.GetTranslations("Upload file", LID)" id="btnupload" class="formBtn" onclick="Loader();" style="min-width: 130px !important;  padding: 3px 0px !important; background-color:gray;   font-size: 15px !important;" disabled /></td>
                                 



   public ActionResult Diamondfile(HttpPostedFileBase Dfilename)
        {
            if (Dfilename != null && Dfilename.ContentLength > 0)
            {
               var attachedFile = Dfilename;
               var csvReader = new StreamReader(attachedFile.InputStream, Encoding.UTF8);      
                string inputDataRead;
                var values = new List<string>();
                while ((inputDataRead = csvReader.ReadLine()) != null)
                {
                    values.Add(inputDataRead);
                }
                values.Remove(values[0]);            
                string StockNumbers = string.Empty;
                string Stockexist = string.Empty;

                if (values.Count > 0)
                {
                    foreach (var value in values)
                    {
                        var eachValue = new string[61];
                        var myList = value.Split(',');
                        for (int i = 0; i < 61; i++)
                        {
                            eachValue[i] = i < myList.Length ? myList[i] : "";
                        }
                        //Diamond objdiamond = new Diamond();
                        #region get value
                        string dAvailabilityStatusID = eachValue[1].ToString();
}
}



Upload Excel file using connection Excel2003"].ConnectionString and ["Excel2007"].ConnectionString



  private DataSet UploadFile(HttpPostedFileBase flbupload)
        {
            string strcon = string.Empty;    
            DataSet ds = new DataSet();      
                string exten = Path.GetExtension(flbupload.FileName);
                if (exten.ToLower() == ".xls") //Excel 97-03
                {
                    strcon = ConfigurationManager.ConnectionStrings["Excel2003"].ConnectionString;
                }
                else if (exten.ToLower() == ".xlsx") //Excel 07
                {
                    strcon = ConfigurationManager.ConnectionStrings["Excel2007"].ConnectionString;
                }    
                string uploaddir = ConfigurationManager.AppSettings["UploadExelFile"];
                string physicalDirPath = Server.MapPath("~/content/" + uploaddir + "/");
                if (!Directory.Exists(physicalDirPath))
                {
                    Directory.CreateDirectory(physicalDirPath);
                }
                string filename = physicalDirPath + Path.GetFileNameWithoutExtension(flbupload.FileName) + Guid.NewGuid() + Path.GetExtension(flbupload.FileName);
                flbupload.SaveAs(filename);
                using (OleDbConnection con = new OleDbConnection())
                {
                    con.ConnectionString = string.Format(strcon, filename, true);
                    if (con.State == ConnectionState.Closed)
                        con.Open();
                //Get the name of First Sheet
                System.Data.DataTable dtExcelSchema;
                    dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();

                    OleDbCommand cmd = new OleDbCommand("SELECT * From [" + SheetName + "]", con);
                    OleDbDataAdapter da = new OleDbDataAdapter(cmd);                
                    da.Fill(ds);  
                }
            return ds;
        }


//Connection String

   <add name="Excel2003" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'" />
    <add name="Excel2007" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'" />

Thursday 17 November 2016

Excel upload using Excel.4.5 and ICSharpCode.SharpZipLib dll

//upload excel file
string FileName = Path.GetFileName(filestudent.PostedFile.FileName);
string Extension = Path.GetExtension(filestudent.PostedFile.FileName);
string FilePath= Server.MapPath("~/Supervisor/" + Convert.ToString(Session["MinistryAccountId"])            
                          + DateTime.Now.ToString("ddMMyy") + Extension);
filestudent.SaveAs(filepath);      

Exceltodatatable(FilePath,Extension)



  public DataTable Exceltodatatable(string FilePath, string Extension)
        {
            FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
            IExcelDataReader excelReader;
            if (Extension.ToLower() == ".xls")
                excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            else
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            excelReader.IsFirstRowAsColumnNames = true;
            DataSet result = excelReader.AsDataSet();
            return result.Tables[0];
        }