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

Friday, July 20, 2012

“Server.Transfer()” vs “Response.Redirect()”

Both “Server.Transfer()” and “Response.Redirect()” are used to transfer a user from one page to another page. Logically both methods are used for the same purpose but still there are some technical differences between both which we need to understand.

The basic difference between them is the way they communicate. Response.Redirect() first sends request for new page to the browser, then browser sends that request to the web-server, and after that your page changes. But Server.Transfer() directly communicate with the server to change the page hence it saves an extra  round-trip (to the browser) in the whole process.

Now the question arises which to use and when to use?

Response.Redirect() should be used when:
  •  we want to redirect the request to some plain HTML pages on our server or to some other web server
  •  we don't care about causing additional roundtrips to the server on each request
  • we do not need to preserve Query String and Form Variables from the original request
  • we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if it’s necessary)

Server.Transfer() should be used when:
  • we want to transfer current page request to another .aspx page on the same server
  • we want to preserve server resources and avoid the unnecessary roundtrips to the server
  • we want to preserve Query String and Form Variables (optionally)
  • we don't need to show the real URL where we redirected the request in the users Web Browser

Friday, May 11, 2012

Cool Progress Bar in C#,Asp.net


 This example shows you how to display a interactive progress bar while work is in progress.For doing this you need a gif image file which gives a good look for progress.
Like this one :
Then You must have an update panel in web form.Now implement the code given below.You can change image and text as per your need.

<asp:UpdateProgress ID="UPdtProgress" runat="server"
                   AssociatedUpdatePanelID="upTakeAttendance">
        <ProgressTemplate>
                <img ID="imgProgress" runat="server" alt="Work is in Progress" 
                           src="~/PayRoll/images/progressbar.gif" height="17" width="100" /><br />
                 <span style="color: #FF0000;  font-size: small;">  Please Wait</span>
          </ProgressTemplate>
 </asp:UpdateProgress>

Output will look like this -:


Tuesday, May 8, 2012

Open doc,txt or pdf files in C#

This example shows you how to open any doc,txt or pdf file which is saved in any specified location.In this example I m using a GridView which contains a template field which holds FileName.

<asp:TemplateField HeaderText="Application Name" SortExpression="ApplicationName">
       <ItemTemplate>
                       <asp:LinkButton ID="lbOpenApplication" runat="server" Text='<%# Bind("ApplicationName") %>'  CommandArgument='<%# Bind("ApplicationName") %>' CommandName="ViewApplication"></asp:LinkButton>
       </ItemTemplate>
</asp:TemplateField>

In Gridview's RowCommand event we have to write code snippet given below.

protected void gvViewLeave_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ViewApplication")
        {
            string filename = e.CommandArgument.ToString();
            string path = Server.MapPath("~/PayRoll/Applications/");
            System.Diagnostics.Process.Start(path + filename);
        }
    }

Friday, April 20, 2012

Send GridView in Mail in asp.net,C#

This example makes u enable to understand how to email server controls information like Gridview as it is.
Now I am considering that we have a web form which contains a GridView (containing Data) and a button
which will be used to send email.

At first include these namespaces to your code behind.

using System.Net.Mail;
using System.Text;
using System.IO;

Now in Button Click event write this code :


protected void ibMail_Click(object sender, ImageClickEventArgs e)
    {
        string to = "anukana@symtechindia.net";
        string From = "mafire5@gmail.com";
        string subject = "Balance Detail";
        string Body = "Dear sir ,<br> Plz Check d Attachment <br><br>";
        Body += GridViewToHtml(gvPArtyStatement); //Elaborate this function detail later
        Body += "<br><br>Regards,<br>Anukana";
        bool send = send_mail(to, From, subject, Body);//Elaborate this function detail later
        if (send == true)
        {
            string CloseWindow = "alert('Mail Sent Successfully!');";
            ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
        }
        else
        {
            string CloseWindow = "alert('Problem in Sending mail...try later!');";
            ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
         }
    }

send_mail() Definition :

public bool send_mail(string to, string from, string subject, string body)
    {
            MailMessage msg = new MailMessage(from, to);
            msg.Subject = subject;
            AlternateView view;
            SmtpClient client;
            StringBuilder msgText = new StringBuilder();
            msgText.Append(" <html><body><br></body></html> <br><br><br>  " + body);
            view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");

            msg.AlternateViews.Add(view);
            client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.Credentials = new System.Net.NetworkCredential("jhalpharegi@gmail.com", "Your_password");
            client.EnableSsl = true; //Gmail works on Server Secured Layer
            client.Send(msg);
            bool k = true;
            return k;
   }


GridViewToHtml() definition :


 private string GridViewToHtml(GridView gv)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.RenderControl(hw);
        return sb.ToString();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
         //Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
    }


Now browse and send mail and output will be like this one -:


Sometime one can  encountered by this error  -:
RegisterForEventValidation can only be called during Render();

This means that either you have forgot to override VerifyRenderingInServerForm in code behind or EventValidation is true.
So the solution is set EventValidation to false and must override VerifyRenderingInServerForm method.

Tuesday, April 10, 2012

Open outlook in Asp.net(C#) only in 3 steps


Open outlook in Asp.net(C#) only in 3 steps-:
Step 1 :  At first  add the namespace for outlook  and if its not showing in intellisense than add reference for Microsoft.Outlook
using Microsoft.Office.Interop.Outlook;
Step 2 : Bind Data in Grid Which contains Mail Address.Keep Mail Id in Template field in this format

<asp:TemplateField HeaderText="Email" SortExpression="Email">
<ItemTemplate>
<asp:LinkButton ID="lbSendMail" runat="server"  CommandName="SendMail"
CommandArgument='<%# Bind("Email") %>' Text='<%# Bind("Email") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

Step 3 : Fire the RowCommand Event of GridView and Write down the Code Given Below.

if (e.CommandName == "SendMail")
{
   Microsoft.Office.Interop.Outlook.Application oApp = new                Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMailItem = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(OlItemType.olMailItem);
  oMailItem.To = e.CommandArgument.ToString();          
  //Similary U can Add another Detail like body, bcc etc...
  oMailItem.Display(true);
}

Now Run Your Programme and output will be like this :
After Clicking on Any mail Id a new window popup like this one :

Note : To get proper output you have to configure Outlook in your System.


And Finally Here is the Source Code :



Monday, February 13, 2012

How To get Column Value From DataSet


This example shows how to get particular column value from a dataset. Even  We can get all values of that particular field using loop construct.

query = "SELECT [EnrollmentNo] FROM [vw_NewAttenInfo]";
SqlDataAdapter adp = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
adp.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count;i++)
{
…………
…………
string st = ds.Tables[0].Rows[i]["EnrollmentNo"].ToString();
……
……
}

Friday, December 16, 2011

Confirm Message Box using C# in Web Application

To use windows confirm message box in web form at first add window namespace in your cs file.
using System.Windows;
Then add code given below to your desired place.
 
System.Windows.Forms.DialogResult dia = System.Windows.Forms.DialogResult.Yes;

if (gvOrder.Rows.Count > 0)
{
    dia = System.Windows.Forms.MessageBox.Show("Previous Order Is Not Placed Yet.Do U want to      Discard Order? ", "DELETE?", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification);
    if (dia == System.Windows.Forms.DialogResult.Yes)
     {
    //Place Your Code Here

     }

}
else
{
    //Place Your Code Here
}

Put New Line In C#

In C we have a habit  of using "\n" for new line and "\r" for  carriage return.Some operating systems use the value 0x0a ('\n') to mark the end of a line. Some use the value 0x0d ('\r') to mark the end of a line. Some use the sequence 0x0d,0x0a ("\r\n"). "\r\n" is a carriage return followed by a newline. Since the days of teletype machines is mostly gone, \r\n is usually converted to just \n and handled that way. But the notable thing is that Windows  uses NewLine as "\r\n"  whereas  "\n" in Unix.
 In C# you can use "Environment.NewLine" also. Here the code explaining example -:


 Label1.Text = "First Line" + Environment.NewLine + "Next Line";
 TextBox1.Text = "First Line" + Environment.NewLine + "Next Line";
 TextBox2.Text = "First Line\nNext Line";
You have to  change textmode property of textbox from singleline to multiline otherwise you wont be able to see the effect like you cant see this effect in Label.

Tuesday, November 15, 2011

Add Month To any Given Date

Given example shows you how to add months to a given Date.

using System.Globalization;

protected void DropEMISchedule_SelectedIndexChanged(object sender, EventArgs e)

{

DateTime dt;

int calcy = Convert.ToInt32(DropEMISchedule.SelectedValue) * Convert.ToInt32(txttenure.Text);

if (DateTime.TryParseExact(txtEMIStartDate.Text, "dd/MM/yyyy",new CultureInfo("en-US"),  System.Globalization.DateTimeStyles.None, out dt))

{

TextBoxend.Text = "";

DateTime dtshow = dt.Date.AddMonths(calcy);

TextBoxend.Text = (dtshow).ToString("dd/MM/yyyy");

}

}

Convert Number to Text

Function below can be used in converting any number into text.
 
public string NumberToText(int number)
    {
        if (number == 0) return "Zero";
        if (number == -2147483648) return "Minus Two Hundred and Fourteen Crore Seventy Four Lakh     Eighty Three Thousand Six Hundred and Forty Eight";
        int[] num = new int[4];
        int first = 0;
        int u, h, t;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (number < 0)
        {
            sb.Append("Minus ");
            number = -number;
        }
        string[] words0 = { "", "One ", "Two ", "Three ", "Four ", "Five ", "Six ", "Seven ", "Eight ", "Nine " };
        string[] words1 = { "Ten ", "Eleven ", "Twelve ", "Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ", "Seventeen ", "Eighteen ", "Nineteen " };
        string[] words2 = { "Twenty ", "Thirty ", "Forty ", "Fifty ", "Sixty ", "Seventy ", "Eighty ", "Ninety " };
        string[] words3 = { "Thousand ", "Lakh ", "Crore " };
        num[0] = number % 1000; // units
        num[1] = number / 1000;
        num[2] = number / 100000;
        num[1] = num[1] - 100 * num[2]; // thousands
        num[3] = number / 10000000; // crores
        num[2] = num[2] - 100 * num[3]; // lakhs
        for (int i = 3; i > 0; i--)
        {
            if (num[i] != 0)
            {
                first = i;
                break;
            }
        }
        for (int i = first; i >= 0; i--)
        {
            if (num[i] == 0) continue;
            u = num[i] % 10; // ones
            t = num[i] / 10;
            h = num[i] / 100; // hundreds
            t = t - 10 * h; // tens
            if (h > 0) sb.Append(words0[h] + "Hundred ");
            if (u > 0 || t > 0)
            {
                //if (h > 0 || i == 0) sb.Append("and ");
                if (t == 0)
                    sb.Append(words0[u]);
                else if (t == 1)
                    sb.Append(words1[u]);
                else
                    sb.Append(words2[t - 2] + words0[u]);
            }
            if (i != 0) sb.Append(words3[i - 1]);
        }
        //  sb.Append(" Rupees Only");
        return sb.ToString().TrimEnd();
    }

And if you want to convert Rupees value in word then one can use this idea.Here lblBUnit contains the bigger unit of any currency and lblSUnit holds the value of smaller unit of any currency.

             int i = 0;
            String[] val = lbltotal_amount.Text.Split('.');
            foreach (string s in val)
                i++;
            lbltotal_amountinword.Text = NumberToText(Convert.ToInt32(val[0]));
            if (i == 1)
                lbltotal_amountinword.Text = lbltotal_amountinword.Text + " " + lblBUnit.Text + " Only";
            else
                lbltotal_amountinword.Text = lbltotal_amountinword.Text + " " + lblBUnit.Text + " and " +    NumberToText(Convert.ToInt32(val[1])) + " " + lblSUnit.Text + " Only";

Wednesday, November 2, 2011

string.format for datetime

String Format for DateTime [C#]

This example shows how to format DateTime using String.Format method. All formatting can be done also using DateTime.ToString method.
Custom DateTime Formatting

There are following custom format specifiers :
y (year),
M (month),
d (day),
h (hour 12), 
H (hour 24),
m (minute),
s (second),
f (second fraction), 
F (second fraction, trailing zeroes are trimmed),
t (P.M or A.M) and
z (time zone).

Following examples demonstrate how are the format specifiers rewritten to the output.


// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone

You can use also date separator / (slash) and time sepatator : (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.


// date separator in german culture is "." (so "/" changes to ".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

Here are some examples of custom date and time formatting:


// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Standard DateTime Formatting

In DateTimeForma­tInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt for en-US culture and value HH:mm for de-DE culture.

Following table shows patterns defined in DateTimeForma­tInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTi­mePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSorta­bleDateTimePat­tern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent

Following examples show usage of standard format specifiers in String.Format method and the resulting output.


String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime