Tuesday, November 27, 2012

Barcode in Multiple Columns In RDLC

This article shows how to print barcode in rdlc in multiple columns. The final outcome of this article will be like this one -:
At first design the report than format it accordingly.I have used list control , Textbox and one Image control for this report.
Now, in this report three important things are present.
First one barcode, 2nd one Rupee symbol and the 3rd one is multiple column.
BARCODE :
Now for Barcode just install barcode font like 3o9 etc.And set the font of textbox to barcode font.One thing u must take care that the barcode is prefixed and suffixed by "*". For example if barcode is "000003" then it will be like "*000003*".
RUPEE SYMBOL :
Now for rupee symbol I have just put the image of it. Help for Image.
MULTIPLE COLUMNS :
For this u have to change columns in properties of Body.Rest is the matter of height n width of page and body.The height n width of body is for each column i.e. if here 3 columns are defined then finally page width will be of 3 inches.
Now, go to Report Properties.
Now, In this new window open the layout tab. And change the column to 3 and column spacing to 0.
In my scenario there is a scarcity of space thats why I have set column spacing to "0". You can change it a/c to ur need.
Then set the page width and height to ur need.Standard width=8.5in and height=11in. I have just saved my space by setting "0" to  left,right,top and bottom margin.
Now ur final design will look like this one :
When u run the report output will be like given image.To view the actual output u have to export it to PDF.


Image in RDLC

Show External Images In RDLC
This post is about "How to show images in RDLC?". 
Step 1 : In RDLC just drag n drop image from toolbox.
Step 2 : In property of Image change source to external and in value specify the path of image.
In path u have to put  "file:/// " before the absolute path for local resources and for Server "http://" .
Step 3 : In Code Behind we have to enable EnableExternalImages.
            ReportViewer1.LocalReport.EnableExternalImages = true;
Now, Run the report. If Image is not visible than we have to follow step 4.
Step 4 : We may need to bypass proxy settings to allow the external image to appear. Add following setting to web.config file.
 <system.net>
        <defaultProxy>
            <proxy proxyaddress ="http://proxyservername:80" usesystemdefault="False" bypassonlocal="True">    </proxy>
        </defaultProxy>
    </system.net>

Wednesday, October 31, 2012

Operation is not valid due to the current state of the object.


Error : Operation is not valid due to the current state of the object.

Stack Trace:



[InvalidOperationException: Operation is not valid due to the current state of the object.]
   System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +2692482
   System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +61
   System.Web.HttpRequest.FillInFormCollection() +148

[HttpException (0x80004005): The URL-encoded form data is not valid.]
   System.Web.HttpRequest.FillInFormCollection() +206
   System.Web.HttpRequest.get_Form() +68
   System.Web.HttpRequest.get_HasForm() +8743911
   System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
   System.Web.UI.Page.DeterminePostBackMode() +63
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +133

This error occurs when form fields are very large in numbers.By default, the maximum value of MaxHttpCollection is 1000.

Solution:

To solve this error, increase MaxHttpCollection value. Try adding the following setting in your web.config's <appsettings> block. 

<appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="3000" />

 </appSettings> 

you can change the value accordingly as per your need. 

Thursday, October 18, 2012

Count No of Table,View,Indexes,Stored Procedure

Sometime we need to count the no of table/view/indexes/stored procedure in Database.
 --Returns Total No of User Defined Table
select count(*) cntTables from sysobjects where type = 'U'

--Returns Total No of User Defined View
select count(*) cntView from sysobjects where type = 'V'

 --Returns Total No of Index.You may need to further filter,
 -- depending on which types of indexes you want.
select count(*) cntIndex from sysindexes

--Returns No of Stored Procredure
select Count(*) cntProc from sys.procedures


--Return numbers of non clustered indexes on any table in entire database.
SELECT COUNT(i.TYPE) NoOfIndex,
[schema_name] = s.name, table_name = o.name
FROM sys.indexes i
INNER JOIN sys.objects o ON i.[object_id] = o.[object_id]
INNER JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
WHERE o.TYPE IN ('U')
AND i.TYPE = 2
GROUP BY s.name, o.name
ORDER BY schema_name, table_name

Tuesday, October 9, 2012

Delete Duplicate Rows from Multiple Tables

There are various ways for removing duplicate rows from  table. In my scenario there are three table which from where I have to delete duplicate rows. All these tables have relation. These tables are-:

Purchase_Rcv -: Keeps information about each purchase receive.
Purchase_RcvDet -: Keeps information about purchased product  for each purchase receive
BarcodeDet -: Keeps Barcode Detail for each received product
There is one more table that is -:
POS_STOCK-: As its name exhibits, keeps stock information

So I have to also update stock in this table.

So, to implement this I wrote a select statement which fetches all the rows of table without duplicacy and the query is :
SELECT min(PoRcvDet_Id) as id   FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code]

Here Product_Code is the column on which I want to remove duplicacy. So, I used group by on Product_Code which returns distinct rows based on Product_Code.

I used min() to keep first entry.One can use max() also.

 Then I wrote the Delete Command which deletes all rows which are not in the selected rows.


Delete FROM [Purchase].[BarcodeDet]
      WHERE fkPoRcvDetId not in
      (SELECT min(PoRcvDet_Id) as id   FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code] )
           
Delete FROM Purchase.Purchase_RcvDet
WHERE PoRcvDet_Id not in
      (SELECT min(PoRcvDet_Id) as id  FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code] )
           
Delete FROM Purchase.Purchase_Rcv
WHERE PoRcv_Id not in
      (SELECT min(fkPoRcv_Id) as id  FROM [Purchase].[vw_PurchaseRcvDet] group by [Product_code] )



Update Stock--:


UPDATE [dbo].[POS_STOCK]
   SET [Stock] = b.[Qty]
  from [Purchase].[Purchase_RcvDet] as b
  left outer join  [dbo].[POS_STOCK] on b.[fkProductId]=[dbo].[POS_STOCK].[fkProductId]



In my scenario POS_STOCK has same no of rows as in Purchase_RcvDet. Thats why I have used  left outer join.


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

Monday, July 16, 2012

Upload And Remove Files From Table Dynamically

This example shows how to add / remove rows in a grid
simoltaneously. To implement this I have used Repeater Control and DataTable where DataTable is used to store the values entered runtime also remove data if remove command will be passed and Repeater is used to show the data .Final output will be like this one -:

For this add a repeater control on your aspx and  fire properties "onitemcommand " &" onitemdatabound".
 <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand"
        onitemdatabound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table style="border: thin dotted #0000FF; width: 950px">
<tr>
<th>File Category</th>
<th>File Access</th>
<th>File</th>
<th>Description</th>
<th>&nbsp;</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:DropDownList ID="ddlFileCat" runat="server" ></asp:DropDownList>
</td>
<td>
<asp:RadioButtonList ID="rblFileAccsess" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>Public</asp:ListItem>
<asp:ListItem>Private</asp:ListItem>
</asp:RadioButtonList>
</td> 
<td>
<asp:Label ID="lblFileNm"  runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FileNm") %>'></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:TextBox ID="txtFileDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FileDesc") %>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnAddAnother" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Button") %>'  CommandName='<%#DataBinder.Eval(Container.DataItem,"Button") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

Repeater's ItemDataBound property is used to bind dropdownlist form database and to show the value as selected runtime.
 protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList ddl = (DropDownList)e.Item.FindControl("ddlFileCat");
            RadioButtonList rbl = (RadioButtonList)e.Item.FindControl("rblFileAccsess");

            SqlDataAdapter adp = new SqlDataAdapter("SELECT [CategoryID],[CatName] FROM [dbo].[MST_FileCategory]", con);
            DataSet ds = new DataSet();
            adp.Fill(ds);

            ddl.DataSource = ds;
            ddl.DataTextField = "CatName";
            ddl.DataValueField = "CategoryID";
            ddl.DataBind();
            ddl.SelectedValue = dtTemp.Rows[i]["FileCat"].ToString();
            rbl.SelectedValue = dtTemp.Rows[i]["FileAccess"].ToString();
            i++;

        }
        //   ddl.SelectedValue = Eval("FileCat").ToString();
    }

To Add or Remove rows from Datatable we will use ItemCommand from where we will pass the Command ADD or REMOVE.

  protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        //int cnt = Repeater1.Items.Count; //get total row count in repeater
        if (e.CommandName == "Add")
        {
            //  cnt++;
            AddColumns();

            foreach (RepeaterItem item in Repeater1.Items)
            {
                //Getting the value of fields
                FileUpload fu = (FileUpload)item.FindControl("FileUpload1");
                Label fileName = (Label)item.FindControl("lblFileNm");
                Button btnAdd = (Button)item.FindControl("btnAddAnother");

                if (btnAdd == e.CommandSource)
                {
                    if (fu.HasFile)
                    {
                        string path = Server.MapPath("~/Docs/");
                        fileName.Text = fu.FileName;
                        fu.SaveAs(path + fileName.Text);
                    }
                }

                string fileCat = ((DropDownList)item.FindControl("ddlFileCat")).SelectedValue;
                string fileAccess = ((RadioButtonList)item.FindControl("rblFileAccsess")).SelectedValue;
                string fileNm = ((Label)item.FindControl("lblFileNm")).Text;
                string fileDesc = ((TextBox)item.FindControl("txtFileDesc")).Text;

                //now chnage button text to remove & save values in table
                dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Remove");
            }
            //Add dummy rows bcoz we neeed to increase
            dtTemp.Rows.Add("", "", "", "", "Add");
            BindWithRepeater();
        }
        else if (e.CommandName == "Remove")
        {
            // cnt--;
            AddColumns();
            foreach (RepeaterItem item in Repeater1.Items)
            {
                Button btnAdd = (Button)item.FindControl("btnAddAnother");
                if (btnAdd != e.CommandSource)
                {
                    string fileCat = ((DropDownList)item.FindControl("ddlFileCat")).SelectedValue;
                    string fileAccess = ((RadioButtonList)item.FindControl("rblFileAccsess")).SelectedValue;
                    string fileNm = ((Label)item.FindControl("lblFileNm")).Text;
                    string fileDesc = ((TextBox)item.FindControl("txtFileDesc")).Text;

                    if (btnAdd.Text == "Remove")
                    {
                        dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Remove");
                    }
                    else
                    {
                        dtTemp.Rows.Add(fileCat, fileAccess, fileNm, fileDesc, "Add");
                    }
                }

            }
            BindWithRepeater();
        }

    }

AddColumns() and BindWithRepeater() are user defined functions.Define this functions also and call them in pageload.

  public void AddColumns()
    {
        dtTemp.Columns.Add("FileCat");
        dtTemp.Columns.Add("FileAccess");
        dtTemp.Columns.Add("FileNm");
        dtTemp.Columns.Add("FileDesc");
        dtTemp.Columns.Add("Button");
    }
    public void BindWithRepeater()
    {
        //Bind this Dataset to repeater
        Repeater1.DataSource = dtTemp;
        Repeater1.DataBind();
    }

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            AddColumns();
            dtTemp.Rows.Add("", "", "", "", "Add");
            BindWithRepeater();
        }
    }

Now here is the whole code -:

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

Calculate No of Days Between Two Dates in Sql Server


Monday, May 7, 2012

C Sharp Interview Questions with Answers

Here I am going to include some important questions asked in recent interview.This is beneficial for both freshers and experienced.By answering these questions You will leave a good impression on interviewer.
So,now no more talks..start reading and digesting.

What is Mutex?

Mutex is the short form for MUTual EXclusion.
Mutual exclusion refers to the problem of ensuring that no two processes or threads can be in their critical section at the same time. Here, a critical section refers to a period of time when the process accesses a shared resource, such as Shared Memory. The problem of mutual exclusion was first identified and solved by Edsger W. Dijkstra in his seminal 1965 paper titled: Solution of a problem in concurrent programming control.
In C# there is Mutex class defined within System.Threading Namespace

What do You mean by LOCK and Wait?


A Lock is a synchronization mechanism for enforcing limits on access to a resource in an environment where there are many threads of execution. Locks are one way of enforcing concurrency control policies.

A process (or task) may wait on another process to complete its execution. In most systems, a parent process can create an independently executing child process. The parent process may then issue a wait system call, which suspends the execution of the parent process while the child executes. When the child process terminates, it returns an exit status to the operating system, which is then returned to the waiting parent process. The parent process then resumes execution.

Define Static members of the class in the terms of C# -:
Static members belong to whole class rather than to individual object. For example, if you have a static phoneNumber field in your Student class, then there will be the single instance of this field and all the objects of this class will share this single field. Changes made by one object to phone Number will be realized by the other object.
Class Student
{
    Public static int phoneNumber;
    Public int rollNumber;
}
Class Test
{
    Public  static void Main()
    {
        Student  st1=new Student();
        Student st2=new Student();
        St1.rollNumber=3
        St2.rollNumber=5;
        Student.phoneNumber=4929067;
     }
}
Here you can see that the phoneNumber is accessed without any reference to the object but with the name of the class it belongs. Static methods are very useful while programming. In fact, the WriteLine() and ReadLine() methods are static methods of Console Class. Even Main () is declared as static as CLR calls it without making any instance of class. It’s useful when we want to cache data that should be available to all objects of class.
Some precautions:
Don’t put too many static methods in your class as it is against the OO design principles and makes your class less extensible.
You tend to loose a number of OO advantages while using static methods, as static methods can’t be overridden which means it cannot be used polymorphically, something widely used in the OO paradigm of programming.

What DoYou mean by Singleton Approach?
This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

Tuesday, May 1, 2012

Bind DropDownList in Gridview


Binding values in Dropdownlist in Gridview at runtime is not a big task.We can do it using RowDatabound event.In the given example dropdownlist is being populated at the time of editing.
At first declare a dropdownlist control in EditItemTemplate.

 <asp:TemplateField HeaderText="State" SortExpression="StateName" >
 <EditItemTemplate>
      <asp:DropDownList ID="ddlStateNm" runat="server" DataTextField="StateName"    DataValueField="StateID"> </asp:DropDownList>
      <asp:Label ID="lblStateID" runat="server" Text='<%# Bind("StateID") %>' Visible="false"></asp:Label>
 </EditItemTemplate>
 <ItemTemplate>
         <asp:Label ID="lblStateName" runat="server" Text='<%# Bind("StateName") %>'></asp:Label>
 </ItemTemplate>
</asp:TemplateField>

Write a Function to bind DropDownList.
 public void BindStateddl(DropDownList ddl)
    {
        SqlDataAdapter adp = new SqlDataAdapter("SELECT [StateID],[StateName] FROM [dbo].[MST_State] order by [StateName] asc", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);


        ddl.DataSource = ds;
        ddl.DataBind();
        ddl.Items.Insert(0, new ListItem("---Select---", "0"));
    }

Now the most important part the RowDataBound event. Here at first check for DataRow so that it will overlook HeaderRow and then check for EditIndex so that Databinding to DropDownList will be implemented to editble row only.

   protected void gvCourt_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         
            if (gvCourt.EditIndex == e.Row.RowIndex) //to overlook header row
            {
                string StateId = ((Label)e.Row.FindControl("lblStateID")).Text;


                DropDownList ddlGridState = (DropDownList)e.Row.FindControl("ddlStateNm");
           
                BindStateddl(ddlGridState);


                ddlGridState.SelectedValue = StateId;
            }
        }
    }


Tuesday, April 24, 2012

Equivalent Split function in SqlServer

Several times we have a collection of unique ids and we have to do some operation like update or delete based upon those ids.Now Given below function works as split and send all  values to the table.
This function basically needs three parametes-:
1) a string containg values seperated by some delimeter
2) delimiter
3)TrimSpace option( bit type to kill whitespaces)

Create FUNCTION [dbo].[fn_String_To_Table] (
            @String VARCHAR(max), /* input string */
   @Delimeter char(1),   /* delimiter */
   @TrimSpace bit )      /* kill whitespace? */
RETURNS @Table TABLE ( [Val] VARCHAR(4000) )
AS
BEGIN
    DECLARE @Val    VARCHAR(4000)
    WHILE LEN(@String) > 0
    BEGIN
        SET @Val    = LEFT(@String,
             ISNULL(NULLIF(CHARINDEX(@Delimeter, @String) - 1, -1),
             LEN(@String)))
        SET @String = SUBSTRING(@String,
             ISNULL(NULLIF(CHARINDEX(@Delimeter, @String), 0),
             LEN(@String)) + 1, LEN(@String))
  IF @TrimSpace = 1 Set @Val = LTRIM(RTRIM(@Val))
    INSERT INTO @Table ( [Val] )
        VALUES ( @Val )
    END
    RETURN
END

Now here is a Stored Procedure using above function to update table.

create PROCEDURE [dbo].[sp_AdminDelStudEntry]
@RegNoString varchar(max)
AS
BEGIN
SET NOCOUNT ON;
UPDATE [dbo].[Admission] SET [Isdelete] = 'Y'
    WHERE [Reg_Noid] in (SELECT Val FROM [dbo].[fn_String_To_Table](@RegNoString,',',1))
 
UPDATE [dbo].[Academic] SET [Isdeleted] = 'Y'
    WHERE [regno] in (SELECT Val FROM [dbo].[fn_String_To_Table](@RegNoString,',',1))
END

CSS for Rounded Corner TextBox


A simple example for implementing rounded corner on TextBox using CSS.
 <style type="text/css">

.roundedbox {
    background:#fff;
    font-family:Verdana,Arial, Helvetica, sans-serif;
    font-size:10pt;
    margin-left:auto;
    margin-right:auto;
    margin-top:1px;
    margin-bottom:1px;
    padding:3px;
    border-top:1px solid #CCCCCC;
    border-left:1px solid #CCCCCC;
    border-right:1px solid #999999;
    border-bottom:1px solid #999999;
    -moz-border-radius: 8px;
    -webkit-border-radius: 8px;
}

 </style>

<asp:TextBox ID="TextBox1" runat="server" CssClass="roundedbox" Width="300px">

And here the output :

Saturday, April 21, 2012

Left or Right alignment in Gridview Columns

When we work with Grid-view we need to make left or right or centered alignment on column values according to their Datatype.For example we have to make right aligned all money values and character values to be left aligned. To do this just embed column within table like given example -:

 <asp:TemplateField HeaderText="Debit">
          <ItemTemplate>
                    <table align="right"  ><tr><td>
                                <asp:Label ID="lblDebit" runat="server" Text='<%# Bind("Debit") %>'></asp:Label>
                    </td></tr></table>
          </ItemTemplate>
 </asp:TemplateField>

Hope you'll get it. Enjoy coding.

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster

Here are few steps to fix "Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster" error.

Step 1 : Visit this link and generate your machine key.
http://www.eggheadcafe.com/articles/GenerateMachineKey/GenerateMachineKey.aspx

Step 2 : Copy the machine key given by above link and paste it to your web.config file.


<?xml version=”1.0″?>

<configuration>

    <appSettings/>
    <connectionStrings/>
    <system.web>

       <machineKey validationKey='4C8B22744D71B73CE6B16262A97CF3862E584829229EDE45C9DF207DDF5F3507782A3F2F6506085028628868F6AFFC25D16BE4AD8BB677637B11C892F95FE819'   decryptionKey='53EA49CFEC5C5A1E4720DE83E1CC75337674757144EB1DCB'   validation='SHA1'/>

    </system.web>
</configuration>


Step 3 : By doing above two steps you will be relieved by this error.But you must know why this error occurs.To get a good detail about this error you must visit this link.

http://www.codeproject.com/Articles/16645/ASP-NET-machineKey-Generator

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 :



Wednesday, April 4, 2012

Value does not fall within the expected range in rdlc

Whenever we encountered by this error in rdlc, it simply means that we are assigning whole dataset to ReportDatasource.

 ReportDataSource rds = new ReportDataSource("MinQtyItem_sp_MinQtyItem", ds);


To overcome this issue just tell ReportDataSource which table of DataSet She/He has to load.

 ReportDataSource rds = new ReportDataSource("MinQtyItem_sp_MinQtyItem", ds.Tables[0]);

Monday, March 26, 2012

Multiple Invoice


 This example illustrate how to generate report for Multiple Invoice. Multiple Invoice is a concept where table data changes  accordingly invoice no but header and footer will be same.
Step 1 : Now start from Creating Stored Procedure which fetches data from table or view for invoice.
Step 2 : Create DataSet. and  Add new RDLC. If you need help in doing this then goto HELP
Step 3 : Add LIST from Report Items

Step 4 : Right Click on Blank Area of List then goto properties.

Step 5 : Choose Data set Name. Click “Edit Details Group” button. In General Tab  Select in Group on the expression value on which you want to group. Parent group is optional.Check “ Page Break at End”  option.

Step 6 : Now you have to put all information in the list area.In my sample report I have a header section in body which will change a/c to  Invoice No.
Drag n Drop Textbox from ReportItems and then Drag n Drop field values to related textboxes.

Step 7 :  Drag n Drop Table.

Step 8 : Now Drag n Drop the fields  to detail section which u want to show in table format.

Step 9 : To add new column to table right click on any column and do whatever you want.

Step 10  : Reduce the width of textbox of table from its properties.

Step 11  : To view sum of any field of table just drag n drop same field to its footer section.
 Step 12 : To calculate VAT put formula in texbox's expression.

Step 12 : From Report Menu Add Header and Footer. 
Step 13 : Design Header and Footer Section a/c to your need.

 

Now Add ReportViewer to aspx and connect it to RDLC.If you need elaborate description  for then read Basic RDLC
Finally view report in browser  and  output will be like this.

Now here is the thing you are looking for :

Show Value upto Two Decimal Places in Gridview

Show money or float values upto two decimal places using 
String.Format in Gridview.
 
<%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem,"Rate")) %>
 or
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Amt","{0:f2}")  %>'></asp:Label> 
 
Example :  
<asp:TemplateField  HeaderText="Rate">
<ItemTemplate>
   <table align="right" style="text-align: right"><tr><td align="right">
    <asp:Label ID="lblRate" runat="server" 

Text='<%# String.Format("{0:f2}",DataBinder.Eval(Container.DataItem,"Rate")) %>' ></asp:Label>
   </td></tr></table>
</ItemTemplate>
</asp:TemplateField>

Monday, February 27, 2012

Upper case, Lower case, Proper Case or Title Case in C#


Convert a string to Uppercase

String Sub_Code = txtcode.Text.ToUpper();

Convert a string to Lowercase

String Sub_Code = txtcode.Text.ToLower();

Note : ToLower and ToUpper are methods of string class.

Convert a string to ProperCase or TitleCase
The String class does not include any method that converts a string to title case. To convert  a string to title case we use ToTitleCase method which resides in the TextInfo class, which is a member of the System.Globalization namespace. Unlike the ToUpper and ToLower methods of the String class, the ToTitleCase method is not a static method and requires an instance of the class.

When we use the TextInfo class, we must specify cultural information. CultureInfo class represents information about a specific culture including the names of the culture, the writing system, and the calendar used, as well as access to culture-specific objects that provide information for common operations, such as formatting dates and sorting strings.

Example :
CultureInfo cultureinfo = CultureInfo.InvariantCulture;
TextInfo textinfo = cultureinfo.TextInfo;

string Sub_Name =textinfo.ToTitleCase(txtname.Text);