Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, October 21, 2014

Print HTML to PDF in Windows Application

Print HTML to PDF in Windows Forms (C#)




using TuesPechkin one can generate good quality PDF from html string both on Web or in windows application. 
First of all Download TuesPechkin.dll  or 
download source code and build it and add this dll in your project.

Link:
https://github.com/tuespetre/TuesPechkin

Now use the following in your main form, It requires html string and file path parameters.

using System;using System.Diagnostics;using System.Drawing.Printing;using System.IO;using System.Linq;using System.Windows.Forms;using TuesPechkin;
      {
            {
                GlobalSettings = {
                    ProduceOutline = true,
                    DocumentTitle = "Invoice Pdf",
                    PaperSize = PaperKind.A4,
                    Margins = {
                        Top = 1.5,
                        Right = 1,
                        Bottom = 1,
                        Left = 1.25,
                        Unit = Unit.Centimeters
                    }
                },
                Objects = {
                    new ObjectSettings { HtmlText = html }  ////                }
            };
            IPechkin sc2 = Factory.Create();
            var buf = sc2.Convert(document);                                 
                string fn = string.Format(PathWithName, Path.GetTempFileName());
                fs.Write(buf, 0, buf.Length);
                fs.Close();
                
                Process myProcess = new Process();
                myProcess.StartInfo.FileName = fn;
                myProcess.Start();
          
         

   private void CreateHtmlToPdf(string html,string PathWithName)
 var document = new HtmlToPdfDocument
                FileStream fs = new FileStream(fn, FileMode.Create);





Thursday, June 28, 2012

Insert selected records (checkboxes) from asp gridView & perform CRUD operations


Scenario :- I have to perform CRUD operation for selected records ( check boxes) in a GridView  ID as described in the image.









No what we are doing  is to perform a for loop on datatgrid & get selected checkbox id in a string varibale separted by ','.After that we will create a DB function that will split the checkbox ID'd string in new row for each id.


It will make CRUD operation very easy


GridView in aspx:-





  <asp:DataGrid ID="grdList" DataKeyField="diagnosis_id" Runat="server" AutoGenerateColumns="False"
AllowPaging="False" PageSize="100" ShowHeader="true"  >
<Columns>
<asp:BoundColumn DataField="diagnosis_name" HeaderText="DIAGNOSIS" SortExpression="diagnosis_name asc">
<HeaderStyle Width="75%" HorizontalAlign="Center" ></HeaderStyle>
<ItemStyle CssClass="greylabelsmall"></ItemStyle>
</asp:BoundColumn>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>






VB function to get selected checkboxes in datagrid




 Private Sub GetCheckedBox()
        For Each item As DataGridItem In grdICDList.Items
            If CType(item.FindControl("chkICD"), CheckBox).Checked Then
                icdIds = icdIds + Convert.ToString( grdList .DataKeys.Item(item.ItemIndex)) + ","
            End If
        Next
        If icdIds.Length > 0 Then
            If icdIds.LastIndexOf(",") > 0 Then
                icdIds = icdIds.Substring(0, icdIds.Length - 1)
            End If
            'SaveICDs()
            InsertDiagnosis(icdIds)
        End If
    End Sub








Now create a db Function like this:-


CREATE  FUNCTION [dbo].[Split]      
(      
 @RowData varchar(8000),      
 @SplitOn nvarchar(5)      
)       
RETURNS @RtnValue table      
(      
 Id int identity(1,1),      
 Data nvarchar(100)      
)      
AS       
BEGIN      
 Declare @Cnt int      
 Set @Cnt = 1      
      
 While (Charindex(@SplitOn,@RowData)>0)      
 Begin      
  Insert Into @RtnValue (data)      
  Select      
   Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))      
      
  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))      
  Set @Cnt = @Cnt + 1      
 End      
       
 Insert Into @RtnValue (data)      
 Select Data = ltrim(rtrim(@RowData))      
      
 Return      
END 








And Use it in your stored procedures like this :-





                INSERT INTO INSERTABC         
                        (CPTID,   
                         
                         ICDID,   
                         CREATED_USER,         
                         CREATED_DATE,         
                         ISDELETED)         
       SELECT @CPTID,LTRIM(RTRIM(DATA)), @CREATED_USER,  GETDATE(),0   FROM SPLIT(@ICDIDS,','






Example :--


  SELECT DATA  FROM SPLIT(@ICDIDS, ',' )
Data will give you select check boxes ID in new rows.
  
   

Wednesday, May 30, 2012

Display Image from Database in ASP.NET


Scenario - I have image names (eg:- abc.jpg) saved in a database & actual images lie in a folder in file system (~/ClientImages/).
Now I want to retrieve image from db & diplay it on webpage,in a div 

Solution :-

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="id" DataSourceID="SqlDataSource1">
    <Columns>          
   <asp:TemplateField>
  <ItemTemplate>
  <asp:Image ID="img12" runat="server" Width="600px" Height="400" ImageUrl='<%# Page.ResolveUrl(string.Format("~/ClientImages/{0}", Eval("image"))) %>' />

  </ItemTemplate>
  </asp:TemplateField>

    </Columns>
</asp:GridView>

## SqlDataSource ##
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:XXXXConnectionStringName %>" 
    SelectCommand="Stored_Procedure_Name" SelectCommandType="StoredProcedure">
</asp:SqlDataSource>

Friday, January 13, 2012

Send Mail in C#


Create a simple aspx form :

// Use Validation
<asp:TextBox ID="txtName" runat="server" />
<asp:TextBox ID="txtFrom" runat="server" />                                  
<asp:TextBox ID="txtBody" runat="server"  TextMode="MultiLine"  />
<asp:Button ID="Btn_SendMail" Text="Send Mail" runat="server" onclick="Btn_SendMail_Click" />                                



C#

Add Namespace using System.Net.Mail;



 protected void Btn_SendMail_Click(object sender, EventArgs e)
    {
        MailMessage mailObj = new MailMessage(
           txtFrom.Text, "x@xxx.org ", "Message from" + txtName.Text.ToString(), txtBody.Text);
        SmtpClient SMTPServer = new SmtpClient("xxx.org");      // Check your SMTP server Name
        try
        {
            SMTPServer.Send(mailObj);
// show a success pop up
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }


Wednesday, December 21, 2011

Display Image from Database in ASP.NET

Scenario -

I have image names (eg:- abc.jpg) saved in a database & actual images lie in a folder in file system (~/ClientImages/).

Now I want to retrieve image from db & diplay it on webpage,in a div

Solution :-
 It is a very basic method,You can also fill the datagrid from CS file,But I opted dirty approach ie.SqlAdaperSource Take a Gridview choose - DataSource (ie :- SqlDataAddapter,go through the wizard ).

DataKeyNames="id" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="img12" runat="server" Width="600px" Height="400" ImageUrl='<%# Page.ResolveUrl(string.Format("~/ClientImages/{0}", Eval("image"))) %>' />

</ItemTemplate>
</asp:TemplateField>

</Columns>

</asp:GridView>


## SqlDataSource ##
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:XXXXConnectionStringName %>"
SelectCommand="Stored_Procedure_Name" SelectCommandType="StoredProcedure">
</asp:SqlDataSource

Tuesday, November 15, 2011

Read Excel data & Insert into SQL


Used spread gear DLL
DB  must have  following column   ..I will add later



  public void readExcel(String FilePath, String SheetName)
    {
        string row = "";
        string column = "";
        string transectionocurs = "";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlTransaction myTrans = con.BeginTransaction();
        SqlCommand cmd1 = new SqlCommand("sp_InserXSLData", con);
        cmd1.Transaction = myTrans;
        try
        {

            SpreadsheetGear.IWorkbook oWB;
            SpreadsheetGear.IWorksheet OSHEET;
            SpreadsheetGear.IRange oRng;
            //  DataTable ds = new DataTable();

            oWB = SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(FileUpload1.PostedFile.InputStream);
            SpreadsheetGear.IWorksheet templateWorksheet = oWB.Worksheets[0];
            DataSet ds = oWB.GetDataSet(SpreadsheetGear.Data.GetDataFlags.FormattedText);
     

            bool saveit = true;


            DateTimeFormatInfo info = new System.Globalization.CultureInfo("en-gb").DateTimeFormat;
                                 
            if (ds.Tables[0].Rows.Count > 0)
            {
                if ((ds.Tables[0].Columns["Mobilenumber"].ToString().ToLower() == "mobile") &&
                    (ds.Tables[0].Columns["Name"].ToString().ToLower() == "name") &&
                    (ds.Tables[0].Columns["flightdate"].ToString().ToLower() == "flightdate") &&
                    (ds.Tables[0].Columns["scheduleddeparturetime"].ToString().ToLower() == "departuretime") &&
                    (ds.Tables[0].Columns["Airport"].ToString().ToLower() == "airport") &&
                    (ds.Tables[0].Columns["terminal"].ToString().ToLower() == "terminal"))
                {

                    for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                    {
                     
                        row = j.ToString();
                        DateTime FlightDate = Convert.ToDateTime(ds.Tables[0].Rows[j]["flightdate"],info);

                        objClass = new WisemiserSMS();
                        column = ds.Tables[0].Columns["Mobilenumber"].ToString().ToLower();
                        objClass.PhoneNoxsl = ds.Tables[0].Rows[j]["Mobilenumber"].ToString();
                        column = ds.Tables[0].Columns["Name"].ToString().ToLower();
                        objClass.name = ds.Tables[0].Rows[j]["Name"].ToString();
                        objClass.servertime = System.DateTime.Now;
                        column = ds.Tables[0].Columns["Airport"].ToString().ToLower();
                        objClass.airport = ds.Tables[0].Rows[j]["Airport"].ToString();
                        column = ds.Tables[0].Columns["terminal"].ToString().ToLower();
                        objClass.terminal = ds.Tables[0].Rows[j]["terminal"].ToString();
                        cmd1.CommandType = CommandType.StoredProcedure;
                        cmd1.Parameters.AddWithValue("@phoneno", ds.Tables[0].Rows[j]["Mobilenumber"].ToString());
                        cmd1.Parameters.AddWithValue("@name", ds.Tables[0].Rows[j]["Name"].ToString());
                        column = ds.Tables[0].Columns["flightdate"].ToString().ToLower();
                        cmd1.Parameters.AddWithValue("@flightdate", FlightDate.Month + "/" + FlightDate.Day + "/" + FlightDate.Year);
                        cmd1.Parameters.AddWithValue("@airport", ds.Tables[0].Rows[j]["Airport"].ToString());
                        cmd1.Parameters.AddWithValue("@terminal", ds.Tables[0].Rows[j]["terminal"].ToString());
                        column = ds.Tables[0].Columns["scheduleddeparturetime"].ToString().ToLower();
                        cmd1.Parameters.AddWithValue("@schedularDepartureTime", Convert.ToDateTime(ds.Tables[0].Rows[j]["scheduleddeparturetime"]));
                        cmd1.ExecuteNonQuery();
                        transectionocurs = "y";
                        cmd1.Parameters.Clear();

                    }


                }
                else
                {
                    saveit = false;
                    lblError.Text = "Error:Column name is not correct";

                    if (transectionocurs == "y")
                        myTrans.Rollback();
                    System.IO.File.Delete(filePath);
                }

            }
            else
            {
                saveit = false;
                lblError.Text = "Error:No data found in the file";

                if (transectionocurs == "y")
                    myTrans.Rollback();
                System.IO.File.Delete(filePath);
            }


            if (saveit == true)
            {
                myTrans.Commit();
                lblError.Text = "Data uploaded successfully";
            }
            //con.Close();
            //cmd1.Dispose();

        }
        catch (Exception ex)
        {
            if (row != "" && column != "")
            {
                lblError.Text = "Row  " + (Convert.ToInt32(row) + 1) + " and column " + column + " has wrong data";
                System.IO.File.Delete(filePath);
                if (transectionocurs == "y")
                    myTrans.Rollback();
            }
            else
            {
                lblError.Text = "You have wrong data in excel sheet.Please rectify";
                System.IO.File.Delete(filePath);
                if (transectionocurs == "y")
                    myTrans.Rollback();
            }
        }

    }

Upload files in C#


 protected void btnUpload_Click(object sender, EventArgs e)
    {

        if (FileUpload1.HasFile == true)
        {

            filePath = Server.MapPath("~/FileUpload/" + FileUpload1.FileName);

            string strExension = Path.GetExtension(filePath);
            if (strExension == ".xls")
            {
                FileUpload1.SaveAs(filePath);



                readExcel(filePath, "Source Data");


            }
            else
            {
                lblError.ForeColor = System.Drawing.Color.Red;
                lblError.Text = "Please select a file with .XLS file extension (Excel File).";
            }

Data Access Layer (DAL Example) in ASP.NET (C#)

DAL Example


DAL resides in appcode folder.It is a simple C# class.

Create a new folder name it appcode & now add a new C# class in it & write code for database connectivity.

//Import Required Namespace Here
public class       CALLConnection
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    public WisemiserSMS()
    {

    }
    #region properties

    string _phoneNumber;
    public string PhoneNumber { get { return _phoneNumber; } set { _phoneNumber = value; } }
    int _msgId;
    public int MessageId { get { return _msgId; } set { _msgId = value; } }
    int _userId;
    public int UserId { get { return _userId; } set { _userId = value; } }
    string _messageText;
    public string MessageText { get { return _messageText; } set { _messageText = value; } }
    DateTime _sentTime;
    public DateTime SentTime { get { return _sentTime; } set { _sentTime = value; } }
    string _userName;
    public string UserName { get { return _userName; } set { _userName = value; } }
    string _password;

 
    #endregion

    public void sentSMSFlag()
    {
    openConnection();
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand("sp_smsSentFlag", con);
 
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@id", this.id);
        //cmd.Parameters.AddWithValue("@raiseflag", this.addedtime);

        cmd.ExecuteNonQuery();
        con.Close();
        cmd.Dispose();
    }
}


Now we can call it in our code like this  CALLConnection.sentSMSFlag()  

Monday, October 31, 2011

Upload & save a file to server in C#

Add a asp file upload control to your page

Now add new button  btnsave (save button)
 add this code on btnsave click

    protected void btnsave_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == false)
        {
            label.Text = "Please select a file ";
        }
        else
        {

// Note  UploadedFiles is a folder Name in the Project.

            string filePath = Server.MapPath("~/UploadedFiles/" + FileUpload1.FileName);
            FileUpload1.SaveAs(filePath);
            Label2.Text = "File Uploaded succesfully";
        }




This is a very basic File uploading in C# .Also Please take care of security aspect,max file size,delete file after use,same names etc parameters into account .


Thanks





Monday, August 8, 2011

Custom Regular Expression for Integer & decimal validation

It will allow integer & decimal values (Eg- 19,.50,166666.34,)

\d{1,16}(,\d{16})*(\.\d\d)?|\.\d\d