Friday, September 30, 2011

Monday, September 19, 2011

Convert html to pdf using i text sharp

First u download the i text sharp dll from internet

and then





namespace

using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.Collections;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;



//------- Function for generate pdf ---
    private void newpdf()
    {
        Document doc = new Document(PageSize.A4);
        DataTable dtPDFfile = new DataTable();
        DataTable dt = new DataTable();

            dt.Columns.Add("link", typeof(System.String));
            dt.Columns.Add("Property_name", typeof(System.String));
            dt.Columns.Add("Street_address", typeof(System.String));
            dt.Columns.Add("walia", typeof(System.String));




            for (Int32 i = 0; i < 30; i++)
            {

                DataRow dr = dt.NewRow();
                dr["link"] = "text5";
                dr["Property_name"] = "walia";
                dr["Street_address"] = "sachin";
                dr["walia"] = "sachin";
                dt.Rows.Add(dr);

            }

        //PdfWriter.GetInstance(document, new FileStream(Server.MapPath(".") + "/pdf/test" + guid + ".pdf", FileMode.Create));
        // string strPath = ConfigurationManager.AppSettings["Pdfpath"].ToString();



            string strPath = Server.MapPath("test.pdf");
        dtPDFfile = dt;

        if (dtPDFfile.Rows.Count > 0)
        {
            CreatePdfReport(dtPDFfile, "", strPath, "sachin");
        }
    }
 //---------------------
 public void CreatePdfReport(DataTable dt, string headerText, string filepath, string filename)
    {

        HttpContext.Current.Response.ContentType = "Application/pdf";
        Document document = new Document(PageSize.A4.Rotate(), 50, 50, 50, 50);
        int numColumns = 0;
        if (dt.Columns.Count > 0)
        {
            numColumns = dt.Columns.Count;
        }
        PdfPTable datatable = new PdfPTable(numColumns);
        //string strPathImage = DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() + "Image." + strExtension;
        // set image path for header image 
        //PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath
        //(Environment.SpecialFolder.Desktop) + "\\TimeScheduler"+DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString() + "" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + "" + DateTime.Now.Second.ToString() +".pdf", FileMode.Create));
        string imagepath = Server.MapPath("logo.gif");
        PdfWriter.GetInstance(document, new FileStream(filepath + "timescheduler.pdf", FileMode.Create, FileAccess.ReadWrite));
        //PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));
        document.Open();
        // set header image
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
        image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
        //PdfPCell cell = new PdfPCell(image);
        //image.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
        // set spacing betwwen table and header image         
        image.SpacingAfter = 20f;
        //image.SpacingBefore = 10f;
        image.ScalePercent(80f);
        document.Add(image);
        Phrase headerPhrase = new Phrase(headerText, FontFactory.GetFont("Verdana", 28));
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        header.Border = Rectangle.NO_BORDER;
        header.Alignment = Element.ALIGN_CENTER;
        document.Header = header;
        document.Add(headerPhrase);
        HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
        footer.Border = Rectangle.NO_BORDER;
        footer.Alignment = Element.ALIGN_CENTER;
        document.Footer = footer;
        float[] columnWidths = { 18, 40, 40, 40 };

        datatable.SetWidths(columnWidths);
        datatable.DefaultCell.Padding = 4;
        datatable.WidthPercentage = 100; // percentage
        datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
        datatable.DefaultCell.BorderWidth = 1;
        datatable.DefaultCell.GrayFill = 0.7f;
        datatable.SpacingBefore = 50f;



        foreach (DataColumn column in dt.Columns)
        {
            string columnName = column.ColumnName;
            Phrase phrase = new Phrase(columnName, FontFactory.GetFont("Tahoma", 20, Font.BOLD));
            datatable.DefaultCell.GrayFill = 0.9f;
            datatable.AddCell(phrase);
        }

        datatable.HeaderRows = 1;

        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn column in dt.Columns)
            {
                string columnName = column.ColumnName;
                Phrase phrase = new Phrase(row[columnName].ToString(), FontFactory.GetFont("Arial", 18));
                datatable.DefaultCell.GrayFill = 10f;
                datatable.AddCell(phrase);
            }

        }
        document.Add(datatable);
        document.Close();
        HttpContext.Current.Response.ContentType = "Application/pdf";
        HttpContext.Current.Response.WriteFile(filepath + "timescheduler.pdf");
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");
        HttpContext.Current.Response.TransmitFile(filepath + "timescheduler.pdf");
        HttpContext.Current.Response.End();

    }



Friday, September 16, 2011

Jquery get data by partial postback

html code : Please make a aspx page and add this code in html side..

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src ="jquery-1.4.2.min.js" ></script>

<script language="javascript" type="text/javascript">

    window.onload = abc;

  //  $(document).ready(function ()
    function abc() {
        $.ajax({
            type: "GET",
            url: "/WebSite3/Default.aspx",
            data: "mail=1&metro=2",
            success: function (data) {
                document.getElementById('x').innerHTML = data;
            }

        });

        setTimeout("abc()", 1000);
    };

</script>

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <span id="x">
    </span>
    </div>
    </form>
</body>
</html>

///---
Now add a page  Default.aspx and write the below code in cs page  in page load..
     protected string str = "";
        Random ran = new Random();
        str = ran.Next(10, 2000).ToString();

//-----
Now print this function in html side

<%= str %>

Happy learing g.....

Thursday, September 8, 2011

MD5 Sqr server password encrypt

CREATE FUNCTION [dbo].[fn_MD5]
(
    @string AS VARCHAR(MAX),
    @chars AS INT
)
RETURNS NVARCHAR(32)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @md5 NVARCHAR(32)

    SELECT @md5 = SUBSTRING(CAST(master.dbo.fn_varbintohexstr(HashBytes('MD5',@string )) AS NVARCHAR(32)),3,@chars )

    -- Return the result of the function
    RETURN @md5
END

select dbo.fn_MD5('hello', 32) as md5
select dbo.fn_MD5('rakeshwalia', 40) as md5
select dbo.fn_MD5('sachinrameshtendulkarserttuiklolioooooo', 40) as md5

SQL Script to check what was changed in database after 9PM Last night

SELECT name,
 TYPE,
 type_desc,
 create_date,
 modify_date
FROM sys.objects
WHERE TYPE IN ('U','V','PK','F','D','P')
AND modify_date >= Dateadd(HOUR,21,Cast((Cast(Getdate() - 1 AS VARCHAR(12))) AS SMALLDATETIME))
ORDER BY modify_date

--U - Table
--V - View
--PK - Primary Key
--F - Foreign Key
--D - Default Constraint
--P - Procedure

Display multiple rows values as single row value like comma separtae

SET NOCOUNT ON 
DECLARE @listValues VARCHAR(8000) 
DECLARE @delimeter VARCHAR(3) 
SET @delimeter = ' ; '

CREATE TABLE #Table1 (FirstName varchar(10)) 
INSERT #Table1 VALUES ('Michiel') 
INSERT #Table1 VALUES ('John') 
INSERT #Table1 VALUES ('Smith') 
INSERT #Table1 VALUES ('Peter') 
 select * from #Table1
SELECT @listValues = ISNULL(@listValues + @delimeter + CAST(FirstName AS VARCHAR(8000)), 
        CAST(FirstName AS VARCHAR(8000)) 
    ) 
    FROM #Table1
    ORDER BY FirstName 

DROP TABLE #Table1
SELECT list = @listValues

Count all row in all table RowCount

 Run this script to get the row counts of all tables.
 

SELECT o.name AS "Table Name", i.rowcnt AS "Row Count"
FROM sysobjects o, sysindexes i
WHERE i.id = o.id AND indid IN(0,1)
AND xtype = 'u'
AND o.name <> 'sysdiagrams'
ORDER BY i.rowcnt DESC

Column Headers To Row Headers in sql server

--Create Dummy test table and insert data
Declare @t table(num int, descr varchar(20), [value] decimal(9,2), date smalldatetime)
insert into @t
values(101,'Blue Skirt', '20.00', '01/01/2008')
insert into @t
values(102,'white socks', '5.000','12/03/2009')
insert into @t
values(110,'blue shirt', '10.00','01/12/2010')
insert into @t
values(200,'Red Tie', '15.99','05/03/2010')
insert into @t
values(350,'Black Belt ', '100','02/09/2011')
--Test Results
Select num, descr, [value] from @t
--Declare our Variable for the first Column Header and set date as the header Column
Declare @s varchar(8000)
Select @s=COALESCE(@s+''',''','')+cast(num as varchar(10)) +'''as'''+ convert(varchar(10),date,3) from @t
--Declare our second Row Header data
declare @v varchar(8000)
select @v=COALESCE(@v+''',''','')+ descr from @t
--Declare our Third Row Header data
declare @l varchar(8000)
select @l=COALESCE(@l+''',''','')+ cast([value] as varchar(10)) from @t
--Execute all variables as well as inserting our Coulumn header
Exec('Select ''ID'' as ''Name'','''+ @s + ''' union all select ''Item'','''+ @v + ''' union all select ''Price'',''' +@l + '''' )


Fo Find exact age in sql server




/*----------------------------------------------------------------------------------------------------------------------------
  Author     :-    ANAND BABU UCHAGAWKAR
  Purpose    :-    To find the datediff/age in text format (eg. 1 year(s), 10 month(s), 10 day(s)).               
  DATE        :-    30-Aug-2011
  DATABASE    :-     SQL

----------------------------------------------------------------------------------------------------------------------------*/
IF (Select COUNT(*) From Sysobjects Where [name] like 'FN_GETDATEDIFFTEXT') > 0
BEGIN
    DROP FUNCTION FN_GETDATEDIFFTEXT
END
GO
CREATE FUNCTION FN_GETDATEDIFFTEXT(@FromDate DateTime, @ToDate DateTime)
RETURNS NVARCHAR(50)
AS
BEGIN   

    Declare @daysDiff Int
    Declare @monthDiff Int
    Declare @yearDiff Int

    --Select @daysDiff = DATEDIFF(DAY, @FromDate, @ToDate)
    Set @monthDiff = ABS(DATEDIFF(MONTH, @FromDate, @ToDate)%12)
    Set @yearDiff = ABS(DATEDIFF(YYYY, @FromDate, @ToDate))

    -- If the From date month is greater than the month of the To date and the year difference is greater than zero
    -- then the year should the deducted by one
    IF DATEPART(MONTH,@FromDate) > DATEPART(MONTH,@ToDate) AND @yearDiff > 0
    BEGIN
        Set @yearDiff = @yearDiff - 1
    END

    IF DATEPART(DAY,@FromDate) > DATEPART(DAY, @ToDate)
    Begin
        --Get last date of the month of the FromDate
        Declare @lastDateOfMonth DateTime = DATEADD(MONTH, 1, @FromDate)   
        Set @lastDateOfMonth = '01-' + DATENAME(MONTH,@lastDateOfMonth) + '-'+DATENAME(YEAR,@lastDateOfMonth)
        Set @lastDateOfMonth = DATEADD(DAY, -1, @lastDateOfMonth)
       
        Set @daysDiff = DATEDIFF(DAY, @FromDate, @lastDateOfMonth)
        Set @daysDiff = @daysDiff + DATEPART(DAY, @ToDate)
        Set @monthDiff = @monthDiff - 1
    End
    ELSE
    BEGIN
        Set @daysDiff = DATEPART(DAY, @ToDate) - DATEPART(DAY, @FromDate)
    END

    -- Select @yearDiff Yr, @monthDiff Mn, @daysDiff Dy
    RETURN
        CAST(@yearDiff as nvarchar) + ' year(s), ' +
        CAST(@monthDiff as  nvarchar) + ' month(s), ' +
        CAST(@daysDiff as nvarchar) + ' day(s)'
END
GO

-- Select DBO.FN_GETDATEDIFFTEXT('30-Dec-2010', '31-Jan-2011')
-- Select DBO.FN_GETDATEDIFFTEXT('01-Jan-1990', Getdate())

Select DBO.FN_GETDATEDIFFTEXT('24-feb-1983', Getdate())

Tuesday, September 6, 2011

Silverlight pop up window [4.0]

Please add this code on click event :

 private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            Popup p;
            // Create a popup.
            p = new Popup();

            // Set the Child property of Popup to an instance of MyControl.
            p.Child = new Views.SilverlightControl1();

            // Set where the popup will show up on the screen.
            p.VerticalOffset = 600;
            p.HorizontalOffset = 600;

            // Open the popup.
            p.IsOpen = true;


            //MessageBox.Show(dataGrid1.CurrentColumn.Header.ToString() + ": " +
            //        ((TextBlock)dataGrid1.CurrentColumn.GetCellContent(dataGrid1.SelectedItem)).Text);

        }

//------------------------------
  private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Collapsed;
        }