Monday, 31 December 2012

Json Function





Convert List<Employee> into Json String:
string jsonResult = JavaScriptConvert.SerializeObject(lst);

Convert Json String into List<Employee>:
emp = JavaScriptConvert.DeserializeObject<List<Employee>>(jsonService.getJsonData());



For JavaScriptConvert  you must have dll 
Please click on Download.

Send Mail


WebConfig:

<add key="SMTPHost" value="127.0.0.1" />
<add key="SMTPPort" value="25" />
Code Behind :
string mailTo =”To”;
string mailFrom = “From”;
string Sub = “Subject”;
string strBody =”Body part”;
SendMail(mailTo, mailFrom, string.Empty, string.Empty, strBody, Sub, null);


public static void SendMail(string ToMail, string FromMail, string Cc, string Bcc, string Body, string Subject, ArrayList AttachmentFiles)
        {
            SmtpClient smtp = new SmtpClient();
            MailMessage mailmsg = new MailMessage();

            mailmsg.From = new MailAddress(FromMail);
            mailmsg.To.Add(ToMail);

            if (!string.IsNullOrEmpty(Cc))
                mailmsg.CC.Add(Cc);

            if (!string.IsNullOrEmpty(Bcc))
                mailmsg.Bcc.Add(Bcc);

            mailmsg.Body = Body;
            mailmsg.Subject = Subject;
            mailmsg.IsBodyHtml = true;

            mailmsg.Priority = MailPriority.High;

            smtp.Host = Convert.ToString(ConfigurationManager.AppSettings["SMTPHost"]);
            smtp.Port = Convert.ToInt32(Convert.ToString(ConfigurationManager.AppSettings["SMTPPort"]));

            if (AttachmentFiles != null)
            {
                for (int counter = 0; counter < AttachmentFiles.Count; counter++)
                {
                    if (System.IO.File.Exists(Convert.ToString(AttachmentFiles[counter])))
                    {
                        System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(Convert.ToString(AttachmentFiles[counter]));
                        mailmsg.Attachments.Add(attach);
                    }
                }
            }

            try
            {
                smtp.Send(mailmsg);
                mailmsg.Dispose();
            }
            catch { }
        }


Note: 
Must add SMTPHost Ip Address into IIS




Sunday, 30 December 2012

crystal reports using stored procedures in asp.net

crystal reports using stored procedures in asp.net

 




ReportDocument document = new ReportDocument();
        document.Load(this.Page.Server.MapPath("~/CRY/crTest.rpt"));
        string str = ConfigurationManager.AppSettings["ConnectionString"];
        string server = str.Substring(str.IndexOf("=") + 1, str.IndexOf(";") - (str.IndexOf("=") + 1));
        str = str.Substring(str.IndexOf(";") + 1);
        string database = str.Substring(str.IndexOf("=") + 1, str.IndexOf(";") - (str.IndexOf("=") + 1));
        str = str.Substring(str.IndexOf(";") + 1);
        string user = str.Substring(str.IndexOf("=") + 1, str.IndexOf(";") - (str.IndexOf("=") + 1));
        str = str.Substring(str.IndexOf(";") + 1);
        string password = str.Substring(str.IndexOf("=") + 1);
        document.DataSourceConnections.Clear();
        document.DataSourceConnections[0].SetConnection(server, database, user, password);
        new TableLogOnInfos();
        TableLogOnInfo logonInfo = new TableLogOnInfo();
        ConnectionInfo info2 = new ConnectionInfo();
        info2.ServerName = server;
        info2.DatabaseName = database;
        info2.UserID = user;
        info2.Password = password;
        foreach (CrystalDecisions.CrystalReports.Engine.Table table in document.Database.Tables)
        {
            logonInfo = table.LogOnInfo;
            logonInfo.ConnectionInfo = info2;
            table.ApplyLogOnInfo(logonInfo);
        }
        document.SetDatabaseLogon(user, password, server, database);
        document.Refresh();
        for (int i = 0; i < document.ParameterFields.Count; i++)
        {
            document.SetParameterValue(document.ParameterFields[i].Name, 1);
        }
        this.CrystalReportViewer1.ReportSource = document;

Date Picker control for ASP.net using Dropdown control of DD,MM,YYYY

Date Picker control for ASP.net using Dropdown control of DD,MM,YYYY


.aspx File


<asp:DropDownList ID="ddlDay" Width="60px" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="ddlMonth" Width="120px" runat="server">
</asp:DropDownList>
<asp:DropDownList ID="ddlYear" Width="80px" runat="server">
</asp:DropDownList>
&nbsp;
<%--<asp:Image ID="imgCalendar" runat="server" ImageUrl="~/Images/calendar.gif"
    EnableViewState="False"></asp:Image>--%>
<asp:Label ID="lblError" runat="server" CssClass="error" Visible="False" EnableViewState="False"><BR />The date is not valid.</asp:Label>




.cs File



public partial class DateTimePicker : System.Web.UI.UserControl
{
// Fields
private DateTime _dateTime;
private int _endYear = -1;
private bool _isValid;
private int _startYear = 0x7d0;

// Methods
private void BuildDropDownLists()
{
this.ddlDay.Items.Clear();
this.ddlMonth.Items.Clear();
this.ddlYear.Items.Clear();
for (int i = 1; i <= 0x1f; i++)
{
this.ddlDay.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
for (int j = 1; j <= 12; j++)
{
DateTime time = new DateTime(0x7d0, j, 1);
this.ddlMonth.Items.Add(new ListItem(time.ToString("MMMM"), j.ToString()));
}
for (int k = this._startYear; k <= this.EndYear; k++)
{
this.ddlYear.Items.Add(new ListItem(k.ToString(), k.ToString()));
}
}

public override void DataBind()
{
base.DataBind();
this.ddlDay.SelectedIndex = this._dateTime.Day - 1;
this.ddlMonth.SelectedIndex = this._dateTime.Month - 1;
if ((this._dateTime.Year >= this._startYear) && (this._dateTime.Year <= this.EndYear))
{
this.ddlYear.SelectedIndex = this._dateTime.Year - this._startYear;
}
else
{
this.ddlYear.SelectedIndex = 0;
}
}

private int GetEndYear()
{
if (this._endYear != -1)
{
return this._endYear;
}
return DateTime.Now.Year;
}

private void InitializeComponent()
{
}

protected override void OnInit(EventArgs e)
{
this.InitializeComponent();
base.OnInit(e);
this.BuildDropDownLists();
}

protected void Page_Load(object sender, EventArgs e)
{
//this.imgCalendar.Attributes["onclick"] = "DisplayDatePicker('" + this.ddlDay.UniqueID + "','" + this.ddlMonth.UniqueID + "','" + this.ddlYear.UniqueID + "','" + this._startYear.ToString() + "');";
//this.imgCalendar.Attributes["style"] = "cursor: pointer;";
if (!this.Page.IsClientScriptBlockRegistered("DateTimePicker"))
{
this.Page.RegisterClientScriptBlock("DateTimePicker", "");
}
if (!base.IsPostBack)
{
this.DataBind();
}
else
{
this._startYear = Convert.ToInt32(this.ddlYear.Items[0].Value);
this._endYear = Convert.ToInt32(this.ddlYear.Items[this.ddlYear.Items.Count - 1].Value);
int day = Convert.ToInt32(this.ddlDay.SelectedItem.Value);
int month = Convert.ToInt32(this.ddlMonth.SelectedItem.Value);
int year = Convert.ToInt32(this.ddlYear.SelectedItem.Value);
try
{
this._dateTime = new DateTime(year, month, day);
if ((year >= this._startYear) && (year <= this.EndYear))
{
this._isValid = true;
}
else
{
this._isValid = false;
}
}
catch (ArgumentOutOfRangeException)
{
this._isValid = false;
}
this.lblError.Visible = !this._isValid;
}
}

// Properties
public DateTime DateTime
{
get
{
return this._dateTime;
}
set
{
this._dateTime = value;
}
}

public int EndYear
{
get
{
return this.GetEndYear();
}
set
{
this._endYear = value;
this.BuildDropDownLists();
}
}

public bool IsValid
{
get
{
return this._isValid;
}
}

public int StartYear
{
get
{
return this._startYear;
}
set
{
this._startYear = value;
this.BuildDropDownLists();
}
}
}

Simple Cursor Example in SQL

DECLARE @Pram int

    DECLARE aCursor CURSOR
    FOR
        SELECT
            *
           
        FROM
            TableName
           
    OPEN aCursor
   
           
    FETCH NEXT FROM aCursor INTO
        @Pram
       
    WHILE @@FETCH_STATUS = 0
        BEGIN
            --'what you want to do hear'
            FETCH NEXT FROM aCursor INTO
                @Pram
        END
    CLOSE aCursor
    DEALLOCATE aCursor

Cookies example in ASP.net

Add Value in Cookies

 Response.Cookies["Cookies"].Value = txtEmailID.Text;
Response.Cookies["Cookies"].Expires = DateTime.Now.AddMonths(2);

Get Value From Cookies

Request.Cookies["Cookies"]

Clear Cookies

Response.Cookies.Clear();

File Upload with Update Panel

ASPX Page
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:PostBackTrigger ControlID="Button2" />               
            </Triggers>
            <ContentTemplate>
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <asp:FileUpload ID="fupLogo" runat="server" Visible="False"></asp:FileUpload>
                <asp:Button ID="Button2" runat="server" Text="Upload" OnClick="Button2_Click" Visible="False" />
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="show Uploader " />
            </ContentTemplate>
        </asp:UpdatePanel>
Code Behind

protected void Button2_Click(object sender, EventArgs e)
    {
        if (fupLogo.HasFile)
        {
            string fileFormat = fupLogo.PostedFile.ContentType;
            Label1.Text = fupLogo.PostedFile.ContentType;
            if (string.Compare(fileFormat, "image/jpeg", true) == 0 ||
            string.Compare(fileFormat, "image/png", true) == 0 ||
            string.Compare(fileFormat, "image/gif", true) == 0)
            {
                Label1.Text += "file format supported<br/>";
            }
            else
            {
                Label1.Text += "file format not supported<br/>";
            }
        }
        else
        {
            Label1.Text += "file not exist<br/>";
        }
    }