Convert Webpage to PDF

Posted by Venkat | Labels: ,

How to Convert the webpage to PDF. There is a question asked in forums by most of the members.

Here the some methods that will be help you.

There are number of ways to do...,

1) using ITextSharp

2) Make the webpage as Image and add it to PDF ( proposed by Charith - Thanks anyway)

Check the forums discussion here

3) Using some online tool like this HTML to PDF

4) If the User want a link on the webpage so if the user click the link , current page is converted to PDF.

Check this:  http://www.pdfspot.com/

Thanks

Post Method - Example Code

Posted by Venkat | Labels: ,

Here I am going show : how to post the data from one page to another page using POST Method.

Here is the Simple example.

P1.aspx


   <form id="form1" runat="server" method ="post" action ="p2.aspx">
    <div>
    User : <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br/>
        Password : <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>

        <asp:Button ID="btnSend" runat="server" Text="Send"  PostBackUrl ="~/p2.aspx" /> 
    </div>
    </form>



So if you are going to use post method on form tag set method="post" and action="p2.aspx" ie: designation url to get the data of p1.aspx on p2.aspx.

P2.aspx


 <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </div>
    </form>





protected void Page_Load(object sender, EventArgs e)
    {
        TextBox1.Text = Request.Form["txtName"].ToString ();
        TextBox2.Text = Request.Form["txtPassword"].ToString ();
    }


Finally on destination page

using Request.Form["yourcontrolid"] to get value of the control on p1.aspx

Configure the Google Map API key for Multiple domains

Posted by Venkat | Labels: ,

Recently I am looking in to the issue.. how to configure the google map API key for the Multiple Domains.

In my case i have two domains : Create a Google MAP API key for the Two Domains

Example:

'domain1.com' : 'api-key-for-domain1'
'domain2.com' : 'api-key-for-domain2'


So use this Javascript instead of your previous Javascript




<script type="text/javascript">
var strKey = "";

switch (window.location.host)
{
case 'domain1.com':
strKey = 'ABsdfQIAA34AArNH17caPfR3kIylWMznsdfh3xTfvmRwsdfsd6dRB3osdfVmrrtfPwNADfaZlxQgtqbBp4xswSjiA0KYuB2Y2ynaUQ';
break;
case 'domain2.au':
strKey = 'Agbs42BQIAdfsAAArNH17caPfdfdfR3kIylWMfsdznh3xRosdfqCxgZKzqbnVvUHRgAMBYHaL-QhSwZqznIVtPbMQt4wrboRbFET9LYQ';
break;

}

document.write('<'+'script src="http://maps.google.com/maps?file=api&v=2&key='
+ strKey + '" type="text/javascript">' + '<'+'/script>');
</script>




So try the above script - this will work for multiple domains.

Ref:


http://groups.google.com/group/google-maps-api/browse_thread/thread/3c300b5be6b5cad7/77037ee6035f2c84?lnk=gst&q=multiple+domains#77037ee6035f2c84

How to check the specific field in the row has contain null or value.

Posted by Venkat | Labels: , ,

Good Morning after a month I spend the time to post the small tips who already known but i would like to share this post which everyone come to know.

Question :  how to check the specific field in the row has contain null or value.

Normally we used to get the data from the DB using specific id for ex: get the specific user details using his userid. So it will return that row value. In that row some field may contain NULL value.

Here is the code to check the particular field contains value or null.

In my case I am getting the row from Database and assigned to the Datarow like this

Dim dr as DataRow

dr = ds.Tables(0).Rows(0)

Here the dr contains the row data from this I am checking the field.

Datarow  contains a method called  IsNull to check whether the field has null or value.

EX:

if (dr.IsNull("fieldname")) then
' if the field contain null do the manipulation here
else
' the field cotains some value.
End if 

the above code defines the Datarow contain a method called IsNull which is going to check the whether the specified fieldname has value or null as per we can manipulate it.

And also I am going to tell another tips which was pointed @ DotnetCurry.com here - thanks for that.

IE: if we are going to display user photo on Gridview where user have to upload his photo which will be an optional, User may or may not upload his photo, at that time the user who don't have photo on DB , the Gridview shows the cross mark image for that user. This is not good in practice from user point of view  instead we have to show the default image for the user who don't have photo on DB.

Example:

on the HTML img tag write like this

< img src="Dynamic-imagename" onerror="this.src='../images/NoImageFound.jpg'" .. / > 

This above tag will show the user photo who have photo on DB if there is no photo on DB for those it shows the default image specified on onerror event.

Read or Write Session value on HTTP Handler file (.ashx)

Posted by Venkat | Labels: ,

How to use Session (ie: read or Write) on HTTPHandler file ie: .ashx file ?

I noticed some post on forums how to get the Session value on (.ashx file). So here is the solution.
By Default if you use Session on handler, the session returns null value. You have to implement the interface to read or write session value on handler file. If there is a situation to read Session value on your Handler file  implement IReadOnlySessionState.

When there is a case, you have to read or write session value in Handler file.
Implement IRequireSessionState.

Here is the code where i implement both IReadOnlySessionState and IRequireSessionState.

Example:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Web.SessionState; 

public class Handler : IHttpHandler , IReadOnlySessionState  , IRequiresSessionState   {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

Import XML file to Sql Server using SSIS

Posted by Venkat | Labels: ,

Good Morning to Everyone.

Today I am going to discuss about the SSIS (Sql server Integration Services) ie: how to Export the XML file to Sql Server with Column name and Data.

What is SSIS ?

 - To solve complex busniess problems.

 - sending and downloading files
 
 - sending email messages in response to events

 - Update Datawarehousing

 - Cleaning and Data mining

 - Managing Sql server data objects

Its the concept of ETL - ie. Extract - Transform - Load

Purpose:

1) Automate maintenance of sql server Database.

2) Update MultiDimensional Cube data as well.

I have the situation that xml file can be imported to the SQL server ie: i have the xml file look like this


<dataset>
<items>
 <empid>1</empid> 
 <empname>ela</empname> 
 <empcity>madhurai</empcity> 
 <empsalary>10000</empsalary> 
 </items>
 <items>
 <empid>2</empid> 
 <empname>arun</empname> 
 <empcity>chennai</empcity> 
 <empsalary>20000</empsalary> 
 </items>
 <items>
 <empid>3</empid> 
 <empname>kumar</empname> 
 <empcity>bangalore</empcity> 
 <empsalary>25000</empsalary> 
 </items>
 </dataset>

I have convert this XML file to DB tables. It should be same schema , contraints, Relationship, trigger etc..
For this SSIS is a easy way to convert any XML , text , Word , Excel file to Sql Database.

So you have to choose Business Intelligence and Development Studio (BIDS) to do the task

There are three ways to create a packages.

1) SSIS Designer(BIDS - Business Inelligence Development Studio)

2) API Programming

3) Import and Export Wizard

Here I am using the BIDS its a Graphical tool to create a packages, withoud need to write single line of code.

Open the new Project on Sql Server Integration Services.

Here is the steps to follow.

1. Create a new SSIS project in VS2005

2. Create a new data flow task - Double-click on the added task

3. Drag "xml source" from toolbox into data flow panel,Double Click on the XML

DataSource - a window opens select the xml file, and then generate XSD schema if not.

4. You could drag a "SQL Server detination" to the panel as data destination, connect XML source and SQL Server Destination, and use a new table.

Suppose if you getting Package Validation Error - Use the "data conversion" component in a data flow.
There may be the Datatype can be mismatched on Output columns. so at that time you can directly change the Datatype follow the below steps.

1. Right click the XML source->Show Advanced editor->Input and Output properties

2. Expand inputname->External Columns->Column name

3. On right panel, try to change the Datatype directly.

OR you could use "data conversion" component to convert the field that does not have the proper data type.
Finally if you check the DB it contains the New Table with the column Name and  its all Data available in the xml file.

Ref:

Validate Checkbox and Checkboxlist in easy way

Posted by Venkat | Labels: , ,

Hi Good Evening Techies.

I saw the post that has been asked number of times ie: how to validate the Checkbox and checkboxlist
so we can validate the Both of this using the Javascript or JQuery , but here I am going to make it much more easy ie: 4guysformula Provides the Control which can added to our toolbox then you can work these similar to the other validation Control

Validation Control for Checkbox and Checkboxlist

Go to the page down - Get the control ie: dll file ie: skmvalidators.dall place the file on Bin Folder of your project then add the dll file to your toolbox. then drag and drop to your aspx page & set some property thats it.

Alternatively Download the file here skmValidators.rar

AjaxHoverMenuExtender with ASP.NET

Posted by Venkat | Labels: ,

Today i am going to discuss, how to use AJAXHoverMenuExtender with ASP.NET. There are javascript available for onmouseover function which shows some text or something like menus. Today I am going to implement the same on serverside by using ajax functionality. There are number of tools available with ajax for our requirement I am going to use AjaxHoverMenuExtender - it show the menus or some text onmouseover of control or image or text.

First Create AjaxEnabled Website - so it automatically include AJAX Controls on your toolbox.

Place the ScriptManager on your page.
 <ajax:ScriptManager ID="ScriptManager1" runat="server">
        </ajax:ScriptManager>

Then Drag the Hyperlink and AjaxHoverMenuExtender on the Design page.
<asp:HyperLink ID="Hyperlink1" runat="server" Text="Session Mode"               NavigateUrl="~/Description.aspx"></asp:HyperLink>

 <ajaxToolkit:HoverMenuExtender ID="hme2" runat="Server" TargetControlID="Hyperlink1"
            PopupControlID="Panel1" PopupPosition="Center" OffsetX="-25" OffsetY="15"
/>

Main Properties of AjaxHoverMenuExtender

TargetControlID - Specify the server ControlID where you going to show the popup text.

PopupControlId -  Specify the ControlD which shows the popup while onmouseover of the

text of link.

PopupPosition - Center , Left , Right .

OffSetX , OffSetY - specify the X and Y position on that page according to the parent
Control.

Now i have to define the PopUp so this will be shown while mouseover.So here I used the panel which contains Datalist inside Where I bind the data from DB.

<asp:Panel ID="Panel1" runat="server" Width="600px">
            <asp:DataList ID="Dtl_Unit" CellPadding="1" CellSpacing="1"
ShowHeader="False" BorderWidth="0px"
                runat="server" DataKeyField="ServicesSubId" DataSourceID="Sqd_Unit" 

RepeatColumns="5">
                <ItemTemplate>
                    <table border="0">
                        <tr>
                            <td>
                                     <asp:HyperLink ID="Hyperlink2"  runat="server" 

NavigateUrl='<%#"Description.aspx?SId="+Eval("sessionmodeID") %>'
Text='<%#Eval("sessionmodeName")%>'></asp:HyperLink>
                            </td>

                        </tr>
                    </table>
                </ItemTemplate>
                <ItemStyle BorderWidth="0px"  />
            </asp:DataList>
            <asp:SqlDataSource ID="Sqd_Unit" runat="server" ConnectionString="<%$ 

ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT [sessionmodeID], [sessionmodeName] FROM 

[SessionTable]">
            </asp:SqlDataSource>
        </asp:Panel>

Output:

Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page.

Posted by Venkat | Labels:

When i faced this issue

Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page.

I fixed it by putting my Databind  code ie: Gridview Databind code in the Page_Load event in a !Page.IsPostBack block

Solution:

if(!IsPostback)

{
//Bind the Gridview Databind
}

Show Online Username

Posted by Venkat | Labels: ,

Now I am going to discuss, how to show who is online on my site - showing the Online Username , We know already how to show the Number of users online using Application Variables on Global.asax file.

But here i am going to show the online usersName.So, In my case i used Login Control and implement SecurityMembershipProvider and Roleprovider.Whenever the user Login - the LastAcivityDate field in the Users table will be updated with Current DateTime. The code has written on the SecurityMembership Provider.

When the user navigating the page ie: OnPostback the page - LastActivityDate will be Updated automatically, this will make sure the userName was active on the site.

if i say Simply it will show the online Username for the last 15 Minutes.

Code-behind:

// here getting the 15 Minutes, if you want the time difference you use it here..ie: to // update the your page at regular intervals.
TimeSpan onlineSpan = new TimeSpan(0,15,0);
// here i minus the 15 Minutes from the Current Datetime and pass it as a parameter
            DateTime compareTime = DateTime.Now.Subtract(onlineSpan);
            using (SqlCommand cmd = new SqlCommand("SELECT users.username from users where users.LastActivityDate > @CompareDate ", con))
{
            cmd.Parameters.Add("@CompareDate", SqlDbType.DateTime).Value = compareTime;
            using(SqlDataAdapter adap = new SqlDataAdapter())
            {
            adap.SelectCommand = cmd;
            }

}          
            DataTable dt = new DataTable();
            adap.Fill(dt);
            OnlineuserList_GridView.DataSource = dt;
            OnlineuserList_GridView.DataBind();

Creating Dynamic Controls

Posted by Venkat | Labels: ,

Good Day to All.

When i came across one issue ie: while creating a dynamic control ie: Dropdownlist on my case , if i choose some value on Dropdownlist onClick of the button i want the selected value that has to be stored in Database. But on postback the Control is not visible.

so here i am going discuss how to create a dynamic control , onpostback how to retain  its value. its just simple ie: Re-Create the Dynamic Control OnPostback so it will retain the selectedvalue.

HTML Code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="True" OnRowDataBound="GridView1_RowDataBound">
        <Columns >
        <asp:TemplateField >
        <ItemTemplate >
        <table >
        <tr>
        <td>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        </td>
        <br />
        <td>
         <asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
        </td>
        <br />
        
        <td>
         <asp:PlaceHolder ID="PlaceHolder3" runat="server"></asp:PlaceHolder>
        </td>
        </tr>
        </table>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>

   <asp:Button ID="Button1" runat="server" Text="Get Value" OnClick="Button1_Click"  />


So here in Gridview i am going to create a dynamic control on page_Load.
so i am placing the Placeholder to hold the Control. Its a Container for that controls.

Code-Behind

private void BindArraylist()
    {
        List<string> bindG = new List<string>() ;
        bindG .Add ("Mani");
        bindG .Add ("Shivaram");
        bindG .Add ("Gopi");
        bindG.Add ("Venu");
        GridView1 .DataSource = bindG ;
        GridView1 .DataBind ();
     
    }
//page_OnLoad

 if (!Page.IsPostBack)
        {
            
            BindArraylist();
        }

//On Row databound we are creation a dynamic dropdownlist, by adding some items and added to the Placholder Container

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            PlaceHolder p1 = new PlaceHolder();
            PlaceHolder p2 = new PlaceHolder();
            PlaceHolder p3 = new PlaceHolder();

            p1 = (PlaceHolder)e.Row.FindControl("PlaceHolder1");
            p2 = (PlaceHolder)e.Row.FindControl("PlaceHolder2");
            p3 = (PlaceHolder)e.Row.FindControl("PlaceHolder3");

            DropDownList d1 = new DropDownList();
            DropDownList d2 = new DropDownList();
            DropDownList d3 = new DropDownList();
            d1.ID = "d1";
            d1.Items.Add("123");
            d1.Items.Add("00");
            d1.Items.Add("dfgdf");
            d2.ID = "d2";
            d2.Items.Add("34f");
            d2.Items.Add("h456");
            d2.Items.Add("ngfy3e35");
            d3.ID = "d3";
            d3.Items.Add("3478");
            d3.Items.Add("0fghdj0");
            d3.Items.Add("2d43g5gh5");

            p1.Controls.Add(d1);
            p2.Controls.Add(d2);
            p3.Controls.Add(d3);
      }
}

Write the code onButton_Click to get the selected value, before that i am calling the bindArraylist method again to re-Create dropdownlist control.


protected void Button1_Click(object sender, EventArgs e)
    {
        BindArraylist();
        foreach (GridViewRow row in GridView1.Rows)
        {
        
            DropDownList d1 = new DropDownList();
            DropDownList d2 = new DropDownList();
            DropDownList d3 = new DropDownList();

            d1 = (DropDownList)row.FindControl("d1");
            d2 = (DropDownList)row.FindControl("d2");
            d3 = (DropDownList)row.FindControl("d3");
            //txtValues.Add(d1.SelectedIndex.ToString());
  
            Response.Write(d1.SelectedValue.ToString() + "-" + d2.SelectedValue.ToString() + "-" + d3.SelectedValue.ToString());
        }
    }

Sys.WebForms.PageRequestManagerServerErrorException

Posted by Venkat | Labels:

When i was worked with Ajax with timer Control i have the task ie: updating the some control inside the UpdatePanel ie: I am refreshing or call the method  at regular intervals. That time i got this error

 Sys.WebForms.PageRequestManagerServerErrorException ... 404 not found

This error occurs only when the page is idle for 1 min or more than 1 min, so i googled to get the solution for this issue. there is number of solution available according the problem and at which situation you are using.

Solution: 

< asp:ScriptManager ID="ScriptManager1" runat="server"   EnablePartialRendering="false" />

Creating Windows Service using ASP.NET

Posted by Venkat | Labels: , ,

Good morning to All

Now I am going to explain how to Create a windows Service in asp.net

What is the purpose of Creating windows service in asp.net ?

For ex: if you have the task of Sending birthday email to the members Automatically or  you are going to do some manipulation on particular day or do some manipulation on Consecutive intervals so at this situation you can go for Window service or even you can do birth email process through Sql Job Scheduling.

Now see how to create a simple service.

Choose Create Project -> VisualC# -> Windows -> Windows Service

Fig 1:


So once you give the windowService Name it will show this - by default the serviceName is Service1 here i am changed to TimerService.

Fig 2:



Then Right Click on Service - Select -> Add Installer

Fig 3:


Then the ProjectInstaller window show two Services like serviceProcessIntaller1 , serviceInstaller1 so you have to change some Properties for this service

Properties of serviceProcessIntaller1

Account - > there are some 4 types of account are there as per the requirement

1) LocalService - for only particular computer

2) Network Service - to access resource on remote side ie: server

3) Local System - to works on local System

4) User - Based on User credentials

For Brief Description Check it :

http://technet.microsoft.com/en-us/library/ms143504.aspx

Fig 4:


Properties of serviceInstaller1

StartType :

1) Automatic

2) Manual

3) Disabled

You have to specify whether you are going to start this Service Manually or Automatically or Disabled the Service.then give the name for ServiceName Property , And give some Name for DisplayName property - this name will be displayed on your servicelist to identify your Service.

Fig 5:


Now we going to write the code for Service on Service1.cs

by default it has OnStart and OnStop Event - so this event occurs when service start and stop.

using System.Timers;

Add timer to do some manipulation on particular intervals

  //Initialize the timer
Timer timer = new Timer();

so here is the code - what i am doing is create a method called AddToFile where i am adding the string to the file ie: on C Directory if the file is present it will write it on  or it will create a new file with the specified name and write the content on that file.

And onStart Event i am creating the Timer Elapsed event which called at every 1 minute so their i am adding another entry on that event.

Finally onStop Event i set the timer enabled = false and made last entry ie: Service stopped.

protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            //add line to the file
            AddToFile("Make starting service");

            //ad 1: handle Elapsed event
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

            //ad 2: set interval to 1 minute (= 60,000 milliseconds)
            timer.Interval = 60000;

            //ad 3: enabling the timer
            timer.Enabled = true;
        }

  protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            timer.Enabled = false;
            AddToFile("Make stopping service");
        }

  private void AddToFile(string contents)
        {

            //set up a filestream
            FileStream fs = new FileStream(@"c:\timelog.txt", FileMode.OpenOrCreate, FileAccess.Write);

            //set up a streamwriter for adding text

            StreamWriter sw = new StreamWriter(fs);

            //find the end of the underlying filestream

            sw.BaseStream.Seek(0, SeekOrigin.End);

            //add the text
            sw.WriteLine(contents);
            //add the text to the underlying filestream

            sw.Flush();
            //close the writer
            sw.Close();
        }
        private void OnElapsedTime(object source, ElapsedEventArgs e)
        {
            AddToFile("Make Another entry");
        }

so once you written the code just press F5 to run it show this dialog

Fig 6:

so you can start the service to start the service you have to install installutil.exe through commandline.

so go to Command Prompt on this Path.

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

From here you have to install the service , once you compile the project exe file is created on bin folder.

here is the step to install the Service

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727: InstallUtil "F:\WindowsService1\bin\Debug\WindowsService1.exe"

so if you press enter. Service will be installed.

To UnInstall The service follow this line

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\: IntsallUtil  /u"F:\WindowsService1\bin\Debug\WindowsService1.exe"

Once the Serice is installed it will be available on your Service list To check this follow this one

Start -> Control Panel -> Administrative Tools -> Services -> then find the Service as you given while creating the windowsService ie: DisplayName : TimerService

Fig7:



so if you set the Startup Type - Automatic - the service started when the System boots, you can also start the service Manually Right Click on the Service -> start. to start the service.

After the start the service check the C:\ Directory - you can check the file with the entry.

Happy Coding.


Enhanced by Zemanta

Compress and Cache the CSS and JS file using ASP.NET

Posted by Venkat | Labels: ,

HTTPCombiner
Credit goes to : http://code.msdn.microsoft.com/HttpCombiner

In my last article i have discussed how to compress .aspx pages. Now we are going to see how to compress the Javascript and CSS file.

Once the JS and CSS file is requested to the server and has been Cached. On next time You get it from Cache.If i have 10 Javascript file and 10 Stylesheets , every time when you request the page - each time it requested the server for JS and CSS file ie: 10 request to server for CSS and 10 request to Server for JS, to avoid the issue we have to combine all the CSS as one file and all JS as one file. Therefore only one request is sent to the server to get the JS file so totally two request has been sent to the server one for JS and CSS.

There is some JS and CSS compressor tools available for free, these tools will compress or minify your JS or CSS file this is the one waybut we have to do manually.

If you want to compress the file at runtime, here i am using HTTPCombiner to make the all the CSS as 1 CSS and all the JS and 1 JS file.

It has one file ie: HTTPCombiner.ashx - to Compress the CSS and JS file.Place the file on your project.
Add these two line to include all your Css and Js file on your appSettings tag on your web.config, You can get the file name using key part of the appSettings.

<add key="Set_Css" 

value="App_Themes/Default/Css1.css,App_Themes/Default/Css2.css"/>
  <add key="Set_Javascript" 
value="Javascripts/Js1.js,Javascripts/Js2.js,

http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>

After that you have to give the cSS and JS path on the Page1.aspx.

<link   type="text/css" 
            rel="Stylesheet" 
            href="HttpCombiner.ashx?s=Set_Css&t=text/css&v=1" />

    <script     
        type="text/javascript" 
        src="HttpCombiner.ashx?s=Set_Javascript&t=type/javascript&v=2" >
    </script>

Thats all, now you upload the file to server and check the JS,CSS file compressed (check the file length before and after applying this technique) using Fiddler tool or any other tools.
These are some tools to check Page response time.

http://www.aptimize.com/
http://websiteoptimization.com/services/analyze/
http://www.fiddler2.com/

Compressing Asp.Net Pages

Posted by Venkat | Labels: ,

Good Evening to All.
Here I am going to cover how to compress the .aspx pages.
so there are no.of ways to compress the pages in asp.net
1) using IIS.
2) using Code ie: through HTTPCompress.dll i got the source code from codeproject.com.
so i am going to share with you.
There are two type of Compression ie: Deflate , GZIP. here i am going to use GZIP compression to compress the asp.net pages.
First Place the DLL file ie::HTTPCompress.dll to the Bin folder of your project.
Then you have to include some tag on web.config file

<configsections>
  <sectiongroup name="Flanders">
   <section name="HttpCompress" type="Flanders.Library.Modules.HttpCompress.Configuration, HttpCompress">
  </section>
 </sectiongroup>
<flanders>
  <httpcompress compressiontype="GZip">
   <excludedpaths>
    <add path="NoCompression.aspx">
   </add>
   <excludedmimetypes>
    <add mime="image/jpeg">
   </add>
  </excludedmimetypes></excludedpaths>
</httpcompress>
</flanders>
</configsections>
Here i am using GZiP Compression technique. there are two more inner Tags ie: ExcludePaths, ExcludeMimeTypes.
ExcludePaths - It includes the Page Name that don't want to compress.
ExcludeMimeTypes - Include the mime types that dont want to compress the images..
By default images are compressed so no need to compress the image while using compression so our ExcludedMimeTypes tag should be like this.

<excludedmimetypes>
  <add mime="image/jpeg">
  <add mime="image/jpg">
  <add mime="image/png">
  <add mime="image/gif">
</add>
</add>
</add>
</add>
</excludedmimetypes>
Finally we need to add the httpModules

<httpmodules>
   <add> name="HttpCompressModule" type="Flanders.Library.Modules.HttpCompress.HttpModule,HttpCompress"/>
 </add>
</httpmodules>
Download Source Code

Credit goes to :
Ref: http://www.codeproject.com/KB/aspnet/HttpCompress.aspx

Postback not works when using HTTPCompression

Posted by Venkat | Labels: , ,

Some members asked this question on forums. Here is the Solution to overcome this issue.

When i am going to compress the .aspx pages using HTTPCompression, the postback will not works. Because it also compressing the Scripresource.axd, webresource.axd file.

To make the postback works in your project you do not compress the above two files, by adding these code.

Solution:

........,

<httpcompress compressiontype="GZip">
 <excludedpaths>
 <add path="scriptresource.axd">
 <add path="webresource.axd">
</add>
</add>
</excludedpaths></httpcompress>


And one more thing don't compress the images like jpg, gif, jpeg etc.. because its already compressed one. if you compress the image it will degrade the performance. you should the exclude the image from compression.

Solution:

..,
<excludedmimetypes>
 <add mime="image/jpeg">
 </add>
 </excludedmimetypes>

Thanks to all.

Convert String to DateTime using ASP.NET

Posted by Venkat | Labels: , ,

I saw the question repeatedly asking on forums ie: how to convert the String to datetime.

even if someone give solution still the problems exists..,

Error: String is not recognized as a valid DateTime.

Here i am giving the solution to overcome the problem.

First make sure whether you entered is a valid date or not because User may enter alphabets, special symbols etc.. so in order to avoid that , I have to validate the textbox. Here i am using the Regex to to validate the date.

This is my Article to vaildate date using Regex

try
{
 string sDate ="06/05/2010";
// this the regex to match the date ie: dd/MM/yyyy
 string _dateExpression = @"^((0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](?:19|20)\d\d)$";
 Regex chkDate = new Regex(_dateExpression);
 if ((chkDate.IsMatch(sDate))
 {
 // so if the date is valid and its matched you can store the date on DB or do some manipulatio.
 }
 else
 {
 // show invalid date
 }
}
 catch (System.FormatException ex)
 {
 // show invalid date
 }
catch(Exception ex1)
{
throw;
}

So if the user enter other than numbers it shows format exception to avoid this exception. once i caught the FormatException i am showing the Message to user ie:- input is not valid date or something.

Another small manipulation on DateTime

DateTime sDate = new DateTime();

sDate = DateTime.Today; //  Here i am getting like this 5/6/2010

// So i want this format 05/06/2010  - for this i am using Format to Convert the Date as i Want.

string gDate = String.Format("{0:dd-MM-yyyy}", sDate);

Thanks to All.

Sending Email Asynchronously

Posted by Venkat | Labels: , ,

Good Morning to Everybody this is my First article.
Now i am going to see how to send email Asynchronously, actually we send email normally using asp.net Example check here..
Send Email Using ASP.NET

By default smtpClient has one method called SendAsync to send an email ansynchronously. so if you sending an email normally it will take some time for each mail sent. But if you send an email Asynchronously it will not wait for each mail sent it will do the other process , while mail sending is done at background process.
So Here is the code.

//creating mail message object
 MailMessage mailMessage = new MailMessage();
 mailMessage.From = new MailAddress("venkat@gmail.com");
 mailMessage.To.Add(new MailAddress("msdotnettechies@gmail.com"));
 mailMessage.CC.Add(new MailAddress("user1@gmail.com"));
 mailMessage.Bcc.Add(new MailAddress("user2@gmail.com"));
 mailMessage.Subject = "Email Checking Asynchronously";
 mailMessage.Body = "Email test asynchronous";
 mailMessage.IsBodyHtml = true;//to send mail in html or not

 SmtpClient smtpClient = new SmtpClient();//portno here
 smtpClient.Host = "smtp.gmail.com";
 smtpClient.EnableSsl = true ; //True or False depends on SSL Require or not
 smtpClient.Credentials = new NetworkCredential("yourGmail@gmail.com", "yourpassword");
 //smtpClient.UseDefaultCredentials = true; //true or false depends on you want to default credentials or not
 Object mailState = mailMessage;

 //this code adds event handler to notify that mail is sent or not
 smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
 try
 {
 smtpClient.SendAsync(mailMessage, mailState);
 }
 catch (Exception ex)
 {
 Response.Write(ex.Message);
 Response.Write(ex.StackTrace);
 }

// this is the event called on main method
void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
 {
 MailMessage mailMessage = e.UserState as MailMessage;
 if (e.Cancelled || e.Error != null)
 {

 Response.Write(e.Error.Message);
 Response.Write(e.Error.StackTrace);
 }
 else
 {
 Response.Write("Email sent successfully");
 }
 } 
 

Ref :  http://jalpesh.blogspot.com/2010/02/how-to-send-mail-asynchronously-in.html

Sams Teach Yourself ASP.NET 3.5 in 24 Hours, Complete Starter Kit How to Train Your DragonHarry Potter Box Set

Logout issue : Copy the URL of the user page and paste user after logout show the page only IE has Issue

Posted by Venkat | Labels: , ,

When i working on the project ,i faced the issue - that i am sharing to u. ex: When the user login in to his account then do some navigation inside User page - at this stage I copied the URL then i Click Logout button. 

Once i logged out if i paste the Copied URL on that page it redirect to the user Page, when i do some navigation (or clicking any button on that page ) its has been redirect to Login page , but this should not occur  like this if i paste the URL it will directly redirect to the Login page only.This issue will not occur on Mozilla , IE 8 version. it occurs only on IE  browser.

Even if  I set the Session on page_load event but no use. So the thing is Cache ie: the page has been cached stored on Client Browser, so we need to disable the cache.

So Add this line on Master Page inside the Head Tag.

 <meta http-equiv="PRAGMA" value="NO-CACHE"></meta>
<meta content="Mon, 01 Jan 1990 12:00:00 GMT" http-equiv="Expires"></meta>



 
 

uploading text and numeric data from an excel file shows NULL Value

Posted by Venkat | Labels: , ,

Good Morning to everyone

I was working with one of the project , where i had the task of uploading excel ie: Read the Excel data to Dataset ie: from DataSet I am going to store the each field value to DB, so the excel sheet may contain numbers ,or string ,.. by default the Excel sheet  accept  the data based on the first rows of excel sheet.

If the first row and first column will be string - so further the whole first rows and first columns accept strings, if there is any Numeric found  on the first rows and first columns it consider as NULL ie: Empty value , as the same for Numeric also so it may also contain alphanumeric on some cells.

So while we read the Excel sheet  these problems are arise. then we tried to select all cell ie: full excel sheet -> Right Click on the Excel sheet - > format Cells - > Choose String - > click ok .Then I upload this Excel sheet to Read the Data.

Why we change the Format cell  to String means if we set it as string it will accept as both numeric , strings , or alphanumeric - so i am going end it up by doing this.

But the problem arises again - it works that time correctly after few day the same problem occurs, then i do some research or googled and came up with a solution :

The short answer is "IMEX=1" 

You have to apply this on Connection String

To connect to an excel file within ADO.NET use the "System.Data.OleDb" provider  a connection string similar to:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Sample.xls";Persist Security Info=False;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1" 

 Thanks for All. 

 

window.open method

Posted by Venkat | Labels: , ,

Window.open method in asp.net - this is used in javascript to open a page on new window.
through this you can hide the menubar ,set the width and hieght of the popupwindow,status,toolbar,resizable etc., for this you can either set the value is 0 | 1 or yes | no

Example

window.open('http://msdn.microsoft.com', '', '');");

Suppose if you want to do on code behind check this code :

Here i have mentioned widht , height of the window ,top and left , menubar,toolbar,
location, resizable, scrollbars
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language="javascript">");
sb.Append("window.open('popuop.aspx', 'CustomPopUp',");
sb.Append("'width=1020, height=750, left=0, top=0, menubar=no, toolbar=no, resizable=no, status=no, location=no, scrollbars=yes');<");
sb.Append("/script>");
Type t = this.GetType();
if (!Page.ClientScript.IsStartupScriptRegistered(t, "PopupScript"))
{
     Page.ClientScript.RegisterStartupScript(t, "PopupScript", sb.ToString());
 }


If you want to open a new window through in-line code try this.

   <img border="0" id="img_PopUp" onclick="window.open('../PopUp.aspx','custompopop','width=250,height=300,toolbar=no,menubar=no,statusbar=no,resizable=no,scrollbars=no,location=no, directories=no,copyhistory=no,left=250,top=250')" />
                                runat="server" src="../Images/Newwindow.png" style="width: 35px" />

Reference:


http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx

Arithmetic Captcha

Posted by Venkat | Labels: , ,

In this post i am going to show how to work with Arithmetic CAPTCHA. Generally we used , Alpha or alphaNumeric Captcha on most of the site but some site like  ASP.SNIPPETS it shows ARITHMETIC CAPTCHA like 18 + 12 = ? so user have to give correct value then only it proceeds.

Here I am getting help from this site

http://www.knowlegezone.com/documents/80/Simple-ASPNET-CAPTCHA-Tutorial/

Which was in VB.NET so I would like to Written in C#, here I have been posted , On the Above link they used normal ASPX image to Generate the Image ie: 18 + 12 = .

So i written the code on Generic Handler File to improve the site performance.
By default Handler file does not Read or write the value to Session so we have to use like this

using System.Web.SessionState;

public class Captcha : IHttpHandler, IRequiresSessionState


suppose if we are going to read the Session value on HTTP Handler file

using System.Web.SessionState;
public class Captcha : IHttpHandler, IReadOnlySessionState

This is the full code for Captcha.ashx file

<%@ WebHandler Language="C#" Class="Captcha" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class Captcha : IHttpHandler, IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        Random num1 = new Random();
        Random num2 = new Random();
        int numQ1 = 0;
        int numQ2 = 0;
        string QString = null;
        numQ1 = num1.Next(10, 15);
        numQ2 = num1.Next(17, 31);
        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        int tAnswer = numQ1 + numQ2;
        context.Session["answer"] = tAnswer .ToString ();
        Bitmap bitmap = new Bitmap(85, 25);
        Graphics Grfx = Graphics.FromImage(bitmap);
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);
        Rectangle Rect = new Rectangle(0, 0, 100, 25);
        Grfx.FillRectangle(Brushes.Snow, Rect);
        Grfx.DrawRectangle(Pens.White, Rect);
        // Border
        Grfx.DrawString(QString, font, Brushes.Black, 0, 0);
        context.Response.ContentType = "Image/jpeg";
        bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bitmap.Dispose();
        Grfx.Dispose();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Here is the code if you are going to write it on Captcha.aspx page

Explanation was given on Comment itself. Write the below code on Page_Load Event

// Getting Random number
        Random num1 = new Random();
        Random num2 = new Random();

        int numQ1 = 0;
        int numQ2 = 0;
        string QString = null;

        // here we get the random number for the first and second numer - ie: shows the number in between the range.
        numQ1 = num1.Next(10, 15);
        numQ2 = num1.Next(17, 31);

        //Total answer has been  stored it on String and assign to the Session["number"]
        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        Session["answer"] = numQ1 + numQ2;

        // Here we create  Bitmap width - 85 and height - 25
        Bitmap bitmap = new Bitmap(85, 25);
        Graphics Grfx = Graphics.FromImage(bitmap);

        // Setting the font name, size etc for the text that we have to write it on the image
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);

        // Here we specify  a Rectangle object of x , y co-ordinate , with width and height 
        Rectangle Rect = new Rectangle(0, 0, 100, 25);

        //Fill the color to the Rectangle
        Grfx.FillRectangle(Brushes.Snow  ,Rect);

        // Now Using Pen Object Drawing a rectangle
        Grfx.DrawRectangle(Pens.White, Rect);

        // Border - here drawing the string of the num1 and num 2, font size , type etc, font color , and x and y co-ordinate
        Grfx.DrawString(QString, font, Brushes.Black   , 0, 0);
        // Specify the Content type of the image - here i am using JPEG
        Response.ContentType = "Image/jpeg";

        // Save the image and show it on page using response object
        bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

        //Dispose the object and release the resources
        bitmap.Dispose();
        Grfx.Dispose();

Google Custom Search

Posted by Venkat | Labels: , ,

Google Custome Search

Google provider Custom search - that can be integrated to our own site - to searh a text,keywords
inside our site.

This is the link go Through and add to your site.

http://code.google.com/apis/customsearch/docs/ui.html

Fetch DB to Xml then bind to Asp.net Server control

Posted by Venkat | Labels: , ,

Today I am going to see how to bind or get the Data from the DB to XML file. so XML is also a
Datasource to store the data or content and you can get the data from xml file easily,it also
improves server performance. ie: instead of creating connection and request the DB to fetch the data
, Getting the Data , Closing Connection. so this operation occurs multiple times or as per
user needs.

Now what i am doing here is , first get the Table Data From DB to the XML file.
first i had created one xml file called Test.xml - to place the Employee Tables Data.

Then OnButton_Click Event i have written the code to bind the data to XML file.

Ex: i am getting the Employee Table from DB bind to the XML file.

Here is the Code :

Include Namespace

using System.IO;
using System.Data.SqlClient;


protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand command = new SqlCommand();
        command.CommandText = "Select * from Employees";
        command.CommandType = CommandType.Text;
        command.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        da.Fill(ds, "Emp");
       
        // Get a StreamWriter object
        StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/Test.xml"), false);

        // Apply the WriteXml method to write an XML document
        ds.WriteXml(xmlDoc, XmlWriteMode .WriteSchema );
        xmlDoc.Close();

       
    }
After that - i am going to bind the all the employeename and empid to the Dropdownlist.

Here is the Code : so we get the emp details on the XML file , we have to retrieve the data
from the XML file using Dataset because - Dataset has two method ReadXML and WriteXML ie: able
to read or write the data from the XML.

so after read the data from XML to Dataset, now we have all the emp details on the Dataset ds,
. just bind as its to the Dropdownlist datasource.


 DataSet ds = new DataSet();

 ds.ReadXml(Server.MapPath("~/Testdo.xml"));

DropDownlist1.DataSource = ds;
DropDownlist1.DataTextField = "empname";
DropDownlist1.DataValueField = "empid";
DropDownlist1.DataBind();
suppose i want to filter the employees whose salary is greater than 20000

write like this

dt = ds.Tables[0];
  DataRow[] dr ;
        dr = dt.Select("salary >= '20000'");

 DataTable fDt = new DataTable();
        fDt.Columns.Add("empName");
        fDt.Columns.Add("empId");

 foreach (DataRow dr1 in dr)
        {
            DataRow newrow = fDt.NewRow(); 
            newrow[0] = dr1[0];  // here you have to give correct index for the empid or empname field name
            newrow[1] = dr1[1];
           

            fDt.Rows.Add(newrow);
        }

dropdownlist2.DataSource = fDt;
DropDownlist1.DataTextField = "empname";
DropDownlist1.DataValueField = "empid";
DropDownlist1.DataBind();

Creation Tooltip

Posted by Venkat | Labels: , ,

Good Friday to all.

Now i am going to show how to create  a Tooltip using Javascript there are many scripts,JQuery available to make the work easy and even we can design the tooltip stylish manner.

But finally i have worked with this sample , it shows tooltip , when u click on the Textbox - you can give your own font color, backcolor.

Here is the link Check it

http://lixlpixel.org/javascript-tooltips/

And its a dynamic tool tip..

http://blog.devarchive.net/2008/04/advanced-tooltip-control-aspnet-ajax.html

Here is the Screenshot

How to Create Nifty Round corner

Posted by Venkat | Labels: , ,

I have situation Create a Roundcorner for the table or div or panel ...
So in Ajax there is a built-in-control - RoundCornerExtender is available , but i have used that but i was not showing the round corner sometimes properly.

so i found this Nifty round corner was the good one, no image needed for the Round Corner.

Its full javascript., you can apply the round corner to div,panel,table etc..

Here is the Sample code

First you have to add Javascript on your page. You can get the javascript here ie: niftycube.js and niftycorner.css.

http://www.html.it/articoli/nifty/index.html

http://www.html.it/articoli/niftycube/index.html

You have to write code like this

if you use id use (#) , if you are going to use it for class user (.)


<script type="text/javascript">
window.onload=function(){
Nifty("div#box","big");
Nifty("Panel#" + '<%= contactUs_Panel.ClientID %>',"transparent");
Nifty("Panel.setround","big");
Nifty("Panel#" + '<%= callback_Panel.ClientID %>',"transparent");
Nifty("table.setround","big");

//Nifty("PopupControlExtender","big");
}
</script>


Validate Indian Mobile Number

Posted by Venkat | Labels: ,

Hi , Now i am going to discuss about how to validate a Indian Mobile Number.

First the Mobile Number field should not be null so for that - Add RequiredFieldValidator.

It should not accept any Aplhabets , or any special characters for this you have to write RegularExpression Validator to Accept only Numbers
EX:

Regex \d+


Atlast i have to check whether user entered Number is 10 digit or not and also it should be valid Mobile Number
Regex ^[9][0-9]{9}$


This Regex which first digit should be 9 then followed by 9 digits and totally it accept only 10 digits.

Paypal Code - Validate Credit Card & CreditCard Payment through Website Payments Pro method

Posted by Venkat | Labels: , , ,

How to Validate the CreditCard in asp.net ??

To validate the CreditCard first you have to check the Card Type then followed by
the no.of digits..etc.. on that Specific Card type. here i am using Luhn Algorithm to validate.

So you have place these algorithm on Separate Class file ie: Create

CardValidator.cs on the App_Code Folder and paste the below code.

using System;

public enum CardType
{
    MasterCard, BankCard, Visa, AmericanExpress, Discover, DinersClub, JCB
};

public sealed class CardValidator
{
    private CardValidator() { } // static only

    public static bool Validate(CardType cardType, string cardNumber)
   {
      byte[] number = new byte[16]; // number to validate

      // Remove non-digits
      int len = 0;
      for(int i = 0; i < cardNumber.Length; i++)
      {
         if(char.IsDigit(cardNumber, i))
         {
            if(len == 16) return false; // number has too many digits
            number[len++] = byte.Parse(cardNumber[i].ToString ());
         }
      }

      // Validate based on card type, first if tests length, second tests prefix
      switch(cardType)
      {
         case CardType.MasterCard:
            if(len != 16)
               return false;
            if(number[0] != 5 || number[1] == 0 || number[1] > 5)
               return false;
            break;

         case CardType.BankCard:
            if(len != 16)
               return false;
            if(number[0] != 5 || number[1] != 6 || number[2] > 1)
               return false;
            break;

         case CardType.Visa:
            if(len != 16 && len != 13)
               return false;
            if(number[0] != 4)
               return false;
            break;

         case CardType.AmericanExpress:
            if(len != 15)
               return false;
            if(number[0] != 3 || (number[1] != 4 && number[1] != 7))
               return false;
            break;

         case CardType.Discover:
            if(len != 16)
               return false;
            if(number[0] != 6 || number[1] != 0 || number[2] != 1 || number[3] != 

1)
               return false;
            break;

         case CardType.DinersClub:
            if(len != 14)
               return false;
            if(number[0] != 3 || (number[1] != 0 && number[1] != 6 && number[1] 

!= 8)
               || number[1] == 0 && number[2] > 5)
               return false;
            break;

         case CardType.JCB:
            if(len != 16 && len != 15)
               return false;
            if(number[0] != 3 || number[1] != 5)
               return false;
            break;
        
      }

      // Use Luhn Algorithm to validate
      int sum = 0;
      for(int i = len - 1; i >= 0; i--)
      {
         if(i % 2 == len % 2)
         {
            int n = number[i] * 2;
            sum += (n / 10) + (n % 10);
         }
         else
            sum += number[i];
      }
      return (sum % 10 == 0);
   }
}

I have the task of payment method through paypal pro using Credit Card.i was

googled a lot with paypal site , fourms and came with the sample code.

The PayPal Name-Value Pair API (NVP API) enables you to leverage thefunctionality of the PayPal API by simply sending an HTTP request to PayPal and specifying request parameters using name-value pairs. The NVP API is a lightweight alternative to the PayPal SOAP API and provides access to the same set of functionality as the SOAP API.

Ref: https://www.paypal.com/IntegrationCenter/ic_nvp.html

Here i am usin NVP API for payment through CreditCard using website Payment Pro

Method , we can also use SOAP API for this we need to do

1)setExpressionCheckout

2) DoExpressionCheckout

3) GetExpressionCheckout.

Either we can use API or through Code. I am Registering on Sandbox.paypal to check the code. we have to create the Buyer , seller Account to check the amount has been transferred or not , so it will automatically create the creditcard no, cardtype for the test account, we have to use this to check the Amount Transfer
or not. While testing , the amount was not deducted on the buyer account but it will credited on Seller account  as this is sanbox test, this is not an issue ,while you upload it on live , it will work smoothly.As i was tested with Sandbox - so you can check it on live.

One of the main advantage of this method is , it will not redirect the user to paypal site,instead the process has been doing on background from the same site after successfull transaction it will give the Transactionid ,
act etc.. so you can store this thing on DB.


While page Designing make sure you have these Fields

1) Card Type

2) Textbox for CreditCard Number

3) Expire Date  / Expire Month

4) Pay button / Cancel button

paybutton_Click
try
        {
              bool validateCard = false;
              if (ddlCCType.SelectedValue.ToString() == "Visa")
              {
                  validateCard = CardValidator.Validate( CardType.Visa , 

txtCCNumber.Text);
              }
              else if (ddlCCType.SelectedValue.ToString() == "MasterCard")
              {
                  validateCard = CardValidator.Validate(CardType.MasterCard , 

txtCCNumber.Text);
              }
              else if (ddlCCType.SelectedValue.ToString() == "AMEX")
              {
                  validateCard = CardValidator.Validate(CardType.AmericanExpress, 

txtCCNumber.Text);
              }

            if (validateCard != false)
            {
                  string ipaddress;

                ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (ipaddress == "" || ipaddress == null)
                {
                    ipaddress = Request.ServerVariables["REMOTE_ADDR"];

                }
        Session["ipAddress"] = ipaddress;

         //API Credentials (3-token)

            string strUsername = "troy2._1261822640_biz_api1.gmail.com";

            string strPassword = "1261822646";

            string strSignature = 

"An5ns1Kso7MWUdW4ErQKJJJ4qi4-A60C4mgCoX2-L9FhwhF2rfGtRPeI";

            string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword 

+ "&SIGNATURE=" + strSignature;
        
            // For Sandbox testing use this API 
            string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";

            // Fpr Live Server use this API
            string strNVPLiveServer = "https://api-3t.paypal.com/nvp";

            string strAPIVersion = "2.3";

// here i am assigning the credit card type cardno,expiry date/month to
 //the session variable and pass it here 

                       string strNVP = strCredentials + 

"&METHOD=DoDirectPayment&CREDITCARDTYPE=" + Session["cardType"].ToString() + 

"&ACCT=" + Session["cardNo"].ToString() + "&EXPDATE=" + 

Session["expiryDate"].ToString() + "&CVV2=808&AMT=" + Amount_Label.Text + 

"&FIRSTNAME=" + FirstName_Label.Text + "&LASTNAME=" + LastName_Label.Text + 

"&IPADDRESS=" + Session["ipAddress"].ToString() + "&STREET=" + address1 + "+" + 

address2 + "&CITY=" + city + "&STATE=" + state + "&COUNTRY=" + country + "&ZIP=" 

+ zip + "&COUNTRYCODE=US&PAYMENTACTION=Sale&VERSION=" + strAPIVersion;

  //Create web request and web response objects, make sure you using the correct 

server (sandbox/live)

            HttpWebRequest wrWebRequest = 

(HttpWebRequest)WebRequest.Create(strNVPSandboxServer);

            ////Set WebRequest Properties
            wrWebRequest.Method = "POST";

            //// write the form values into the request message
            StreamWriter requestWriter = new 

StreamWriter(wrWebRequest.GetRequestStream());

            requestWriter.Write(strNVP);
            requestWriter.Close();

            //// Get the response.
            HttpWebResponse hwrWebResponse = 

(HttpWebResponse)wrWebRequest.GetResponse();

            StreamReader responseReader = new 

StreamReader(wrWebRequest.GetResponse().GetResponseStream());

            //// and read the response
            string responseData = responseReader.ReadToEnd();

            responseReader.Close();
            Response.Write(Server.UrlDecode(responseData));
               
            }
            else
            {
                validateCard_Label.Text = "Please check your card number...";
            }
            
            
          
        }
        catch (Exception ex)
        {
            throw ex;
        } 

Finally , once your Transaction is success you will get the output ie:TransactionID with ack

EX: Output

ACK=Success&TIMESTAMP=date/timeOfResponse
&CORRELATIONID=debuggingToken&VERSION=2.300000&BUILD=buildNumber
&TOKEN=EC-3DJ78083ES565113B&EMAIL=abcdef@anyemail.com
&PAYERID=95HR9CM6D56Q2&PAYERSTATUS=verified
&FIRSTNAME=John&LASTNAME=Smith...&AMT=15&TRANSACTIONID=24527936A38716

Invalid postback or callback argument.

Posted by Venkat | Labels:

I came across the post on Forums ie:

Invalid postback or callback argument.  Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation

To Solve this issue Make sure that you are using IsPostback on the Page_Load() event of that page.


 page_Load() event
If (!IsPostBack)
{
// bind the data
}

Check whether Querystring is available or not.

Posted by Venkat | Labels: ,

Now , i am going to explain how to check Whether the Querystring is present or available or not.

For ex: I am passing id as a querystring to the page2.aspx from page1.aspx.

So on Page1.aspx


Button1_Clickevent() Response.Redirect("page2.aspx?id=1",false); Then on Page2.aspx Page2_Loadevent() If(!IsPostback) {        If(!String.ISNullOrEmpty(Request.QueryString["id"]))         {               // get the value of Querstring id , if id is not null or empty         }        else if(!String.ISNullOrEmpty(Request.QueryString["name"]))         {              // get the value of name querystring if name is not null or empty         } }   When you run the above code - ie: on Page2.aspx you can get the id Querystring value. this works fine.   
Suppose if you pass some other querystring name ex: name from the Page1.aspx the above code gives
ie: Button2_Clickevent()
         Response.Redirect("page2.aspx?name=Dotnet",false);
Error : Object Reference Exception. 

Because it first check the  if condition so in the first condition it contains id so the querystring id will not present so it leads to the Null reference exception.


to avoid this exception you have to check like this.

Page2_Loadevent()
If(!IsPostback) {   if(Request.QueryString["id"] != null)     {        If(!String.ISNullOrEmpty(Request.QueryString["id"]))         {               // get the value of Querstring id , if id is not null or empty         }   } if ((Request.QueryString["name"] != null)   {         if(!String.ISNullOrEmpty(Request.QueryString["name"]))         {              // get the value of name querystring if name is not null or empty         } }  }
          This if(Request.QueryString["id"] != null)  - checks if id is a QueryString variable.

  If(!String.ISNullOrEmpty(Request.QueryString["id"]))  - Check if the id is empty or not

     

PayOffers.in