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();
        }
    }


show pop up JavaScript message through C#

Add this following script in html code :



<script>
        function ShowMessage() {
            alert('Thank you for your submission!  To complete, please continue with PayPal transaction');
            window.location.href = 'BuyNow.aspx';
        }
   
    </script>


C# Code :-

ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "ShowMessage()", true);


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

Monday, December 19, 2011

Checkbox Validation in ASP.NET

Validation of check box is little bit tricky  but you can validate with Java Script

Add this script in the page.


<script type="text/javascript">
    function validateCheckBox(source,args)
    {
        var cb=document.getElementById("Privacy1");
        if(!cb.checked)
         args.IsValid=false;
    }
    </script>
add a Checkbox Control

<asp:CheckBox ID="Privacy1" runat="server"></asp:CheckBox>
Now you need to add a custom Validator:-

  <asp:CustomValidator ID="CustomValidator1" runat="server" 
            ErrorMessage="CustomValidator" 
            ValidateEmptyText="True" ClientValidationFunction="validateCheckBox"></asp:CustomValidator>



Tuesday, December 6, 2011

How to make free trials last FOREVER!!!


How to make free trials last FOREVER!!!

Difficulty : Piece of Cake 

You can make any software work for life time.          
        
 I am taking example of “ADOBE FLASH CS5 PROFESSIONAL “  Trial version as an example


Here we go  ->
  • First download any trial software(Flash CS5)
  • Type       runasdate        in Google          
  • Open 1st displayed page  most probably      nirsoft.
  • Download the software which is free.
  • Extract it  & run .
  • Then the first option will be application to run .Select desired(CS5)  application’s exe file's path.
  • Now,set a date/time  Make it sure it must be in the trial period. (you can set same date when application is installed or next day’s  date)
  • Check both  radio button, (move the time forward a/c to the real time  & immediate mode)
  • Create a new desktop shortcut   with desired name (eg:- RippedCS5 ).
  • Click   RUN  
  • That’s it
  • This procedure is  required only for 1st time , make sure to make a shortcut & only use that shortcut  on desktop. Configure every trial software with this utility & create short cut then u don’t need to run it again-2                       


                                                                                                   ENJOY

Monday, December 5, 2011

Test Stored Procedure Manually in MS SQL

Write a stored procedure  eg :  sp_Insert_Client_info

Now on New Query window  execut it with stored procedure's required value,

 like this  sp_Insert_Client_info'Age','India','phone',10101

Above sp will take 3 arguments/values :

  1. Age  or text value
  2. India or Text vale
  3. 10101  or integer value


Another example:

 sp_Insert_Client_Info'Jhon','sharma',87


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();
            }
        }

    }