Wednesday 28 December 2016

Html and css drop down menu list

Html:
============================
 <div class="ddropdown">
    <button class="ddropbtn">Dropdown</button>
       <div class="ddropdown-content">  
          <a href="javascript:void(0)">level1</a>
          <a href="javascript:void(0)">level2</a>
          <a href="javascript:void(0)">level3</a>
          <a href="javascript:void(0)">level4</a>
      </div>          
</div>
============================

Css:

===========================
<style>
.ddropbtn {
    background-color: #505050;
    color: white;  
    font-size: 15px;
    border: none;
    cursor: pointer;  
    display: inline-block;
    padding: 0px 24.3px;
    border-radius: 0 0 3px 3px;
}
.ddropdown {
    position: relative;
    display: inline-block;
}
.ddropdown-content {
    display: none;
    top: 26px;
    position: absolute;
    background-color: #babfd3;  
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index:999;  
}
.ddropdown-content a {
    color: white;
    text-align: right;
    padding-bottom: 2px;
    text-decoration: none;
    display: block;
    background-color: #babfd3;
    border-bottom: 1px solid #eaeaf1;
}
.ddropdown-content a:hover {background-color: #3a3f9a}
.ddropdown:hover .ddropdown-content {
    display: block;
}
.ddropdown:hover .ddropbtn {
    background-color: #3a3f9a;
}
</style
=======================

upload excel file without saving any where in system in mvc, asp ,vb.net

Using ClosedXML and Excel.4.5 dll.

//Install-Package ClosedXML -Version 0.76.0
//https://www.nuget.org/packages/ClosedXML/0.76.0

//Install-Package ExcelDataReader -Version 2.1.2.3
//https://www.nuget.org/packages/ExcelDataReader/2.1.2.3

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

C# code
===============

using ClosedXML.Excel;
using Excel;
   public ActionResult Diamondfile(HttpPostedFileBase Dfilename)
        {
if (Dfilename != null && Dfilename.ContentLength > 0)
            {
                string Extension = Path.GetExtension(Dfilename.FileName);

                if (!(Extension == "csv"))
                {
                    #region Excel File
                    var attachedFile = Dfilename;
                    IExcelDataReader excelReader;
                    if (Extension.ToLower() == ".xls")
                        excelReader = ExcelReaderFactory.CreateBinaryReader(attachedFile.InputStream);
                    else
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(attachedFile.InputStream);
                   //In asp.net or vb.net 
                   // excelReader = ExcelReaderFactory.CreateBinaryReader(attachedFile.FileContent)
                    //Else
                   // excelReader = ExcelReaderFactory.CreateOpenXmlReader(attachedFile.FileContent)                  



  excelReader.IsFirstRowAsColumnNames = true;
                    DataSet result = excelReader.AsDataSet();
                    System.Data.DataTable dtResult = result.Tables[0];
                    uploadexcelfile(dtResult);


                    #endregion
                }            
                else
                {
                  //code here csv file
                }
            }
            else
            {
                TempData["Fileupload"] = "no";
            }
            
            return View();
}
=================================


    public void uploadexcelfile(System.Data.DataTable dtResult)
        {
            if (dtResult.Rows.Count > 0)
            {
                string inputDataRead;
                string StockNumbers = string.Empty;
                string Stockexist = string.Empty;

                foreach (DataRow eachValue in dtResult.Rows)
                {           
                    //code here
                }
            }
            else
            {
                TempData["Fileupload"] = "no";
               
            }
            
        }
==============================



Monday 19 December 2016

PayPal without dll using only email

Web config
==============
    <!-- Start Paypal pages-->
    <add key="PayPalUrl" value="https://www.sandbox.paypal.com/cgi-bin/webscr" />
    <add key="PaypalEmailId" value="saurabh_kashyap-facilitator@seologistics.com"></add>
    <add key="PaypalSuccessUrl" value="/Paypal/PayoutSuccess"></add>
    <add key="PaypalErrorUrl" value="/Paypal/PayoutError"></add>
    <add key="PaypalNotifyUrl" value="/Paypal/PayoutNotify"></add>
    <add key="EnvironmentType" value="Dev"></add>
   
    <!-- End Paypal Pages-->
Controler
==================

namespace EMPBenefits.Controllers
{
    public class PayPalController : Controller
    {
        #region Payout amount to EMP by admin...

        #region Declare all object
        /// <summary>
        /// Declare object of outside class
        /// </summary>
        GenericUnitOfWork _Unitofwork = new GenericUnitOfWork();
        EncryptDecrypt objEncDec = new EncryptDecrypt();
        Sendmail objsendmail = new Sendmail();
        #endregion
        public ActionResult PaymentWithPaypal(_Employerreg objpaymentdetails)
        {
            TempData["userpaymentinfo"] = objpaymentdetails;
            return PayoutEMP(objpaymentdetails);
        }

        public ActionResult PayoutEMP(_Employerreg objdata)
        {
           
           // _Employerreg objdata = (_Employerreg)Session["Paymentdetails"];
            int EMPId = Convert.ToInt32(objdata.employeerid);
            decimal EMPEarning = Convert.ToDecimal(objdata.TotalPrice);
            string Employeername = Convert.ToString(objdata.firstName);
            string EMPPaypalEmail = ConfigurationManager.AppSettings["PaypalEmailId"];
            string redirect = ConfigurationManager.AppSettings["PayPalUrl"] + "?cmd=_xclick&business=" + EMPPaypalEmail;
            redirect += "&item_name=" + Employeername;
            redirect += "&quantity=" + 1;
            string totalPaymentAmount = Convert.ToString(EMPEarning);
            redirect += "&amount=" + totalPaymentAmount;
            redirect += "&ItemTotal=" + totalPaymentAmount;
            redirect += "&tax_cart=" + "1";
            redirect += "&rm=" + "2";
            redirect += "&currency_code=USD";
            redirect += "&custom=" + EMPPaypalEmail + "|" + EMPId + "|" + totalPaymentAmount;
            redirect += "&notify_url=" + ConfigurationManager.AppSettings["PageURL"] + ConfigurationManager.AppSettings["PaypalNotifyUrl"];
            redirect += "&return=" + ConfigurationManager.AppSettings["PageURL"] + ConfigurationManager.AppSettings["PaypalSuccessUrl"];
            redirect += "&cancel_return=" + ConfigurationManager.AppSettings["PageURL"] + ConfigurationManager.AppSettings["PaypalErrorUrl"];

            TempData["requesturl"] = redirect;
            return Redirect(redirect);
        }

        public ActionResult PayoutSuccess()
        {
            string strSandbox = ConfigurationManager.AppSettings["PayPalUrl"];
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
            //Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param = Request.BinaryRead(Request.ContentLength);
            string strRequest = System.Text.Encoding.ASCII.GetString(param);
            string strResponse_copy = strRequest;  //Save a copy of the initial info sent by PayPal
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;          
            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            streamOut.Write(strRequest);
            streamOut.Close();
            StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();
            //enquiry status and update  database
            if (strResponse == "VERIFIED")
            {
                if (TempData["CurrentTransactionId"] == null)
                {
                    if (System.Configuration.ConfigurationManager.AppSettings["EnvironmentType"] == "Dev")
                    {
                        System.Collections.Specialized.NameValueCollection these_argies = System.Web.HttpUtility.ParseQueryString(strResponse_copy);
                        string user_email = these_argies["payer_email"];
                        string pay_stat = these_argies["payment_status"];
                        string txn_id = these_argies["txn_id"];
                        string payer_id = these_argies["payer_id"];
                        string payment_status = these_argies["payment_status"];
                        string payment_type = these_argies["payment_type"];
                        string payment_fee = these_argies["payment_fee"];
                        string receiver_id = these_argies["receiver_id"];
                        string handling_amount = these_argies["handling_amount"];
                        string payment_gross = these_argies["payment_gross"];
                        string custom = these_argies["custom"];

                        int providerId = 0;
                        decimal providerAmount = 0;
                        var customList = custom.Split('|');
                        if (customList.Count() == 3)
                        {
                            providerId = Convert.ToInt32(customList[1]);
                            Decimal.TryParse(customList[2], NumberStyles.Any, CultureInfo.InvariantCulture, out providerAmount);
                        }

                        _Employerreg objuserinfo = (_Employerreg)TempData["userpaymentinfo"];
                        tblPayment trns = new tblPayment();                      
                        trns.status = payment_status;
                        trns.amount =Convert.ToDecimal(payment_gross);
                        trns.transaction_date = DateTime.UtcNow;
                        trns.transactionNumber = txn_id;
                        trns.employerId = objuserinfo.employeerid;
                        trns.paymentOptionId = 1;
                        trns.request = Convert.ToString(TempData["requesturl"]);
                        _Unitofwork.GetRepositoryInstance<tblPayment>().Add(trns);
                        _Unitofwork.SaveChanges();
                        int id=Convert.ToInt32(objuserinfo.employeerid);
                        tblEmployer objemployee = _Unitofwork.GetRepositoryInstance<tblEmployer>().GetFirstOrDefaultByParameter(i => i.employerId == id);
                        objemployee.paymentOptionId = 1;
                        objemployee.lastUpdatedDate = DateTime.Now;
                        objemployee.lastUpdatedByUserId = id;                      
                        objemployee.numberOfEmployees = objuserinfo.numberofemp;
                        objemployee.subscriptionStartDate = DateTime.UtcNow;                      
                        objemployee.userName=  GenerateRandom.RandomUserName(Convert.ToInt32(ConfigurationManager.AppSettings["UserNameLength"]));
                        objemployee.password = objEncDec.Encrypt(GenerateRandom.RandomPassword(Convert.ToInt32(ConfigurationManager.AppSettings["PasswordLength"])));
                        objemployee.isPaid = true;
                        _Unitofwork.GetRepositoryInstance<tblEmployer>().Update(objemployee);
                        _Unitofwork.SaveChanges();                      
                    }
                }
             
            }
            else if (strResponse == "INVALID")
            {            
                PayoutError();              
            }
            return RedirectToAction("success", "Home");
        }

        public ActionResult PayoutError()
        {
            TempData["PaypalResponseAfterPayout"] = "There were some issues dring the payment and it is not completed. Please try again";
            return RedirectToAction("index", "Home");
        }

        public ActionResult PayoutNotify()
        {
            string strSandbox = ConfigurationManager.AppSettings["PayPalUrl"];
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
            //Set values for the request back
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param = Request.BinaryRead(Request.ContentLength);
            string strRequest = System.Text.Encoding.ASCII.GetString(param);
            string strResponse_copy = strRequest;  //Save a copy of the initial info sent by PayPal
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;
            //for proxy
            //WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
            //req.Proxy = proxy;
            //Send the request to PayPal and get the response
            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            streamOut.Write(strRequest);
            streamOut.Close();
            StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();
            if (System.Configuration.ConfigurationManager.AppSettings["EnvironmentType"] == "Live")
            {
                System.Collections.Specialized.NameValueCollection these_argies = System.Web.HttpUtility.ParseQueryString(strResponse_copy);
                string user_email = these_argies["payer_email"];
                string pay_stat = these_argies["payment_status"];
                string txn_id = these_argies["txn_id"];
                string payer_id = these_argies["payer_id"];
                string payment_status = these_argies["payment_status"];
                string payment_type = these_argies["payment_type"];
                string payment_fee = these_argies["payment_fee"];
                string receiver_id = these_argies["receiver_id"];
                string handling_amount = these_argies["handling_amount"];
                string payment_gross = these_argies["payment_gross"];
                string custom = these_argies["custom"];

                int providerId = 0;
                decimal providerAmount = 0;
                var customList = custom.Split('|');
                if (customList.Count() == 3)
                {
                    providerId = Convert.ToInt32(customList[1]);
                    Decimal.TryParse(customList[2], NumberStyles.Any, CultureInfo.InvariantCulture, out providerAmount);
                }
                //Tbl_Transactions trns = new Tbl_Transactions();
                //trns.AppointmentId = 0;
                //trns.AdminPromo = 0;
                //trns.AmountPaid = providerAmount; // Payout Amount
                //trns.BookingFee = 0;
                //trns.PayerMemberId = Session["AdminMember"] != null ? Convert.ToInt32(Session["AdminMember"]) : 0; // Admin Id
                //trns.ProviderAmount = -providerAmount;
                //trns.ProviderFee = 0;
                //trns.ProviderPromo = 0;
                //trns.RecieverMemberId = providerId;  //Provider Id
                //trns.TransactionStatusId = 1;
                //trns.VatPercent = 0;
                //trns.OfferDiscount = _GlobalDiscount;
                //trns.SeekerAmount = 0;
                //trns.TransactionTypeId = 3;  // Admin pays to provider: monthly earning is paid by admin to provider
                //trns.CreatedOn = DateTime.UtcNow;
                //trns.ModifiedOn = DateTime.UtcNow;
                //trns.PayerPayPalId = payer_id;
                //trns.PaypalToken = txn_id;
                //trns.PaypalPaymentId = txn_id;
                //trns.ModifiedOn = DateTime.UtcNow;
                //trns.TransactionStatusId = 2;
                //_unitOfWork.GetRepositoryInstance<Tbl_Transactions>().Add(trns);
                //_unitOfWork.SaveChanges();
            }
            return null;
        }
        #endregion

    }
}

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