Tuesday, 21 March 2017

Generate Random number of string in C#

set Key in Webconfig
============================================================
<add key="PasswordLength" value="6"/>
===========================================================
string OTP = GenerateRandom.RandomOTP(Convert.ToInt32(ConfigurationManager.AppSettings["PasswordLength"]));

=================
using Encrypt
=================
string Password = EncriptDecript.Encrypt(GenerateRandom.RandomPassword(Convert.ToInt32(ConfigurationManager.AppSettings["PasswordLength"])));


=============================================================
Create a GenerateRandom Class
============================================================

 public class GenerateRandom
    {
        public static Random rnd = new Random();

        public static string RandomUserName(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[rnd.Next(s.Length)]).ToArray());
        }
        public static string RandomEmailid(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[rnd.Next(s.Length)]).ToArray());
        }

        public static string RandomPassword(int length)
        {
            const string chars = "0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[rnd.Next(s.Length)]).ToArray());
        }
        public static string RandomOTP(int length)
        {
            const string chars = "0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[rnd.Next(s.Length)]).ToArray());
        }
    }

==============================
EncriptDecript


    public class EncriptDecript
    {
        #region Encode the string value
        public static string Encrypt(string clearText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return clearText;
        }
        #endregion

        #region Decode the encoded value
        public static string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            cipherText = cipherText.Replace(" ", "+");
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }
        #endregion
    }

Monday, 20 March 2017

upload a File using web API



                                              Fig:Call a post man like this

Craete a API Controller And using this  updateprofileImage method.
=======================================================
 public HttpResponseMessage updateprofileImage()
       {
           Customer objCustomer = new Customer();
           HttpResponseMessage response = new HttpResponseMessage();
           var httpRequest = HttpContext.Current.Request;
           if (httpRequest.Files.Count > 0)
           {
            //  HttpPostedFile file = httpRequest.Files[0];
            //string[] F_Name = file.FileName.Split('.');
            //string mapName = F_Name[0] + "-" + "Cus" + objCustomer.CustomerId + "." + F_Name[1];
            //string strCustomerfileOriginalPath = "~/Content/ProfilePicture";
           //string filepath = httpRequest.MapPath(strCustomerfileOriginalPath);
           //filepath = Path.Combine(filepath, System.IO.Path.GetFileName(mapName));
           //file.SaveAs(filepath);

                     HttpPostedFile file = httpRequest.Files[0];
                     int UserId = 1;// CustomerId;//httpRequest["CustomerId"];
                     string strCustomerfileOriginalPath = string.Empty;
                     strCustomerfileOriginalPath = "~/Content/Uploads/Customer/ProfilePic";
                     string strTutorImg = string.Empty;
                     if (file != null)
                     {
                         string CustomerImage;
                         CustomerImage = DateTime.UtcNow.Ticks + "-" + 'C' + "-" + file.FileName;

                         var filepath = httpRequest.MapPath(strCustomerfileOriginalPath);
                         if (!Directory.Exists(filepath))
                             Directory.CreateDirectory(filepath);
                         filepath = Path.Combine(filepath,
                                             System.IO.Path.GetFileName(CustomerImage));
                         file.SaveAs(filepath);
                         tblAssign.AttachedFile = strTutorImg;
                         objCustomer.OrgProfilePic = file.FileName;
                         objCustomer.MappedProfilePic = CustomerImage;
                     }
           }
           return Request.CreateResponse(HttpStatusCode.OK, objCustomer); ;
       } 

Tuesday, 21 February 2017

update panel in ASP.net

# if you using this update pannel so apply :

OnClientClick="return onlineschoolvalid();" for validation .

this is working as a ajax method:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

   <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering ="true"></asp:ScriptManager>
   <asp:UpdatePanel ID ="uppanel" runat ="server" ChildrenAsTriggers ="true" UpdateMode="Conditional"  >
   <ContentTemplate>


   </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

Create a manual paging in ASP.net

This is manual paging in asp.net using c# and SQl server.


HTML  Code:
==========
<div id="iddivtotal" runat="server" style="font-size: 16px;font-weight: 700; color: #3a3f9a;">Total record: <label id="lbltotalcount" runat="server"></label></div>
<asp:HiddenField ID="hdfPageNo" runat="server" />
<div class="bradcrum" id="Divbradcrum" runat="server">
 <div>
<div><asp:LinkButton ID="lnk_back" runat="server"  OnClick="lnk_back_Click">
<img src="../Content/images/Previous_Off.png" class="imgp" runat="server" id="idPrevious_Off" />
<img src="../Content/images/Previous_On.png"  class="imgp" runat="server" id="idPrevious_On" /> </asp:LinkButton> |
 <asp:DropDownList ID="ddlImageIndexing" runat="server" OnSelectedIndexChanged="ddlImageIndexing_SelectedIndexChanged" AutoPostBack="true" style="font-size: 12px;margin-bottom: 2px; width: 52px;  padding-right: 10px;"></asp:DropDownList> |
 <asp:LinkButton ID="lnk_next" OnClick="lnk_next_Click"  runat="server">
 <img src="../Content/images/Next_Off.png" class="imgp" runat="server" id="idNext_Off"/>
 <img src="../Content/images/Next_On.png"  class="imgp" runat="server" id="idNext_On" />
 </asp:LinkButton>
                </div>
           </div>                      
         </div>


Css Code:
==========
 .imgp{ margin-top: 6.7px !important;  }
 .bradcrum { float:left; padding-top: 10px;   padding-bottom: 10px;}
.displayr {margin-left: 21px; margin-top: 10px; margin-bottom: 2px; color: black; font-weight: 600;}

C# Code:
==========

   public void studentReportlist(int pageindex)
        {
            int SupervisorId = Convert.ToInt32(Session["SupervisorAccountId"]);
            int PageSize = Convert.ToInt32(ConfigurationManager.AppSettings["pagingsize"]);
            DataTable dtResult = objSuperAdminDl.GetAllStudentReport(SupervisorId, pageindex, PageSize);
            if (dtResult != null)        
            {                            
                if (dtResult.Rows.Count > 0)
                {
                    iddivtotal.Visible = true;
                    Divbradcrum.Visible = true;
                    ddlImageIndexing.Items.Clear();
                    int totalCount = Convert.ToInt32(dtResult.Rows[0]["totalrecord"]);
                    int totalpage = int.Parse(Math.Ceiling((Convert.ToDecimal(totalCount) / Convert.ToDecimal(PageSize))).ToString("0"));
                    for (int i = 1; i <= totalpage; i++)
                    {
                        ddlImageIndexing.Items.Add(new ListItem(i.ToString(), i.ToString()));
                    }
                    lbltotalcount.InnerText = totalCount.ToString();
                    ddlImageIndexing.SelectedValue = pageindex.ToString();

                   int rowNo = 1;
                   tblReportList += "<tr class='titlebar'><td class='width5' style='width:3%'></td><td class='width40' style='color: #fff'>اسم الطالب</td><td class='width10' align='center' style='color: #fff'>كتاب مقروء</td><td class='width10' align='center' style='color: #fff'>كتاب مرفوض</td><td class='width10' align='center' style='color: #fff'>قيد المراجعة</td><td class='width17' align='center' style='color: #fff'>المجموع الكلي للكتب</td></tr>";
                    foreach (DataRow dr in dtResult.Rows)
                    {
                        tblReportList += "<tr><td>"  + Convert.ToString(dr["RowNum"]) +  "-</td>" +
                                         "<td>" + Convert.ToString(dr["Name"]) + "</td>" +
                                         "<td align='center'>" + Convert.ToString(dr["Aproved"]) + "</td>" +
                                         "<td align='center'>" + Convert.ToString(dr["Rejected"]) + "</td>" +                                    
                                         "<td align='center'>" + Convert.ToString(dr["Pending"]) + "</td>" +
                                         "<td align='center'>" + Convert.ToString(dr["totalbook"]) + "</td>";  
                        rowNo = rowNo + 1;
                    }

                    tbodyAllStudentreport.InnerHtml = tblReportList;
                }
                else
                {
                    iddivtotal.Visible = false;
                    Divbradcrum.Visible = false;
                    tbodyAllStudentreport.InnerHtml = "<tr><td style='text-align: center;'>لا توجد أي سجلات مدرجة في الوقت الحالي.</td></tr>";
                }
                dtResult.Dispose();
               
            }
            DisableEnableLinkbutton();
        }
#region Listing method
        protected void lnk_back_Click(object sender, EventArgs e)
        {
            int Pageindex = Convert.ToInt32(ddlImageIndexing.SelectedIndex - 1) + 1;          
            studentReportlist(Pageindex);

        }
        protected void lnk_next_Click(object sender, EventArgs e)
        {
            int Pageindex = Convert.ToInt32(ddlImageIndexing.SelectedIndex + 1) + 1;          
            studentReportlist(Pageindex);

        }
        protected void ddlImageIndexing_SelectedIndexChanged(object sender, EventArgs e)
        {
            int Pageindex = Convert.ToInt32(ddlImageIndexing.SelectedValue);          
            studentReportlist(Pageindex);

        }
        protected void DisableEnableLinkbutton()
        {
            if (ddlImageIndexing.SelectedIndex == ddlImageIndexing.Items.Count - 1)
            {
                lnk_next.Enabled = false;
                idNext_On.Visible = false;
                idNext_Off.Visible = true;
            }
            else
            {
                lnk_next.Enabled = true;
                idNext_Off.Visible = false;
                idNext_On.Visible = true;
            }
            if (ddlImageIndexing.SelectedIndex == 0)
            {
                lnk_back.Enabled = false;
                idPrevious_On.Visible = false;
                idPrevious_Off.Visible = true;
            }
            else
            {
                lnk_back.Enabled = true;
                idPrevious_Off.Visible = false;
                idPrevious_On.Visible = true;

            }



        }
        #endregion

BAL
==========
   public DataTable GetAllStudentReport(int supperviosrid,int pageindex,int  PageSize)
        {
            try
            {
                SqlParameter[] parameter = {                                                
                                             new SqlParameter("@supperviosrid",supperviosrid),
                                              new SqlParameter("@Page", pageindex),
                                               new SqlParameter("@Pagesize", PageSize)
                                           };
                dtResult = SqlHelper.ExecuteReader("Get_eachstudentreportlist", parameter);
                return dtResult;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

 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.Dispose();
                        command.Dispose();                      
                        connection.Close();
                    }
                }
            }
        }


SQL Procedure
==========
--select * from  Tbl_StudentBook
CREATE proc [dbo].[Get_eachstudentreportlist] --2
@supperviosrid int,
@Page int =1,
@Pagesize int=100
as
 begin
 declare @totalrecored int
  select * into #tempreport from
(
    select ts.student_Id, ts.FirstName +' '+ts.SecondName  as Name,count(1) totalbook,
   (select count(1) from Tbl_StudentBook where student_Id=ts.student_Id and IsStatus='A') as Aproved
   , (select count(1) from Tbl_StudentBook where student_Id=ts.student_Id and IsStatus='R') as Rejected
   , (select count(1) from Tbl_StudentBook where student_Id=ts.student_Id and IsStatus='P') as Pending
   ,ROW_NUMBER() OVER (ORDER  BY cast(ts.student_Id as int) asc) AS RowNum
   from Tbl_StudentBook tsb
   inner join tbl_student ts on ts.student_Id=tsb.student_Id
   where ts.Supervisor_id=@supperviosrid and ts.IsActive=1 group by ts.student_Id ,ts.FirstName,ts.SecondName )myreporttbl
    select @totalrecored =count(1) from #tempreport
    select *,@totalrecored as totalrecord from #tempreport where #tempreport.RowNum BETWEEN ((@Page - 1) * @PageSize + 1) AND (@Page * @PageSize)

 end


Monday, 23 January 2017

Create excel file

 var employees = new[]{
                               new{ Id="101", Name="Vivek", Address="Hyderabad" },
                               new{ Id="102", Name="Ranjeet", Address="Hyderabad" },
                               new{ Id="103", Name="Sharath", Address="Hyderabad" },
                               new{ Id="104", Name="Ganesh", Address="Hyderabad" },
                               new{ Id="105", Name="Gajanan", Address="Hyderabad" },
                               new{ Id="106", Name="Ashish", Address="Hyderabad" }
                      };

            string excelName = "employees";

            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=" + excelName + ".xls");
            Response.AddHeader("Content-Type", "application/vnd.ms-excel");

            //Header for table records
            //
            Response.Write("Id");
            Response.Write("\t");
            Response.Write("Name");
            Response.Write("\t");
            Response.Write("Address");
            Response.Write("\t");

            Response.Write("\n");

            //Body for table records
            //
            foreach (var employee in employees)
            {
                Response.Write(employee.Name);
                Response.Write("\t");
                Response.Write(employee.Id);
                Response.Write("\t");
                Response.Write(employee.Address);
                Response.Write("\t");
                Response.Write("\n");
            }

            Response.End();




//Using Gride View
=====================

public void ExportToExcel(string FileName, dynamic datalist)
        {
            GridView gv = new GridView();
            gv.DataSource = datalist;
            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;

            Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            //gv.Font.Bold = false;
            //gv.Font.Size = 14;
            gv.RenderControl(htw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }


===
In Asp .net
================

public void DownloadDatabase(string AccountType, int AccountID)
        {
            UserLoginDl objlogindl = new UserLoginDl();
            DataSet ds = objlogindl.Get_ReportRecord(AccountType, AccountID);
            if (ds != null && ds.Tables.Count > 0)
            {
                #region tbl
                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 طالب";
                }
                #endregion

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

        public void NewDownloadDatabase(string AccountType,string levelname, int AccountID)
        {
            UserLoginDl objlogindl = new UserLoginDl();
            DataSet ds = objlogindl.Get_NewReportRecord(AccountType, levelname, AccountID);
            if (ds != null && ds.Tables.Count > 0)
            {
                string sheetname = "";
                if (levelname == "countrymanager")
                {
                    sheetname = "CountryManager سكرتاريا";
                }
                else if (levelname == "ministry")
                {
                    sheetname = "Ministry وزارة";
                }
                else if (levelname == "ministryadmin")
                {
                    sheetname = "MinistryAdmin منسق وزرارة";
                }
                else if (levelname == "disticmanager")
                {
                    sheetname = "EduDistrict منطقة تعليمية";
                }
                else if (levelname == "school")
                {
                    sheetname = "School مدرسة";
                }
                else if (levelname == "suppervisor")
                {
                    sheetname = "Supervisor مشرف";
                }
                else if (levelname == "student")
                {
                    sheetname = "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") + "_" + sheetname + ".xlsx");
                    using (MemoryStream MyMemoryStream = new MemoryStream())
                    {
                        wb.SaveAs(MyMemoryStream);
                        MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                    }
                }

                //string attachment = "attachment; filename=DataBase_" + DateTime.Now.ToString("dd-MM-yyyy") + "_" + sheetname + ".xls";

                //HttpContext.Current.Response.ClearContent();
                //HttpContext.Current.Response.AddHeader("content-disposition", attachment);
                //HttpContext.Current.Response.ContentType = "application/ms-excel";
                //HttpContext.Current.Response.Charset = "utf-8";
                //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
                //HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
                //string tab = "";
                //foreach (DataColumn dc in ds.Tables[0].Columns)
                //{
                //    HttpContext.Current.Response.Write(tab + dc.ColumnName);
                //    tab = "\t";
                //}
                //HttpContext.Current.Response.Write("\n");
                //int i;
                //foreach (DataRow dr in ds.Tables[0].Rows)
                //{
                //    tab = "";
                //    for (i = 0; i < ds.Tables[0].Columns.Count; i++)
                //    {
                //        HttpContext.Current.Response.Write(tab + dr[i].ToString());
                //        tab = "\t";
                //    }
                //    HttpContext.Current.Response.Write("\n");
                //}
                //HttpContext.Current.Response.End();

              //  ExporttoExcel(ds.Tables[0], attachment);
            }
        }

        public void DateRangeDownloadDatabase(string AccountType, string levelname, int AccountID, DateTime fromdate, DateTime todate)
        {
            UserLoginDl objlogindl = new UserLoginDl();
            DataSet ds = objlogindl.Get_DateRangeReportRecord(AccountType, levelname, AccountID, fromdate, todate);
            if (ds != null && ds.Tables.Count > 0)
            {
                string sheetname = "";
                if (levelname == "countrymanager")
                {
                    sheetname = "CountryManager سكرتاريا";
                }
                else if (levelname == "ministry")
                {
                    sheetname = "Ministry وزارة";
                }
                else if (levelname == "ministryadmin")
                {
                    sheetname = "MinistryAdmin منسق وزرارة";
                }
                else if (levelname == "disticmanager")
                {
                    sheetname = "EduDistrict منطقة تعليمية";
                }
                else if (levelname == "school")
                {
                    sheetname = "School مدرسة";
                }
                else if (levelname == "suppervisor")
                {
                    sheetname = "Supervisor مشرف";
                }
                else if (levelname == "student")
                {
                    sheetname = "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") + "_" + sheetname + ".xlsx");
                    using (MemoryStream MyMemoryStream = new MemoryStream())
                    {
                        wb.SaveAs(MyMemoryStream);
                        MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                    }
                }

                //string attachment = "attachment; filename=DataBase_" + DateTime.Now.ToString("dd-MM-yyyy") + "_" + sheetname + ".xls";

                //HttpContext.Current.Response.ClearContent();
                //HttpContext.Current.Response.AddHeader("content-disposition", attachment);
                //HttpContext.Current.Response.ContentType = "application/ms-excel";
                //HttpContext.Current.Response.Charset = "utf-8";
                //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
                //HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
                //string tab = "";
                //foreach (DataColumn dc in ds.Tables[0].Columns)
                //{
                //    HttpContext.Current.Response.Write(tab + dc.ColumnName);
                //    tab = "\t";
                //}
                //HttpContext.Current.Response.Write("\n");
                //int i;
                //foreach (DataRow dr in ds.Tables[0].Rows)
                //{
                //    tab = "";
                //    for (i = 0; i < ds.Tables[0].Columns.Count; i++)
                //    {
                //        HttpContext.Current.Response.Write(tab + dr[i].ToString());
                //        tab = "\t";
                //    }
                //    HttpContext.Current.Response.Write("\n");
                //}
                //HttpContext.Current.Response.End();

                //  ExporttoExcel(ds.Tables[0], attachment);
            }
        }

        private void ExporttoExcel(DataTable table,string Filename)
        {
            #region old code
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            // Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            HttpContext.Current.Response.AddHeader("Content-Disposition", Filename);

            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
            HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            // Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            //sets font
            HttpContext.Current.Response.Write("<font style='font-size:12px; font-family:Calibri;'>");
       
            //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
            HttpContext.Current.Response.Write("<Table bgColor='#ffffff' " + "cellSpacing='0' cellPadding='0' " + "style='font-size:12px; font-family:Calibri; background:white;'> <TR style='border-bottom: 1px solid white'>");
            //am getting my grid's column headers
            int columnscount = table.Columns.Count;

            for (int j = 0; j < columnscount; j++)
            {      //write in new column
                HttpContext.Current.Response.Write("<Td style='background: gray; color:#fff; font-size:12px; width: 90px;'>");
                //Get column headers  and make it as bold in excel columns
                HttpContext.Current.Response.Write("<B>");
                HttpContext.Current.Response.Write(table.Columns[j].ToString());
                HttpContext.Current.Response.Write("</B>");
                HttpContext.Current.Response.Write("</Td>");
            }
            HttpContext.Current.Response.Write("</TR>");
            foreach (DataRow row in table.Rows)
            {//write in new row
                HttpContext.Current.Response.Write("<TR>");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    HttpContext.Current.Response.Write("<Td>");
                    HttpContext.Current.Response.Write(row[i].ToString());
                    HttpContext.Current.Response.Write("</Td>");
                }

                HttpContext.Current.Response.Write("</TR>");
            }
            HttpContext.Current.Response.Write("</Table>");
            HttpContext.Current.Response.Write("</font>");
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();


         
            //using exlcel4.5 dll and closed dll
            //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 + "_" + levelname + ".xlsx");
            //    using (MemoryStream MyMemoryStream = new MemoryStream())
            //    {
            //        wb.SaveAs(MyMemoryStream);
            //        MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
            //        HttpContext.Current.Response.Flush();
            //        HttpContext.Current.Response.End();
            //    }
            //}
            //using  GridView
            //HttpContext.Current.Response.ClearContent();
            //HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + sheetname + ".xls");
            //HttpContext.Current.Response.ContentType = "application/excel";
            // System.IO.StringWriter sw = new System.IO.StringWriter();
            // HtmlTextWriter htw = new HtmlTextWriter(sw);
            // GridView GridView1 = new GridView();
            // GridView1.DataSource = ds.Tables[0];
            // GridView1.DataBind();
            // GridView1.RenderControl(htw);
            // HttpContext.Current.Response.Write(sw.ToString());
            // HttpContext.Current.Response.End();
            #endregion
        }
        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];
        }

        public DataTable ExceltodatatableImport(string FilePath, string Extension)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("SecondName", typeof(string));
            dt.Columns.Add("ThirdName", typeof(string));
            dt.Columns.Add("FourthName", typeof(string));
            dt.Columns.Add("Country", typeof(string));
            dt.Columns.Add("Nationality", typeof(string));
            dt.Columns.Add("Gender", typeof(string));
            dt.Columns.Add("Grade", typeof(string));
            dt.Columns.Add("Email", typeof(string));



            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();
            // dt = result.Tables[0];


            foreach (DataRow row in result.Tables[0].Rows)
            {
                DataRow dr = dt.NewRow();
   

             dr["FirstName"] =row[0];
              dr["SecondName"] =row[1];
            dr["ThirdName"] =row[2];
            dr["FourthName"] =row[3];
            dr["Country"]=row[4];
            dr["Nationality"]=row[5] ;
            dr["Gender"]=row[6];
           dr["Grade"]=row[7];
            dr["Email"]=row[8];
                dt.Rows.Add(dr);
            }

            return dt;
            // return result.Tables[0];
        }

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";
               
            }
            
        }
==============================