Thursday, April 17, 2014

Create Thumbnail in C# windows application

//This function creates the Thumbnail image and returns the
      //image created in Byte() format
      public static byte[] createThumnail(Stream ImageStream, Double tWidth, Double tHeight)
      {
          System.Drawing.Image g = System.Drawing.Image.FromStream(ImageStream);
          Size thumbSize = new Size();
          thumbSize = NewThumbSize(g.Width, g.Height, tWidth, tHeight);
          Bitmap imgOutput = new Bitmap(g, thumbSize.Width, thumbSize.Height);
          MemoryStream imgStream = new MemoryStream();
          System.Drawing.Imaging.ImageFormat thisFormat = g.RawFormat;
          imgOutput.Save(imgStream, thisFormat);
          int imgBinLength = (int)imgStream.Length;
          byte[] imgBin = new byte[imgBinLength];
          imgStream.Position = 0;
          int n = imgStream.Read(imgBin, 0, imgBinLength);
          g.Dispose();
          imgOutput.Dispose();
          return imgBin;
      }
      public static Size NewThumbSize(Double currentwidth, Double currentheight, Double newWidth, Double newHeight)
      {
          //Calculate the Size of the New image
          Double tempMultiplier;
          if (currentheight > currentwidth)        // Then it's portrait
          {
              tempMultiplier = newHeight / currentheight;
          }
          else
          {
              tempMultiplier = newWidth / currentwidth;
          }

          Size NewSize = new Size(Convert.ToInt16(currentwidth * tempMultiplier), Convert.ToInt16(currentheight * tempMultiplier));
          return NewSize;
      }


      public static Image byteArrayToImage(byte[] byteArrayIn)
      {
          MemoryStream ms = new MemoryStream(byteArrayIn);
          Image returnImage = Image.FromStream(ms);
          return returnImage;
      }

Export DataTable To Excel in c# windows application

 public static void ExportDTToExcel(System.Data.DataTable dt,string FileName)
      {

        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        app.Visible = false; 

        Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

        Worksheet ws = (Worksheet)wb.ActiveSheet; 
        
        // Headers.

        for (int i = 1; i < dt.Columns.Count; i++)
        {
          ws.Cells[1, i] = dt.Columns[i].ColumnName;
        } 

        // Content.

        for (int i = 0; i < dt.Rows.Count; i++)
        {

          for (int j = 1; j < dt.Columns.Count; j++)
          {

            ws.Cells[i + 2, j ] = dt.Rows[i][j].ToString();

          }

        } 

        // Lots of options here. See the documentation.

        wb.SaveAs(FileName );


        wb.Close();

        app.Quit();

      }

SMS Gateway Integration in windows application


                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                    proc.EnableRaisingEvents = false;
                    proc.StartInfo.FileName = "iexplore";
                    proc.StartInfo.Arguments = "http://bulksmsalert.in/SendSms.aspx?username=ekmkgm&password=ekmkgm25&to=" + txtMobile.Text + "&from=ekmkgm&message=" + Message + "";
                    proc.Start();

Label Printing using C# windows application





RDLC XML Code for Design:

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition">
  <DataSources>
    <DataSource Name="LMSDataSet">
      <ConnectionProperties>
        <DataProvider>System.Data.DataSet</DataProvider>
        <ConnectString>/* Local Connection */</ConnectString>
      </ConnectionProperties>
      <rd:DataSourceID>dc9db719-e783-439b-8a6a-21c2d68ef8d9</rd:DataSourceID>
    </DataSource>
  </DataSources>
  <DataSets>
    <DataSet Name="LabelDataSet">
      <Fields>
        <Field Name="SlNo">
          <DataField>SlNo</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="TITLE">
          <DataField>TITLE</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="MEMBNO">
          <DataField>MEMBNO</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="NAME">
          <DataField>NAME</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="ADDR1">
          <DataField>ADDR1</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="ADDR2">
          <DataField>ADDR2</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="CITY">
          <DataField>CITY</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="ROAD">
          <DataField>ROAD</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="PHONE">
          <DataField>PHONE</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
        <Field Name="PIN">
          <DataField>PIN</DataField>
          <rd:TypeName>System.String</rd:TypeName>
        </Field>
      </Fields>
      <Query>
        <DataSourceName>LMSDataSet</DataSourceName>
        <CommandText>/* Local Query */</CommandText>
      </Query>
      <rd:DataSetInfo>
        <rd:DataSetName>LabelManagementSystem</rd:DataSetName>
        <rd:TableName>AddressDetailsDataTable</rd:TableName>
        <rd:ObjectDataSourceType>LabelManagementSystem.LMSDataSet+AddressDetailsDataTable, LMSDataSet.Designer.cs, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
      </rd:DataSetInfo>
    </DataSet>
  </DataSets>
  <Body>
    <ReportItems>
      <Tablix Name="Tablix2">
        <TablixBody>
          <TablixColumns>
            <TablixColumn>
              <Width>2.67717in</Width>
            </TablixColumn>
          </TablixColumns>
          <TablixRows>
            <TablixRow>
              <Height>1.3061in</Height>
              <TablixCells>
                <TablixCell>
                  <CellContents>
                    <Rectangle Name="Rectangle1">
                      <ReportItems>
                        <Tablix Name="Tablix1">
                          <TablixBody>
                            <TablixColumns>
                              <TablixColumn>
                                <Width>2.67717in</Width>
                              </TablixColumn>
                            </TablixColumns>
                            <TablixRows>
                              <TablixRow>
                                <Height>1.1811in</Height>
                                <TablixCells>
                                  <TablixCell>
                                    <CellContents>
                                      <Textbox Name="Name">
                                        <CanGrow>true</CanGrow>
                                        <KeepTogether>true</KeepTogether>
                                        <Paragraphs>
                                          <Paragraph>
                                            <TextRuns>
                                              <TextRun>
                                                <Value>=System.Environment.NewLine+System.Environment.NewLine+ trim(IIF(Fields!MEMBNO.Value="","",Fields!MEMBNO.Value)) +UCase(trim(IIF(Fields!NAME.Value="","",System.Environment.NewLine+Fields!TITLE.Value+". "+Fields!NAME.Value)) +Trim(IIF(Fields!ADDR1.Value="","",System.Environment.NewLine+ Fields!ADDR1.Value))+Trim(IIF(Fields!ADDR2.Value="","",System.Environment.NewLine+ Fields!ADDR2.Value))+Trim(IIF(Fields!ROAD.Value="","",System.Environment.NewLine+ Replace(Fields!ROAD.Value,",","")))  +Trim(IIF(Fields!CITY.Value="","",System.Environment.NewLine+ Replace(Fields!CITY.Value,",","")))+Trim(IIF(Fields!PIN.Value="","","-"+Replace(Fields!PIN.Value,",",""))))</Value>
                                                <Style>
                                                  <FontFamily>Times New Roman</FontFamily>
                                                  <FontSize>9pt</FontSize>
                                                </Style>
                                              </TextRun>
                                            </TextRuns>
                                            <Style />
                                          </Paragraph>
                                        </Paragraphs>
                                        <rd:DefaultName>Name</rd:DefaultName>
                                        <Style>
                                          <Border>
                                            <Color>White</Color>
                                            <Style>Solid</Style>
                                          </Border>
                                        </Style>
                                      </Textbox>
                                      <rd:Selected>true</rd:Selected>
                                    </CellContents>
                                  </TablixCell>
                                </TablixCells>
                              </TablixRow>
                            </TablixRows>
                          </TablixBody>
                          <TablixColumnHierarchy>
                            <TablixMembers>
                              <TablixMember>
                                <Group Name="ColumnGroup">
                                  <GroupExpressions>
                                    <GroupExpression>=RowNumber("list1_Details_Group")</GroupExpression>
                                  </GroupExpressions>
                                </Group>
                              </TablixMember>
                            </TablixMembers>
                          </TablixColumnHierarchy>
                          <TablixRowHierarchy>
                            <TablixMembers>
                              <TablixMember>
                                <TablixMembers>
                                  <TablixMember />
                                </TablixMembers>
                              </TablixMember>
                            </TablixMembers>
                          </TablixRowHierarchy>
                          <KeepTogether>true</KeepTogether>
                          <DataSetName>ListDS</DataSetName>
                          <Height>2.99999cm</Height>
                          <Width>6.80001cm</Width>
                          <Style>
                            <Border>
                              <Color>White</Color>
                              <Style>Solid</Style>
                            </Border>
                            <Color>White</Color>
                          </Style>
                        </Tablix>
                      </ReportItems>
                      <KeepTogether>true</KeepTogether>
                      <Style>
                        <Border>
                          <Style>None</Style>
                        </Border>
                      </Style>
                    </Rectangle>
                  </CellContents>
                </TablixCell>
              </TablixCells>
            </TablixRow>
          </TablixRows>
        </TablixBody>
        <TablixColumnHierarchy>
          <TablixMembers>
            <TablixMember />
          </TablixMembers>
        </TablixColumnHierarchy>
        <TablixRowHierarchy>
          <TablixMembers>
            <TablixMember>
              <Group Name="list1_Details_Group">
                <GroupExpressions>
                  <GroupExpression>=Ceiling(RowNumber(Nothing)/3)</GroupExpression>
                </GroupExpressions>
              </Group>
            </TablixMember>
          </TablixMembers>
        </TablixRowHierarchy>
        <KeepTogether>true</KeepTogether>
        <DataSetName>LabelDataSet</DataSetName>
        <Left>1.28796cm</Left>
        <Height>3.31749cm</Height>
        <Width>6.80001cm</Width>
        <Style>
          <Border>
            <Style>None</Style>
          </Border>
        </Style>
      </Tablix>
    </ReportItems>
    <Height>33.91957cm</Height>
    <Style />
  </Body>
  <Width>8.08797cm</Width>
  <Page>
    <PageHeight>29.7cm</PageHeight>
    <PageWidth>21cm</PageWidth>
    <LeftMargin>2.54cm</LeftMargin>
    <RightMargin>2.54cm</RightMargin>
    <TopMargin>1.27cm</TopMargin>
    <BottomMargin>1.27cm</BottomMargin>
    <Columns>3</Columns>
    <ColumnSpacing>0.3cm</ColumnSpacing>
    <Style />
  </Page>
  <rd:ReportID>a4333754-f838-4002-9f3b-41e041186bf6</rd:ReportID>
  <rd:ReportUnitType>Cm</rd:ReportUnitType>
</Report>

Codebehind C#:

   private void FillReport(DataTable dt)
        {
            reportViewer1.ProcessingMode = ProcessingMode.Local;           
            reportViewer1.LocalReport.ReportPath = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Sowhridam.rdlc";
            reportViewer1.LocalReport.DataSources.Add(new ReportDataSource(reportViewer1.LocalReport.GetDataSourceNames()[0], dt));
            this.reportViewer1.RefreshReport();
        }

Paging in DataGridView of Windows Application

Preview of Paging Control
Add Toolstrip and change properties like above



























Codebehind:

 private void FillGrid(string SortColumn)
        {

            if (con.con.State == ConnectionState.Closed)
            {
                con.con.Open();
            }
            string City = "" ;
            string PinCode = "" ;
            string PostOffice =  "" ;
            string District ="" ;
            string State =  "";
            string Name = cmbName.Text == "Select" ? "" : cmbName.Text;
            string MEMBNO = cmbMemberNo.Text == "Select" ? "" : cmbMemberNo.Text;
            string BloodGroup =  "" ;

            string query = "";
            query = "SELECT * FROM( select row_number() OVER (ORDER BY " + SortColumn + ") AS SlNo,SlNo as Id,TITLE," +
                    " MEMBNO,NAME,ADDR1,ADDR2,ROAD,CITY," +
                    " PIN,BLOODGRP,PHONE,ThumbPhoto from Members " +
                    "left join MembershipCard  on MEMBNO=CardNO " +
                    "where CITY like '%" + City + "%' and  PIN like '%" + PinCode + "%' and  ROAD like '%" + PostOffice + "%' " +
                    "and NAME like '%" + Name + "%' and MEMBNO like '%" + MEMBNO + "%' and BLOODGRP like '%" + BloodGroup +
                    "%'  and Status=1 ) AS alias  WHERE  SlNo BETWEEN (@PageIndex - 1) * @PageSize + 1 " +
                    " AND @PageIndex * @PageSize  order by " + SortColumn + " asc ";
            query = query.Replace("@PageSize", pageRows.ToString());
            query = query.Replace("@PageIndex", CurrentPage.ToString());

            SqlDataAdapter da = new SqlDataAdapter(query, con.con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dt = ds.Tables[0];

         

            dt1 = new DataTable();
            dt1.Columns.Add("Select", System.Type.GetType("System.Boolean"));
            dt1.Columns.Add("SlNo");
            dt1.Columns.Add("Id");
            dt1.Columns.Add("TITLE");
            dt1.Columns.Add("MEMBNO");
            dt1.Columns.Add("NAME");
            dt1.Columns.Add("ADDR1");
            dt1.Columns.Add("ADDR2");
            dt1.Columns.Add("ROAD");
            dt1.Columns.Add("CITY");
            dt1.Columns.Add("PIN");
            dt1.Columns.Add("BLOODGRP");
            dt1.Columns.Add("PHONE");
            //dt1.Columns.Add("Photo", typeof(Bitmap));
            //dt1.Columns["Photo"].AllowDBNull = true;


            tempdt = new DataTable();
            tempdt.Columns.Add("Select", System.Type.GetType("System.Boolean"));
            tempdt.Columns.Add("SlNo");
            tempdt.Columns.Add("Id");
            tempdt.Columns.Add("TITLE");
            tempdt.Columns.Add("MEMBNO");
            tempdt.Columns.Add("NAME");
            tempdt.Columns.Add("ADDR1");
            tempdt.Columns.Add("ADDR2");
            tempdt.Columns.Add("ROAD");
            tempdt.Columns.Add("CITY");
            tempdt.Columns.Add("PIN");
            tempdt.Columns.Add("BLOODGRP");
            tempdt.Columns.Add("PHONE");
            //tempdt.Columns.Add("Photo", typeof(Bitmap));
            //tempdt.Columns["Photo"].AllowDBNull = true;

            DataRow dr;

            for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                dr = dt1.NewRow();

                dr["Select"] = false;
                dr["SlNo"] = dt.Rows[i]["SlNo"].ToString();
                dr["Id"] = dt.Rows[i]["Id"].ToString();
                dr["TITLE"] = dt.Rows[i]["TITLE"].ToString();
                dr["MEMBNO"] = dt.Rows[i]["MEMBNO"].ToString();
                dr["NAME"] = dt.Rows[i]["NAME"].ToString();
                dr["ADDR1"] = dt.Rows[i]["ADDR1"].ToString();
                dr["ADDR2"] = dt.Rows[i]["ADDR2"].ToString();
                dr["ROAD"] = dt.Rows[i]["ROAD"].ToString();
                dr["CITY"] = dt.Rows[i]["CITY"].ToString();
                dr["PIN"] = dt.Rows[i]["PIN"].ToString();
                dr["BLOODGRP"] = dt.Rows[i]["BLOODGRP"].ToString();
                //dr["PHONE"] = dt.Rows[i]["PHONE"].ToString();
                //if (dt.Rows[i]["ThumbPhoto"] == DBNull.Value)
                //{

                //    System.IO.FileInfo imageInfo = new System.IO.FileInfo(Path.GetDirectoryName(
                //                                                        System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\face_outline.gif");

                //    Photocontent = new byte[imageInfo.Length];
                //    imagestream = imageInfo.OpenRead();
                //    imagestream.Read(Photocontent, 0, Photocontent.Length);
                //    Photocontent = CommonFunctions.createThumnail(imagestream, 50, 50);
                //    dr["Photo"] = CommonFunctions.byteArrayToImage(Photocontent);
                //}
                //else
                //{
                //    dr["Photo"] = CommonFunctions.byteArrayToImage((byte[])dt.Rows[i]["ThumbPhoto"]);
                //}
                dt1.Rows.Add(dr);
            }

            dgvUsers.AllowUserToAddRows = false;
            dgvUsers.AllowUserToDeleteRows = false;
            dgvUsers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvUsers.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

            dgvUsers.DataSource = dt1;


         
            dgvUsers.Refresh();
            con.con.Close();
        }
       
        private void RefreshGrid(string SortColumn)
        {
            FillGrid(SortColumn);

            if (con.con.State == ConnectionState.Closed)
            {
                con.con.Open();
            }
            cmd = new SqlCommand("select COUNT(*) from Members", con.con);
            int count = int.Parse(cmd.ExecuteScalar().ToString());
            lblmsg.Text = "Total Number : " + count;

            PagesCount = Convert.ToInt32(Math.Ceiling(count * 1.0 / pageRows));
            CurrentPage = 1;

            RefreshPagination();
            RebindGridForPageChange();
        }

        private void RebindGridForPageChange()
        {
            //Rebinding the Datagridview with data
            int datasourcestartIndex = (CurrentPage - 1) * pageRows;

            tempdt = dt1.Clone();
            DataRow dr = null;
            int ii = 0;
            int jj = 0;
            tempdt.Rows.Clear();

          

            for (int i = datasourcestartIndex; i < datasourcestartIndex + pageRows; i++)
            {
                if (i >= dt1.Rows.Count)
                    break;


                dr = tempdt.NewRow();
                for (jj = 0; jj <= dgvUsers.Columns.Count - 1; jj++)
                {
                    if (jj == 13)
                    {
                        dr[jj] = (Bitmap)dt1.Rows[i][jj];
                    }
                    else
                    {
                        dr[jj] = dt1.Rows[i][jj].ToString();
                    }
                }
                tempdt.Rows.Add(dr);
            }

            dgvUsers.DataSource = tempdt;
            dgvUsers.Refresh();
        }

        private void RefreshPagination()
        {
            ToolStripButton[] items = new ToolStripButton[] { toolStripButton1, toolStripButton2, toolStripButton3, toolStripButton4, toolStripButton5 };

            //pageStartIndex contains the first button number of pagination.
            int pageStartIndex = 1;

            if (PagesCount > 10 && CurrentPage > 2)
                pageStartIndex = CurrentPage - 2;

            if (PagesCount > 10 && CurrentPage > PagesCount - 2)
                pageStartIndex = PagesCount - 4;

            for (int i = pageStartIndex; i < pageStartIndex + 5; i++)
            {
                if (i > PagesCount)
                {
                    items[i - pageStartIndex].Visible = false;
                }
                else
                {
                    //Changing the page numbers
                    items[i - pageStartIndex].Text = i.ToString(CultureInfo.InvariantCulture);

                    //Setting the Appearance of the page number buttons
                    if (i == CurrentPage)
                    {
                        items[i - pageStartIndex].BackColor = Color.Black;
                        items[i - pageStartIndex].ForeColor = Color.White;
                    }
                    else
                    {
                        items[i - pageStartIndex].BackColor = Color.White;
                        items[i - pageStartIndex].ForeColor = Color.Black;
                    }
                }
            }

            //Enabling or Disalbing pagination first, last, previous , next buttons
            if (CurrentPage == 1)
                btnBackward.Enabled = btnFirst.Enabled = false;
            else
                btnBackward.Enabled = btnFirst.Enabled = true;

            if (CurrentPage == PagesCount)
                btnForward.Enabled = btnLast.Enabled = false;

            else
                btnForward.Enabled = btnLast.Enabled = true;
        }

Add Multiple file uploading in asp.net





<script type="text/javascript">

var counter = 0;

function AddFileUpload() {

var div = document.createElement('DIV');

div.innerHTML = '<input id="file' + counter + '" name = "file' + counter +

'" type="file" />' +

'<input id="Button' + counter + '" type="button" ' +

'value="Remove" onclick = "RemoveFileUpload(this)" />';

document.getElementById("FileUploadContainer").appendChild(div);

counter++;

}

function RemoveFileUpload(div) {

document.getElementById("FileUploadContainer").removeChild(div.parentNode);

}

</script>

 <form id="form1" runat="server" enctype="multipart/form-data" method="post">

<table>
<tbody>
<tr>
<td>
<span style="font-family: Arial">Click to add files</span>&nbsp;&nbsp;
<input id="Button1" type="button" value="add" onclick="AddFileUpload()" />
<br />
<br />
<div id="FileUploadContainer">
<!--FileUpload Controls will be added here -->
</div>
<br />
</td>
</tr>
<tr>
<td align="left">
<hr />
<asp:Label runat="server" ID="lblFiles"></asp:Label>
</td>
</tr>
</tbody>
</table>
</form>


Codebehind:

 for (int i = 0; i < Request.Files.Count; i++)
            {

                HttpPostedFile PostedFile = Request.Files[i];

                if (PostedFile.ContentLength > 0)
                {

                    string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
                    Stream fs = PostedFile.InputStream;
                    BinaryReader br = new BinaryReader(fs);
                    byte[] ba = br.ReadBytes((Int32)fs.Length);

                 }

            }

Thursday, March 28, 2013

Dynamic Word Document Creation,view as thumbnail and Download in asp.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing;
using System.Text;
using System.Drawing.Imaging;

namespace AccordionMenu
{
    public partial class WebForm10 : System.Web.UI.Page
    {
        //http://wfjanjua.blogspot.in/2011/09/read-ms-word-document-edit-it-and.html
        //http://cathalscorner.blogspot.in/2009/08/docx-v1007-released.html
        //http://docx.codeplex.com/releases/view/31554
        //http://richtexteditor.com/

        //<script type="text/javascript">
        // function createTextSnippet() {
        //     //example as before, replace YOUR_TEXTAREA_ID
        //     var html=CKEDITOR.instances.YOUR_TEXTAREA_ID.getSnapshot();
        //     var dom=document.createElement("DIV");
        //     dom.innerHTML=html;
        //     var plain_text=(dom.textContent || dom.innerText);
        //     //create and set a 128 char snippet to the hidden form field
        //     var snippet=plain_text.substr(0,127);
        //     document.getElementById("hidden_snippet").value=snippet;
        //     //return true, ok to submit the form
        //     return true;
        // }
        //</script>

        protected void Page_Load(object sender, EventArgs e)
        {

        }
      
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (fupDoc.HasFile == true)
            {
                if (System.IO.Path.GetExtension(fupDoc.FileName) == ".doc")
                {
                    fupDoc.SaveAs(Server.MapPath("~\\docs\\") +fupDoc.FileName);
                    this.lblupload.Text = "Doc successfully uploaded";
                    ViewState["doc"] = fupDoc.FileName;
                    //DocX doc = DocX.Load(Server.MapPath("~\\docs\\") + fupDoc.FileName);     
                    ////Created a Docx variable doc and using Docx.Load("word file") to load the word 2007 file                        
                    //txtWord.Text = doc.Text;
                    ////Set the text property of doc to textbox text property. Text property of doc returns all the text from the word document.              
               }
               else
               {
                    Response.Write("");        
               }
            }
            else
            {
                   Response.Write("");        
            }

            if (fupImage.HasFile == true)
            {
                if (System.IO.Path.GetExtension(fupImage.FileName) == ".jpg")
                {
                    fupImage.SaveAs(Server.MapPath("~\\images\\") + fupImage.FileName);
                    this.lblupload.Text = "Image successfully uploaded";                               
                }
                else
                {
                    Response.Write("");
                }
            }
            else
            {
                Response.Write("");
            }
         }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                FileInfo file = new FileInfo(MapPath("~\\docs\\") + ViewState["doc"].ToString());
                if (file.Exists)
                {
                    File.Delete(MapPath("~\\docs\\") + ViewState["doc"].ToString());
                    // Delete existing word file
                }
                //DocX doc = DocX.Create(Server.MapPath("~\\CVs\\") + ViewState["doc"].ToString();
                //// Create a new word document          
                //Formatting f = new Formatting();
                //f.FontFamily = new FontFamily("Tahoma");
                ////Defines font family
                //doc.InsertParagraph(txtWord.Text,false,f);   
                //doc.Save();  
       
               
            }
            catch (Exception)
            {

            }
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            string data = txtWord.Text.ToString();
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Byte[] bytes = encoding.GetBytes(data);
            data = System.Text.ASCIIEncoding.ASCII.GetString(bytes);

            byte[] stringdata = System.Text.Encoding.UTF8.GetBytes(txtWord.Text);
            string result = System.Text.Encoding.UTF8.GetString(stringdata);

           
            Color FontColor = Color.Black;
            Color BackColor = Color.White;
            string FontName = "Times New Roman";
            int FontSize = 12;
            int Height = 40;
            int Width = 200;          

            MemoryStream ms = new MemoryStream();
            Bitmap objBitmap = new Bitmap(Width, Height);
            Graphics objGraphics = Graphics.FromImage(objBitmap);
            Font objFont = new Font(FontName, FontSize);
            PointF objPoint = new PointF(5f, 5f);
            SolidBrush objBrushForeColor = new SolidBrush(FontColor);
            SolidBrush objBrushBackColor = new SolidBrush(BackColor);
            objGraphics.FillRectangle(objBrushBackColor, 0, 0, Width, Height);
            objGraphics.DrawString(result, objFont, objBrushForeColor, objPoint);
            objBitmap.Save(ms, ImageFormat.Jpeg);

         
            objBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] bmpBytes = ms.GetBuffer();
            objBitmap.Dispose();
            ms.Close();

            //Bitmap bit1 = new Bitmap(200, 30, System.Drawing.Imaging.PixelFormat.Format64bppArgb);
            //Graphics gph1 = Graphics.FromImage(bit1);
            //string text;
            //gph1.Clear(Color.Orange);
            //text = result;
            //gph1.DrawString(text, new Font("Arial", 12, FontStyle.Bold),
            //new SolidBrush(Color.Red), new PointF(0.4F, 2.4F));
            //Response.ContentType = "image/Jpeg";          
            //bit1.Save(Response.OutputStream, ImageFormat.Jpeg);
            //bit1.Dispose();

            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=test.doc");
            Response.ContentType = "application/msword";
            Response.BinaryWrite(stringdata);
            Response.Flush();
            Response.End();

            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=test.jpg");
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(bmpBytes);
            Response.Flush();
            Response.End();
        }
    }
}

Using Authorization with Swagger in ASP.NET Core

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