Popular Posts

Dec 18, 2013

Send Auto Notification Using Windows service (asp.net)



-Open visual studio.
- Go to file->new->project
-Select windows service




















-right click on Service1.cs select properties
-In the properties window click on add Installer








-Right click on serviceInstaller1, select propertics
-Change DisplayName, ServiceName to SeraMailService
-StartType to Automatic

-Right click on serviceProcessInstaller1 then select Propertics
-change Account to LocalSystem
















-Right click on Service1.cs Design select ViewCode.
-In the OnStart method type the following code…


public void GetMail(object sender, System.Timers.ElapsedEventArgs args)
        {
            NetworkCredential cred = new NetworkCredential("it.system@lafarge.com", "Password");
            MailMessage msg = new MailMessage();
            msg.To.Add("jubayer@apsissolutions.com");
            msg.Subject = "Welcome JUBAYER";

            msg.Body = "You Have Successfully Entered to Sera's World!!!";
            msg.From = new MailAddress("jubayer@apsissolutions.com"); // Your Email Id
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            SmtpClient client1 = new SmtpClient("smtp.mail.yahoo.com", 465);
            client.Credentials = cred;
            client.EnableSsl = true;
            client.Send(msg);
        }

To keep the method running we add time interval

Add this line before onload method
System.Timers.Timer createOrderTimer;

In the onStart method type this code

createOrderTimer = new System.Timers.Timer();
            createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetMail);
            createOrderTimer.Interval = 500;
            createOrderTimer.Enabled = true;
            createOrderTimer.AutoReset = true;
            createOrderTimer.Start();


Full code:

System.Timers.Timer createOrderTimer;

        public Service1()
        {
            InitializeComponent();
        }


        protected override void OnStart(string[] args)
        {
            createOrderTimer = new System.Timers.Timer();
            createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetMail);
            createOrderTimer.Interval = 500;
            createOrderTimer.Enabled = true;
            createOrderTimer.AutoReset = true;
            createOrderTimer.Start();          
        }



        public void GetMail(object sender, System.Timers.ElapsedEventArgs args)
        {
            NetworkCredential cred = new NetworkCredential("it.system@lafarge.com", "Password");
            MailMessage msg = new MailMessage();
            msg.To.Add("jubayer@apsissolutions.com");
            msg.Subject = "Welcome JUBAYER";

            msg.Body = "You Have Successfully Entered to Sera's World!!!";
            msg.From = new MailAddress("jubayer@apsissolutions.com"); // Your Email Id
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            SmtpClient client1 = new SmtpClient("smtp.mail.yahoo.com", 465);
            client.Credentials = cred;
            client.EnableSsl = true;
            client.Send(msg);
        }


Now build the service using ctrl+shift+b


In the command mode type the code to install InstallUtil.exe

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

To install the service use the command

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>InstallUtil.exe "C:\Documents and
Settings\Administrator\My Documents\Visual Studio 2008\Projects\SeraMailService\
SeraMailService\bin\Debug\SeraMailService.exe"


Type services.msc in the run windiw and enter to see all services
Right click on the service then run the service.


To uninstall the service use this code
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>InstallUtil.exe /u "C:\Documents and
Settings\Administrator\My Documents\Visual Studio 2008\Projects\SeraMailService\
SeraMailService\bin\Debug\SeraMailService.exe"




Nov 17, 2013

Auto Complete TextBox in asp.net



In .aspx file add these line to head section:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "NewEmployee.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtEmail').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
}

</script>

In page body:

<input type="text" id="txtEmail" class="autosuggest" />


In .cs file Add these lines:

[WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        string strCon = ConfigurationManager.ConnectionStrings["IRTConnectionString"].ConnectionString;
        List<string> result = new List<string>();
        using (SqlConnection con = new SqlConnection(strCon))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT username FROM t_Employee WHERE username LIKE '%'+@SearchText+'%'", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@SearchText", username);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["username"].ToString());
                }
                return result;
            }
        }
    }


You need to add this reference 'System.Web.Services'.





Dynamic Checkbox in ASP.NET (Return checkbox value in comma seperated format)




In .aspx File:

<asp:Label ID="lblSelectedValues" runat="server" Text="" style="color: #FF3300"/>

<asp:CheckBoxList ID="AccCheckBoxList" runat="server" RepeatColumns="2" Height="55px" Width="239px" RepeatLayout="Table" BorderColor="Red" BorderStyle="Dotted" BorderWidth="4px">
           </asp:CheckBoxList>


<asp:CheckBoxList ID="AccCheckBoxList" runat="server" RepeatColumns="2" Height="55px" Width="239px" RepeatLayout="Table" BorderColor="Red" BorderStyle="Dotted" BorderWidth="4px">

           </asp:CheckBoxList>



In .aspx.cs File:

private void GetAccListCheckBox()
    {
        DataTable dt = new DataTable();
        dt = empManagerObj.GetAccList();
        AccCheckBoxList.DataSource = dt;
        AccCheckBoxList.DataTextField = "accessories_name";
        AccCheckBoxList.DataValueField = "id";
        AccCheckBoxList.DataBind();
    }


    protected void BtnGetSelectedValues_Click(object sender, EventArgs e)
    {
        if (AccCheckBoxList.SelectedIndex != -1)
        {
            lblSelectedValues.Text = "Selected values are = " + GetCheckBoxListSelections();
        }
        else
        {
            lblSelectedValues.Text = "Please select any course";
        }
    }

    private string GetCheckBoxListSelections()
    {
        string[] cblItems;
        ArrayList cblSelections = new ArrayList();
        foreach (ListItem item in AccCheckBoxList.Items)
        {
            if (item.Selected)
            {
                cblSelections.Add(item.Value);
            }
        }

        cblItems = (string[])cblSelections.ToArray(typeof(string));
        return string.Join(",", cblItems);
    }

    protected void btnClearSelection_Click(object sender, EventArgs e)
    {
        AccCheckBoxList.ClearSelection();
        lblSelectedValues.Text = string.Empty;
    }



Oct 22, 2013

Exporting to Excel in Crystal Reports .NET



Export crystal report to excel in asp.net 

ReportDocument crystalReport;

protected void Page_Load(object sender, EventArgs e)
    {
       
        crystalReport = new ReportDocument();
        crystalReport.Load(Server.MapPath("GenReportMaster.rpt"));
       
        //Set DataBase Login Info
        crystalReport.SetDatabaseLogon("sa", "Nopass123", @"BD-DAC-014", "lamolinsDB");
        string year = (Request.QueryString["year"] != "") ? Request.QueryString["year"] : "";
        string month = (Request.QueryString["month"] != "") ? Request.QueryString["month"] : "";
        string zoneString = Request.QueryString["zone"];
        string zone = (zoneString.Equals("All")) ? "" : zoneString;
        string branchString = Request.QueryString["branch"];
        string branch = (branchString.Equals("All")) ? "" : branchString;
        string brand = (Request.QueryString["brand"]!= "") ? Request.QueryString["brand"] : "";




        crystalReport.SetParameterValue("@month", month);
        crystalReport.SetParameterValue("@year", year);
        crystalReport.SetParameterValue("@zone", zone);
        crystalReport.SetParameterValue("@branch", branch);
        crystalReport.SetParameterValue("@brand", brand);
        CwrVatCrystalReportViewer.Visible = true;
        CwrVatCrystalReportViewer.DisplayGroupTree = false;
        CwrVatCrystalReportViewer.HasPageNavigationButtons = true;
        CwrVatCrystalReportViewer.HasCrystalLogo = false;
        CwrVatCrystalReportViewer.HasDrillUpButton = false;
        CwrVatCrystalReportViewer.HasSearchButton = false;
        CwrVatCrystalReportViewer.HasViewList = false;
        CwrVatCrystalReportViewer.HasToggleGroupTreeButton = false;
        CwrVatCrystalReportViewer.HasZoomFactorList = false;
        CwrVatCrystalReportViewer.ToolbarStyle.Width = new Unit("750px");


        CwrVatCrystalReportViewer.ReportSource = crystalReport;
       
    }



Convert to excel:

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ExportOptions CrExportOptions;

            DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
            ExcelFormatOptions CrFormatTypeOptions = new ExcelFormatOptions();
            CrDiskFileDestinationOptions.DiskFileName = "c:\\report.xls";
            CrExportOptions = crystalReport.ExportOptions;
            CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
            CrExportOptions.ExportFormatType = ExportFormatType.Excel;
            CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
            CrExportOptions.FormatOptions = CrFormatTypeOptions;
            crystalReport.Export();
            messageLabel.Text = "Download excel successful...";
        }
        catch (Exception ex)
        {
            messageLabel.Text = "Download excel failed..."+ex.ToString();
        }

    }



Prevent websites from injection in asp.net






string queryStr = "select email, fullname, from t_employee where username = user_name ='" + username + "' and user_date between '" + startdate + "' and '" + enddate + "'";
 
To prevent from query injection we can change it by using stored procedures or 
parameterised TSQL
 

string queryStr = "select email, fullname from t_employee where user_name = @USER and user_date between @startdate and @enddate'";

cmd.Parameters.Add("@USER", SqlDbType.NVarChar, 100);  -- Assuming type and size
cmd.Parameters["@USER"].Value = username
cmd.Parameters.Add("@startdate ", SqlDbType.DateTime);
cmd.Parameters["@startdate "].Value = startdate ;
cmd.Parameters.Add("@enddate", SqlDbType.DateTime);
cmd.Parameters["@enddate"].Value = enddate;