Friday, November 25, 2011

Upload, Save and Retrieve Image

  This article shows you how to upload,save and retrieve image in asp.net using c#. Basically we can do this in two way.The first one is we can save the image in any specific folder and in database save the path and to retrieve it just bind the path to image url. And in another way we can save the image in binary format in database.Now at first place the image control, file upload control and button in your aspx page.

<asp:Image ID="imgMem" runat="server" Height="116px" BorderColor="Black"  BorderStyle="Double" ImageUrl="~/Images/userimage.jpg" Width="150px" EnableTheming="False" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click"  Text="Upload" />

In button click event write down the code given below.

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            path = Server.MapPath("~/Library/Images/");
            FileUpload1.SaveAs(path+FileUpload1.FileName);
            picnm = FileUpload1.FileName;
           /* If Path exists then set path to ImageUrl & hold the value on ViewState */
            ViewState["picnm"] = picnm;
            imgMem.ImageUrl = "~/Library/Images/" + FileUpload1.FileName;
        }
    }

In database define the field as varchar. And  save it in your own way.
  cmd.Parameters.AddWithValue("@img",ViewState["picnm"].ToString());

To retrieve the image fetch the field value and bind it to image url.
 imgMem.ImageUrl = "~/Library/Images/" + dr["MemPic"].ToString();

Now to save image in binary format write given code in button's click event
  if (FileUpload1.HasFile)
            {
                 // Create a byte[] from the input file
                len = FileUpload1.PostedFile.ContentLength; // Here len is integer
                if(len > 409600)
                {
                    CloseWindow = "alert('Picture size is too large.Maximum file size is 400KB.');";
                    ScriptManager.RegisterStartupScript(this.UpdatePanel_St, this.UpdatePanel_St.GetType(),       "CloseWindow", CloseWindow, true);
                    return;
                }
                pic = new byte[len]; //pic is an array of byte type
                FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
                ViewState["pic"] = pic;
                Session["img"] = pic;
                imgMem.ImageUrl = "GetImgBefSave.aspx";

            
            }

To retrieve the image before save create a blank web form and write down the below code in its cs file.

public partial class Library_GetImgBefSave : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindImg();
    }
    public void BindImg()
    {
        byte[] pic = (byte[])Session["img"];
        Response.BinaryWrite(pic);
    }
}

Now to save the image write down the code given below.
  byte[] img = (byte[])ViewState["pic"];
  query = "INSERT INTO [dbo].[test] ([pic]) VALUES (@img)";
  SqlCommand cmd = new SqlCommand(query,con);
  cmd.CommandType = CommandType.Text;
  cmd.Parameters.AddWithValue("@img", img);
  if (con.State == ConnectionState.Closed)
        con.Open();
  cmd.ExecuteNonQuery();
  con.Close();

To retrieve the image create a new blank web form.In the code behind write down the below code.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Library_getimg : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EduComERPConnectionString"].ConnectionString);
    string query = null;
    string id = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        id = Request.QueryString["ID"];
        if (!IsPostBack)
        {
            GetImg();
        }
    }
    public void GetImg()
    {
        query = "SELECT [MemPic] FROM [dbo].[tbl_LibMemInfo] where [Lib_Id]=" + id + "";
        SqlCommand cmd = new SqlCommand(query,con);
        cmd.CommandType = CommandType.Text;
        if (con.State == ConnectionState.Closed)
            con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            if (dr["MemPic"].ToString() != "")
            {
                byte[] img = (byte[])dr["MemPic"];
                Response.BinaryWrite(img);
            }
        }
        dr.Close();
        con.Close();
    }
}


Now bind the address of this web form to image url.

 imgMem.ImageUrl = "getimg.aspx?ID=" + dr["Lib_Id"].ToString();
    


Check or uncheck items in a checkbox list, based on information

This example shows you the way to get the value of checked items and then again check the checkbox a/c to the values.
 foreach (ListItem val in ChklPeriod.Items)
 {
      if (val.Selected)
            ViewState["data"] += val.Text + ",";  //store the selected values in viewstate separated by a comma
 }

Now to check the checkboxlist a/c to the stored values use the method given below.
if (ViewState["data"] != null)
{
      foreach (string s in ViewState["data"].ToString().Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
      {
             foreach (ListItem l in ChklPeriod.Items)
                        if (l.Text == s)
                            l.Selected = true;
      }
}

Wednesday, November 23, 2011

Concatenate two fields in sql server

Sometime we need to concatenate two or more fields n show them in formatted manner.If all the fields are varchar then its not a big deal just use the technique given below.

SELECT [PartyNm]+' ( '+ [TempAdd] +', '+ [ContactNo]+' )' as name  FROM [dbo].[tbl_AccountMaster]

But you have to face problem if the fields are int type or containing numbers only.In this scenario it add values instead of concatenation.
 SELECT  [Unit_Id]+[BD_Id] as ID FROM [dbo].[MST_Unit]

So to overcome this issue you have to convert the field into varchar than try to concatenate,this will give you the desired result.

SELECT '('+CONVERT(varchar,[Unit_Id])+'-'+convert(varchar,[BD_Id])+')' as ID FROM [dbo].[MST_Unit]

If you will attempt to concatenate columns without conversion like this one,
SELECT '('+[Unit_Id]+'-'+convert(varchar,[BD_Id])+')' as ID FROM [dbo].[MST_Unit]
Then got the following error

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value ' )' to data type int.

Thursday, November 17, 2011

String or binary data would be truncated. The statement has been terminated.

Very often you will get errors like "String or binary data would be truncated. The statement has been terminated". We just wandered why we encountered by this error while everything seems right.But this error simply says you are updating the column with larger size than what it can accommodate.So don't worry just check your field length or your entry for spaces.



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";

Show Total in GridView Footer

 Given Example shows you how to calculate total of particular cells value and show at the footer of Gridview.
At first define footer template in template field for which you want to calculate total.


<asp:TemplateField HeaderText="Total Pcs">
 <ItemTemplate>
          <asp:Label ID="lbltotpcs" runat="server"  Text='<%# Bind("totpcs") %>'></asp:Label>
 </ItemTemplate>
 <FooterTemplate>
        Total : <asp:Label ID="lbltotqty" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>


Populate the RowDataBound event of Gridview where you have to do the main calculation.

int totqty=0;
protected void gvCrate_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label totpcs = (Label)e.Row.FindControl("lbltotpcs");
            totqty = totqty + (Convert.ToInt32(totpcs.Text));
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            ((Label)e.Row.FindControl("lbltotqty")).Text = totqty.ToString();
            TxtTotalpcs.Value = totqty.ToString();
        }
    }

Enable  "ShowFooter" as True in Gridview's property.

Friday, November 11, 2011

Menu Control Not Working Properly On Every Browser

Browser Compatibility Code 
Paste below code in your page_load event of page or master page and then test it on mac safari. Its working fine
if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
  {
            Request.Browser.Adapters.Clear();
  }

Wednesday, November 2, 2011

ISNULL() -Returns Desired Value If The Field Vlue Is Null

This example shows the use of ISNULL() method.It returns the given value if the field value is NULL.This method takes two arguments first one is desired field and 2nd one is the value you want return if field has value NULL.


ISNULL( check_expression , replacement_value)
select  ISNULL(Name,'xyz') as Name from Stud_Master

Temporary Table -SQL Server

This example Shows you how to create temporary table in SqlServer, Insert values in them, Check their existence and finally Drop them.

Create Temp Table

This one is declared as Global Temporary Table
create table ##YourTempTable (YourTableField1 bigint,YourTableField2 varchar(50))

This one is declared as Local Temporary Table
create table #YourTempTable (YourTableField1 bigint,YourTableField2 varchar(50))


Insert Values in Your Temporary Table 
 
insert into ##YourTempTable
SELECT * FROM  YourDesiredTable

Check Existence of Temporary table


if exists(select * from tempdb.dbo.sysobjects where ID=object_ID(N'tempdb..##YourTempTable '))


Check Existence n Then Drop Temporary Table


if exists(select * from tempdb.dbo.sysobjects where ID=object_ID(N'tempdb..##YourTempTable '))
BEGIN
DROP TABLE ##YourTempTable
END

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