Monday, August 20, 2012

Login Validation in MVC

HomeController.cs (Controller)


  [HttpGet]
        public ActionResult Admin()
        {
            //ViewBag.Message = "Welcome to Login Page";
            //var v = ViewData.Model = _db.Employee.ToList();
            // return View(v);
            return View();
        }
        [HttpPost]
        public ActionResult Admin(CabAutomationSystem.Models.LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.IsValid(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                    return RedirectToAction("Home", "Admin");

                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }


            return View(model);
        }

LoginModel.cs (Model)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;

namespace CabAutomationSystem.Models
{
    public class LoginModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
        public bool IsValid(string _username, string _pwd)
        {
            string _sql = "Select uname From Login Where uname='" + _username + "' And pwd='" + _pwd + "'";
            SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLMFConnection"].ToString());
            cn.Open();
            SqlCommand cmd = new SqlCommand(_sql, cn);
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
                return true;
            else
                return false;

        }

    }
}

Admin.cshtml (View)


@model CabAutomationSystem.Models.LoginModel
           @{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title></title>
    <link href="@Url.Content("~/Content/admin_style.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/Content/Mystyle.css")" rel="stylesheet" type="text/css" />  
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
    <div>
    <div>
   
   
    <div id="OuterContainer">
<div id="LogoContainer"></div>
</div>
<div id="HeaderContainer">
   
   
   
</div>

   <div id="BannerContainer">
        <div id="BannerArea">
                &nbsp;</div>
      </div>
       
        <div id="MenuContainer">
        <div id="MenuArea">
            <div id="Menu" >
              </div>
            </div>
        </div>
       
        <div id="ConetntAreaContainer" class="clear">
        <div id="CategoryContainer" style="height:100px">
         <div style="clear:both">
                    <a href="@Url.Action("Default", "Shared")" title="Branch">
                                            <img src="../../Content/images/back.jpg" />
                                           </a>
                 
                      </div>
          </div>
               
                <div id="ContentContainer" style="width:98%">
                 <div id="Welcomecontent">
                   <p>
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
         <table align="center" border="0" cellpadding="0" cellspacing="0" width="300">
             <tr>
                 <td valign="top" width="16">
                     <img alt="" height="14" src="../../Content/images/whitebox_01.jpg" width="16" /></td>
                 <td background="../../Content/images/whitebox-topbg.jpg" valign="top">
                     <img height="14" src="../../Content/images/whitebox-topbg.jpg" width="1" /></td>
                 <td valign="top" width="19">
                     <img alt="" height="14" src="../../Content/images/whitebox_03.jpg" width="19" /></td>
             </tr>
             <tr>
                 <td background="../../Content/images/whitebox-left-bg.jpg" height="56" valign="top">&nbsp;
                </td>
                 <td valign="top">
                 @Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
                 @using (Html.BeginForm())
                 {
                     <table align="center" bgcolor="#0066CC" cellpadding="2" cellspacing="2"
                         width="300">
                         <tr>
                             <td colspan="2" height="35" style="font-size: 14px; color: #006600;
                                 text-align: left">
                                 <strong class="adminhead">Administrator Login</strong></td>
                         </tr>
                         <tr>
                             <td align="right" class="style1" >
                                 <strong> @Html.LabelFor(m => m.UserName)</strong></td>
                             <td class="admin_txt" style="text-align: left">
                                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
                </td>
                         </tr>
                         <tr>
                             <td align="right" class="style1" >
                                 <strong>@Html.LabelFor(m => m.Password)</strong></td>
                             <td class="admin_txt" style="text-align: left">
                         @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
                                     </td>
                         </tr>
                         <tr>
                             <td class="admin_txt" style="width: 100px; text-align: left">                             </td>
                             <td class="admin_txt">
                              @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
                           </td>
                         </tr>
                         <tr>
                             <td>                             </td>
                             <td class="style2" style="text-align: center">
                           <input type="submit" value="Login" />
                               
                           </td>
                         </tr>
                   </table>
                 }
                 </td>
                 <td background="../../Content/images/whitebox-right-bg.jpg" valign="top">
                     <img height="1" src="../../Content/images/whitebox-right-bg.jpg" width="19" /></td>
             </tr>
             <tr>
                 <td valign="top">
                     <img alt="" height="18" src="../../Content/images/whitebox_07.jpg" width="16" /></td>
                 <td background="../../Content/images/whitebox-bottom-bg.jpg" valign="top">
                     <img height="18" src="../../Content/images/whitebox-bottom-bg.jpg" width="1" /></td>
                 <td valign="top">
                     <img alt="" height="18" src="../../Content/images/whitebox_09.jpg" width="19" /></td>
             </tr>
         </table>
<br />
                    </p>
                    </div>
                   
          </div>
                <div style="clear:both"></div>
        </div>
       
     
       
     <div id="FooterConatiner" style="height:25px"></div>
   </div>
     
    </div>
</body>
</html>



Dropdownlist Binding in MVC without Database

Staff (Model)


       public string branchid { get; set; }
        public IEnumerable<SelectListItem> BranchOptions { get; set; }

        public string countryid { get; set; }
        public IEnumerable<SelectListItem> CountryOptions { get; set; }

       
        public IEnumerable<SelectListItem> DepartmentOptions { get; set; }

AdminController (Controller)


  public enum Departments { All, Marketing, Front, Councellor, Application, Documentation, Accounts, Franchisee, Employer,Agency,Institution,Training }
        [HttpGet]
        public ActionResult AddStaff()
        {
            var model = new Staff();
            model.DepartmentOptions = Enum.GetNames(typeof(Departments))
            .Select(c => new SelectListItem() { Text = c, Value = c })
            .ToArray();

            model.CountryOptions = GetCountries("0");
            model.BranchOptions = GetBranches ("0");

            return View(model);
        }
        private List<SelectListItem> GetCountries(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,cntry from cntry", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["cntry"].ToString(), Value = dr["id"].ToString() });
            }
            dr.Close();
            cn.Close();

            return items;
        }


  private List<SelectListItem> GetBranches(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,branch from Branch", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["branch"].ToString(), Value = dr["id"].ToString() });
            }        
            dr.Close();
            cn.Close();

            return items;
        }


AddStaff (View)


@model CabAutomationSystem.Models.Staff

@{              
    ViewBag.Title = "AddStaff";
    Layout = "~/Views/Admin/Master.cshtml";
}


<body>
<h1>Add New Staff</h1>
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true, "Insertion was unsuccessful. Please correct the errors and try again.")
        <div>
            <fieldset>
                <legend>Staff Information</legend>
               
                <div class="editor-label">
                    @Html.LabelFor(m => m.department)
                </div>
                <div class="editor-field">                  
                     @Html.DropDownListFor(model => model.department, new SelectList(Model.DepartmentOptions, "Value", "Text"))
                   
                    @Html.ValidationMessageFor(m => m.department)
                </div>
               
                <div class="editor-label">
                    @Html.LabelFor(m => m.uname)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.uname)
                    @Html.ValidationMessageFor(m => m.uname)
                </div>
               
                <div class="editor-label">
                    @Html.LabelFor(m => m.pwd)
                </div>
                <div class="editor-field">
                    @Html.PasswordFor(m => m.pwd)
                    @Html.ValidationMessageFor(m => m.pwd)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.name)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.name)
                    @Html.ValidationMessageFor(m => m.name)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.address)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.address)
                    @Html.ValidationMessageFor(m => m.address)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.phoneno)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.phoneno)
                    @Html.ValidationMessageFor(m => m.phoneno)
                </div>

                 <div class="editor-label">
                    @Html.LabelFor(m => m.email)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(m => m.email)
                    @Html.ValidationMessageFor(m => m.email)
                </div>

                  <div class="editor-label">
                    @Html.LabelFor(m => m.country)
                </div>
                <div class="editor-field">                  
                     @Html.DropDownListFor(model => model.countryid, new SelectList(Model.CountryOptions, "Value", "Text"))
                   
                    @Html.ValidationMessageFor(m => m.countryid)
                </div>

                  <div class="editor-label">
                    @Html.LabelFor(m => m.branch)
                </div>
                <div class="editor-field">                  
                     @Html.DropDownListFor(model => model.branchid, new SelectList(Model.BranchOptions, "Value", "Text"))
                   
                    @Html.ValidationMessageFor(m => m.branchid)
                </div>
                             
                <p>
                    <input type="submit" value="Insert" />
                </p>
            </fieldset>
        </div>
    }
</body>




RDLC report generation in Windows Application











using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SQLReportSample
{
    public partial class IndImages : Form
    {
        public IndImages()
        {
            InitializeComponent();
        }

        private void IndImages_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'IndItemsDataSet.getIndItemsReport' table. You can move, or remove it, as needed.
            this.getIndItemsReportTableAdapter.Fill(this.IndItemsDataSet.getIndItemsReport);

            this.reportViewer1.RefreshReport();
        }

        private void btnback_Click(object sender, EventArgs e)
        {
            try
            {
                ReportForm pf = new ReportForm();
                pf.Show();
                this.Hide();
            }
            catch (Exception ex)
            {
            }
        }

        private void IndImages_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }
    }
}












Export to PDF using VB.NET


Private Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Try
            Dim Stream As MemoryStream = pdf()
            Response.Clear()
            Response.AddHeader("content-type", "application/pdf")
            Response.AddHeader("cache-control", "no-cache")
            Response.AddHeader("accept-ranges", "none")
            Dim filename As String = "BOLDetails_" & Request.QueryString("ID").ToString() & ".pdf"
            saveFile(Stream, filename)
            Response.AddHeader("content-disposition", "attachment; filename=" & filename)
            Response.OutputStream.Write(Stream.GetBuffer(), 0, Stream.GetBuffer().Length)
            Response.OutputStream.Flush()
            'Response.Write("<script type='text/javascript'>window.close();</script>")
            Response.OutputStream.Close()
            Response.End()
            'Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "close", "<script type='text/javascript'>window.close();</script>")
        Catch ex As Exception
            Response.Write(ex.Message.ToString())
        End Try
    End Sub


 Private Function pdf() As MemoryStream
        Dim content As String = createHTML()
        Dim reader As TextReader = New StringReader(content)
        Dim doc As New Document(iTextSharp.text.PageSize.A4, 10, 10, 10, 10)
        Dim Stream As New MemoryStream()
        Dim wri As PdfWriter
        wri = PdfWriter.GetInstance(doc, Stream)
        doc.Open()
        Dim htmlarraylist As List(Of IElement) = html.simpleparser.HTMLWorker.ParseToList(reader, Nothing)
        For k As Integer = 0 To htmlarraylist.Count - 1
            doc.Add(DirectCast(htmlarraylist(k), IElement))
        Next
        doc.Close()
        Return Stream
    End Function

    Protected Function createHTML() As String
        Dim html As String = "<table cellspacing='0' cellpadding='0' border='0'><tbody>"
        If chkCreatedDate.Checked = True Then
            html = html & "<tr>" &
                "<td valign='top' align='left'>" &
                "Created Date:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtCreatedDate.Text &
                "</td>" &
                "</tr>"
        End If
        If chkClearDate.Checked = True Then
            html = html & "<tr>" &
                "<td valign='top' align='left'>" &
                "Clear Date:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtClearDate.Text &
                "</td>" &
                "</tr>"
        End If
        If chkDoor.Checked = True Then
            html = html &
                "<tr>" &
                "<td valign='top' align='left'>" &
                "Door #:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtDoor.Text &
                "</td>" &
                "</tr>"
        End If
        If chkName.Checked = True Then
            html = html &
                "<tr>" &
                "<td valign='top' align='left'>" &
                "Name:" &
                "</td>" &
                "<td valign='top' align='left'>" &
                txtName.Text &
                "</td>" &
                "</tr>"
        End If
        If chkDirection.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Direction:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtDirection.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkTrailer.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Trailer:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtTrailer.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkCarrier.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Carrier:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtCarrier.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkToFrom.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "To/From:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtToFrom.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkCompany.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Company:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtCompany.Text &
                    "</td>" &
                    "</tr>"
        End If
        If chkCompanyLoc.Checked = True Then
            html = html &
                    "<tr>" &
                    "<td valign='top' align='left'>" &
                    "Company Location:" &
                    "</td>" &
                    "<td valign='top' align='left'>" &
                    txtCompanyLoc.Text &
                    "</td>" &
                    "</tr>"
        End If
        html = html & "</tbody></table>"
        Return html
    End Function


Export to Excel With Multiple sheets using VB.NET


 Private Sub btnexport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnexport.Click
        Try
            Dim dt As New DataTable()
            Dim dtLane As New DataTable
            Dim dtAsset As New DataTable

            Dim filterdate1 As DateTime
            Dim filterdate2 As DateTime
            Dim Container_id As Int64
            Dim facility_lane_idalerts As Int64
            facility_lane_idalerts = -1
            Container_id = -1
            If txtAlertDate.Text <> "" Then
                filterdate1 = Convert.ToDateTime(txtAlertDate.Text)
                filterdate2 = filterdate1.AddDays(1)
            End If
            If ddlAlertContainer.SelectedValue <> "" Then
                Container_id = ddlAlertContainer.SelectedValue
            End If
            If ddlAlertContainer.SelectedValue = 0 Then
                Container_id = -1
            End If
            If ddlAlertLane.SelectedValue <> 0 Then
                facility_lane_idalerts = ddlAlertLane.SelectedValue
            End If
            If txtAlertDate.Text = "" And Container_id = -1 And facility_lane_idalerts = -1 Then
                Dim qry As String = "SELECT OrphanRecord_ID" &
                                ",a.Created_dt" &
                                ",TagNumber" &
                                ",b.door_name" &
                                " FROM OrphansForLaneEntry  a " &
                                " inner join dbo.facility_lane b on a.TReadIP=b.IPReader " &
                                " WHERE  a.Created_dt>DATEADD(DAY,-1,getdate()) and Reason='NO ASSET' and b.facility_ID=" &
                                hdnFacilityID.Value.ToString()
                dtAsset = DataConnect.GetInstance.GetDt(qry)
                qry = "SELECT OrphanRecord_ID" &
                                ",a.Created_dt" &
                                ",TagNumber" &
                            ",b.door_name,con.container_nbr" &
                            " FROM OrphansForLaneEntry  a " &
                            " inner join dbo.facility_lane b on a.TReadIP=b.IPReader " &
                            " left join dbo.container con on a.container_id=con.container_id " &
                                " WHERE  a.Created_dt>DATEADD(DAY,-1,getdate()) and Reason='NO LANE ASSIGNMENT' and b.facility_ID=" &
                                hdnFacilityID.Value.ToString()
                dtLane = DataConnect.GetInstance.GetDt(qry)

         
            End If

            'Create Tempory Table
            Dim dtTemp As New DataTable()
            Dim dtTemp1 As New DataTable()

            'Creating Header Row
            dtTemp.Columns.Add("Created")
            dtTemp.Columns.Add("TagNumber")
            dtTemp.Columns.Add("Door")



            dtTemp1.Columns.Add("Created")
            dtTemp1.Columns.Add("TagNumber")
            dtTemp1.Columns.Add("Door")
            dtTemp1.Columns.Add("Container")

            Dim dtDate As New DateTime
            Dim dtDate1 As New DateTime

            Dim drAddItem As DataRow
            For i As Integer = 0 To dtAsset.Rows.Count - 1
                drAddItem = dtTemp.NewRow()
                dtDate = Convert.ToDateTime(dtAsset.Rows(i)("Created_dt").ToString())
                drAddItem(0) = dtDate
                drAddItem(1) = dtAsset.Rows(i)("TagNumber").ToString()
                drAddItem(2) = dtAsset.Rows(i)("door_name").ToString()
                dtTemp.Rows.Add(drAddItem)
            Next

            Dim drAddItem1 As DataRow
            For i As Integer = 0 To dtLane.Rows.Count - 1
                drAddItem1 = dtTemp1.NewRow()
                dtDate1 = Convert.ToDateTime(dtLane.Rows(i)("Created_dt").ToString())
                drAddItem1(0) = dtDate1
                drAddItem1(1) = dtLane.Rows(i)("TagNumber").ToString()
                drAddItem1(2) = dtLane.Rows(i)("door_name").ToString()
                drAddItem1(3) = dtLane.Rows(i)("container_nbr").ToString()
                dtTemp1.Rows.Add(drAddItem1)
            Next

            'Dim ds As New DataSet
            'ds.Tables.Add(dtTemp)
            'ds.Tables.Add(dtTemp1)
            'Dim dg As New DataGrid
            'dg.DataSource = ds
            'dg.DataBind()
            'ExportToExcel("Alerts.xls", dg)

            Dim rescDS As DataSet = New DataSet
            Dim studiesDS As DataSet = New DataSet
            ' Get data
            rescDS.Tables.Add(dtTemp)
            studiesDS.Tables.Add(dtTemp1)
            ' Create Excel Application, Workbook, and WorkSheets
            Dim xlExcel As New Excel.Application
            Dim xlBooks As Excel.Workbooks
            Dim xlBook As Excel.Workbook
            Dim xlSheets As Excel.Sheets
            Dim stdSheet As Excel.Worksheet
            Dim xlCells As Excel.Range
            Dim sFile As String
            Dim sTemplate As String
            Dim rescSheet As Excel.Worksheet

            sFile = Server.MapPath("ExcelFormatFile\LaneAssignmentAlerts.xls")
            ' Formatted template the way you want.
            ' If you want to change the format, change this template
            sTemplate = Server.MapPath("\ExcelFormatFile\LaneAssignment.xls")
            xlExcel.Visible = False : xlExcel.DisplayAlerts = False
            ' Get all workbooks and open first workbook
            xlBooks = xlExcel.Workbooks
            xlBooks.Open(Server.MapPath("\ExcelFormatFile\LaneAssignment.xls"))
            xlBook = xlBooks.Item(1)
            ' Get all sheets available in first book
            xlSheets = xlBook.Worksheets
            ' Get first sheet, change its name and get all cells
            stdSheet = CType(xlSheets.Item(1), Excel.Worksheet)
            stdSheet.Name = "Unidentified Lane Assignment"
            xlCells = stdSheet.Cells
            ' Fill all cells with data
            GenerateExcelFile(studiesDS.Tables(0), xlCells) 'Fill in the data

            ' Get second sheet, change its name and get all cells
            rescSheet = CType(xlSheets.Item(2), Excel.Worksheet)
            rescSheet.Name = "Unidentified Asset Movement"
            xlCells = rescSheet.Cells
            ' Fill all cells with data
            GenerateExcelFile(rescDS.Tables(0), xlCells)

            ' Save created sheets as a file
            xlBook.SaveAs(sFile)

            ' Make sure all objects are disposed
            xlBook.Close()
            xlExcel.Quit()
            ReleaseComObject(xlCells)
            ReleaseComObject(stdSheet)
            ReleaseComObject(xlSheets)
            ReleaseComObject(xlBook)
            ReleaseComObject(xlBooks)
            ReleaseComObject(xlExcel)
            xlExcel = Nothing
            xlBooks = Nothing
            xlBook = Nothing
            xlSheets = Nothing
            stdSheet = Nothing
            xlCells = Nothing
            rescSheet = Nothing
            ' Let GC know about it
            GC.Collect()

            ' Export Excel for download
            Dim File As FileInfo = New FileInfo(sFile)
            Response.Clear()
            Response.Charset = "UTF-8"
            Response.ContentEncoding = System.Text.Encoding.UTF8
            'Add header, give a default file name for "File Download/Store as"
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(File.Name))
            'Add header, set file size to enable browser display download progress
            Response.AddHeader("Content-Length", File.Length.ToString())
            'Set the return string is unavailable reading for client, and must be downloaded
            Response.ContentType = "application/ms-excel"
            'Send file string to client
            Response.TransmitFile(File.FullName)

            Response.End()
        Catch ex As Exception
            pnlGlobalMessage.Visible = True
            lblGlobalMessage.Text = "A technical issue has occurred.  A message has been sent to the development team.  Sorry for the inconvenience."
            lblGlobalMessage.Visible = True
            Dim dt As DataTable = Session("user_session")
            Worker.HandleError(ex, "Lane History Excel", Int64.Parse(dt.Rows(0)("user_id")), Request.Browser.Browser.ToString())
        End Try
    End Sub

    ' Generates Excel sheet for the given DataTable's data
    Private Function GenerateExcelFile(ByRef table As DataTable, ByVal xlCells As Excel.Range) As String
        Dim dr As DataRow, ary() As Object
        Dim iRow As Integer, iCol As Integer
        'Output Column Headers
        For iCol = 0 To table.Columns.Count - 1
            xlCells(1, iCol + 1) = table.Columns(iCol).ToString
        Next
        'Output Data
        For iRow = 0 To table.Rows.Count - 1
            dr = table.Rows.Item(iRow)
            ary = dr.ItemArray
            For iCol = 0 To UBound(ary)
                xlCells(iRow + 2, iCol + 1) = ary(iCol).ToString
                Response.Write(ary(iCol).ToString & vbTab)
            Next
        Next
    End Function

Dropdownlist Binding in MVC

BranchAdmin (Model)

  public string branchid { get; set; }
  public IEnumerable<SelectListItem> BranchOptions { get; set; }
     
AdminController (Controller)


   [HttpGet]
        public ActionResult AddBranchAdmin()
        {
            var model = new BranchAdmin ();
            // Populate the dropdown options
            model.BranchOptions = GetBranches("0"); // Set the default to American Express
           
            return View(model);
        }
        private List<SelectListItem> GetBranches(string defaultValue)
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Select", Value = "0", Selected = (defaultValue == "0") });
            SqlCommand cmd = new SqlCommand("select id,branch from Branch", cn);
            cn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                items.Add(new SelectListItem { Text = dr["branch"].ToString(), Value = dr["id"].ToString() });
            }        
            dr.Close();
            cn.Close();

            return items;
        }

AddBranchAdmin (View)

@model CabAutomationSystem.Models.BranchAdmin


  <div class="editor-field">                  
                     @Html.DropDownListFor(model => model.branchid, new SelectList(Model.BranchOptions, "Value", "Text"))
                   
                    @Html.ValidationMessageFor(m => m.branch)
                </div>
               



Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...