Showing posts with label .net tips. Show all posts
Showing posts with label .net tips. Show all posts

Tuesday, June 24, 2014

, , ,

Credit Card Validation Plugin in Jquery





Introduction





It's been a long time since my last post. In the last two months I was running through a hectic schedule, so could not publish anything here.



But this time I am here with my first ever JQuery Plugin and that's on Credit Card Validation.





While working with any payment gateway its an important thing to validate the correct credit card/debit card details. You may have developed an interface where the user has to give the credit card details like card no, cvv no, expiry date, name on the card. These fields need to be validated before processing towards the payment.








In order to validate the credit card details you may use the jquery or server side coding with the help of regex expressions, which is a time taking thing. So I thought of developing an efficient plugin which can create a nice looking interface along with the user friendly validations that can be consumed in any type of application. So here it is.






In this post we will see how this plugin works and how to use it in your application. You can download the plugin from the below link.






   Download Source Code Here




   


 



Behind The Scene































































**I have used bootstrap for design purpose, you can use it or not according to your project requirement.





Before entering into the plugin details lets know some basic things about the credit card number pattens. 





The first digit in your credit-card number signifies the system:



    3 - travel/entertainment cards (such as American Express and Diners Club)

    4 - Visa

    5 - MasterCard

    6 - Discover Card



The structure of the card number varies by system. For example, American Express card numbers start with 37; Carte Blanche and Diners Club with 38.




  •  American Express - Digits three and four are type and currency, digits five through 11 are the account number, digits 12 through 14 are the card number within the account and digit 15 is a check digit.

  •  Visa - Digits two through six are the bank number, digits seven through 12 or seven through 15 are the account number and digit 13 or 16 is a check digit.

  • MasterCard - Digits two and three, two through four, two through five or two through six are the bank number (depending on whether digit two is a 1, 2, 3 or other). The digits after the bank number up through digit 15 are the account number, and digit 16 is a check digit.




(Courtesy: http://money.howstuffworks.com)



Lets get into the coding things. Ok first of all we will see the user interface and design it for enabling the user to provide his/her card details for validation and further proceedings.




I have used Bootstrap to get a UI like this, You can use it or else you can not according to your requirement.



This is how our UI is going to look like. Don't you guys like it ? please share your valuable comments below to modify it.




UI for CC Validation


Before we can start you need to download the plugin first. If you have not till now then download it from below.


Download Source Code



Once you download and extract it you will find the below javascript files in the js folder.


  • jquery-1.7.1.min.js

  • ccvalidate-tapan.min.js


We will be needing the ccvalidate-tapan.min.js file for our validation thing and you can add a latest JQuery to your project too.




 In the css folder you will find the below css files 



  • bootstrap.css

  • Validation.css




Ok, Now lets jump into the coding part. Here is the HTML page how it looks like.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<link href="css/bootstrap.css" rel="stylesheet" />
<link href="css/Validation.css" rel="stylesheet" />
<script src="js/ccvalidate-tapan.min.js"></script>
<script>
$(document).ready(function () {
// Initiate CC Validation
InitiateValidation();

// For check valid invalid details
$("#btnValidate").click(function () {

if (ValidateForm()) {
alert('You have entered valid details...');
}
else {
alert('You have entered invalid details/skipped some fields...');
}
});
});

</script>
</head>
<body>
<div style="margin-top: 50px;" class="container">
<div class="row">
<div class="col-sm-5 col-xs-offset-3">
<div class="well">

<div class="row">
<div class="col-sm-12">
<label class="col-sm-12 control-label">Enter Card No.</label>
<div class="col-sm-12">
<input placeholder="4587-7834-6735-1930" id="1" class="form-control" filtertype="CCNo">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<label class="col-sm-12 control-label">Expiry Date (MM/YY)</label>
<div class="col-sm-12">
<input placeholder="12/20" id="3" class="form-control" filtertype="Date">
</div>
</div>
<div class="col-sm-4">
<label class="col-sm-12 control-label pull-right">CVV</label>
<div class="col-sm-12">
<input placeholder="454" id="3" class="form-control" filtertype="Number">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label class="col-sm-12 control-label">Name on Card</label>
<div class="col-sm-12">
<input placeholder="Tapan kumar" id="1" class="form-control" filtertype="CharacterAndSpace">
</div>
</div>
</div><br />
<div class="row">
<div class="col-sm-12">
<button id="btnValidate" class="btn btn-info col-sm-3 col-sm-offset-4 control-label">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>








If you look into the above code you will find that I am using an attribute named filtertype for the input fields, which is responsible for the validation.




Here is the attribute values I have used for validating your card details.



  • Credit Card No : filtertype = "CCNo"

  • Expiry Date :  filtertype = "Date"

  • CVV No : filtertype = "Number"

  • Name on Card : filtertype = "CharacterAndSpace"




These attribute values are used into validate your card details and prevent user from inserting invalid entries in the input fields. 





What you have to do is just to call 2 methods in JQuery in order to validate the card details. Find the script below.

    <script>
$(document).ready(function () {
// Initiate CC Validation
InitiateValidation();

// For check valid invalid details
$("#btnValidate").click(function () {

if (ValidateForm()) {
alert('You have entered valid details...');
}
else {
alert('You have entered invalid details/skipped some fields...');
}
});
});

</script>



The  InitiateValidation() method initiates the validation, and ValidateForm() method will return a boolean if the form is valid or not and you can perform your task accordingly. Here I am showing some alert if the details are correct or not in the click event of the submit button.



That's all for your validation to work out.




Plugin Features :





  • while inserting the card no it will automatically put a "-" in between 4 digits. 

  • It will not allow you put anything except numbers in the card input field.

  • It will show your card type at the right side of the text box.

  • Max length of the CCNo field is 19(including the "-"). 

  • In the Date field you wont be able to put anything except numbers and the field will not accept the first two digits greater than 12 as these two digits indicates the month.

  • Max length of the Expiry Date field is 6(including the "/").

  • Now the CVV no field will accept only 3 digits.

  • Finally the Name on Card field will accept a name, which should be at least of 3-4 characters.




Happy Coding...




Publisher: Tapan kumar - 7:07 AM

Thursday, March 27, 2014

, ,

Creating a Graph in ASP.NET with AJAX, HttpHandler and Morris.js Plugin





Introduction





Graphical representation is something that can make you understand every statistics without a mathematical calculation. It keeps the ability to represent the facts and figures in such a manner that you need not to give any pressure to your brain for calculations.





Lets take a simple example.




Consider yourself as an owner of a laptop selling company which sells thousands of laptops daily. As you are the owner of the company, you must have to keep track of your business if your sales volume is increasing day by day or decreasing. 





In order to keep track of your sales volume in a certain time period what you have to do ????


Yes, you will collect the facts and figure for a comparison and definitely for this comparison you need to do some calculations blah blah blah blah......





Here comes the concepts of Graph by seeing it only you will get a clear cut idea whether your business is growing or not.




Graph is the concept which will save your time, save the utilization of your brain and keeps you away from headache while analyzing a bunch of data.






So, Being a software developer it becomes an important part of development to get all the reports like user accounts, page hits, sales volumes etc. in a graphical representation, so that it will be very easy to understand what is actually happening in the background, and how the business is getting affected day by day.





Here in this article I will show you how to generate a light weight, nice looking Graph using Jquery and AJAX. If you surf in the internet you will get hundreds of plugins for generating Graphs. 




I will be using  morris.js for generating a nice looking graph. For more details about the plugin please visit their website.






   Download Source Code Here




   


Behind The Scene






In this example we will be using AJAX, JQURY along with HttpHandler in ASP.NET. So some basic idea on these topics will be highly appreciated.




You can download the above demo project for a quick demo.





Lets do this.





Front End Stuffs:





Add a new webform  to your solution (in visual studio). And add the below scripts to the header section of your page.


 <link rel="stylesheet" href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="http://cdn.oesmith.co.uk/morris-0.4.3.min.js"></script>



Now add a div to the body of your page with an id. Here I have given it an id of  "area-example" and put it blank.


 <div id="area-example"></div>

Ok, now we need to bind that div with our data in order to produce a graph. So here you go.....



Add the below script to the header section and I will explain it line by line.

    <script type="text/javascript">
$(document).ready(function () {

Morris.Area({
element: 'area-example',
data: Graph(),
xkey: 'label',
ykeys: ['value'],
labels: ['value']
});

});
</script>

Here in the above script I am trying to bind the div with a graph by calling the Morris.Area function and passing it some parameters.



For more details about Morris Charts you can visit their web.



Let me explain these parameters here we are passing.


  • element (mandatory) : This is the ID of the container where the graph will be rendered.

  • data (mandatory) : Here you can provide the data to bind your graph. It accepts data in JSON format. like
    [
    { label: '2012-10-01', value: 802 },
    { label: '2012-10-02', value: 783 },
    { label: '2012-10-03', value: 820 },
    { label: '2012-10-04', value: 839 },
    { label: '2012-10-05', value: 792 },
    { label: '2012-10-06', value: 859 },
    { label: '2012-10-07', value: 790 },
    ]


    Or you can call a function to get data from server side. Here I am using AJAX for getting data from server side through a HTTPHandler.

  • xkeys (mandatory) : A string containing the name of the attribute that contains
    date (X) values.The date format should be in "YYYY-MM-DD" format.

  • ykeys (mandatory) : A string containing the name of the attribute the value for (Y).

  • labels (mandatory) : A list of strings containing labels for the data series
    to be plotted (corresponding to the values in the
    ykeys option).


In our case the data attribute is calling a Javascript function named Graph(). And I am calling a HttpHandler through AJAX. Find the function below.


        function Graph() {
var data = "";

$.ajax({
type: 'GET',
url: "http://localhost:60539/GraphHandler.ashx",
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: { 'GraphName': 'line' },
success: function (result) {
data = result;
},
error: function (xhr, status, error) {
alert(error);
}
});

return data;
}

I am passing the HttpHandler url in the url attribute, and I am sending some data to the server of json type. You can find the dataType : 'json' and data: {'GraphName': 'line'} which I will be using in my handler.




And as you can see I am making this AJAX call synchronous by setting async attribute to false because I need the AJAX call to wait till the data was retrieved from the back end otherwise the graph will not be loaded.



* It is not recommended usually to make the AJAX call synchronous.



Once the call is completed and it get some data then inside the success attribute I am setting a variable and then at the end of the method returning it.



You need to put this method in script block we have created just before sometime.







Back End Stuffs:






Once the call is transferred to the handler you get the flexibility to use your coding ability to fetch data from server or whatever you want to do.



Here I will be using two classes named GraphData.cs to and GraphDataList.cs. Find the two classes below.

    public class GraphData
{
public string label { get; set; }
public string value { get; set; }
}

public class GraphDataList
{
public List<GraphData> ListOfGraphData { get; set; }
}

Find the below function that is responsible for fetching the graph data from the server. Basically this is a DAL function.

        public GraphDataList GetGraphData(string graphName)
{
GraphData graphData = null;
GraphDataList graphDataList = new GraphDataList();
graphDataList.ListOfGraphData = new List<GraphData>();

try
{
using (var con = new SqlConnection(connectionString))
{
con.Open();

SqlCommand cmd = new SqlCommand();
SqlDataAdapter SqlDadp = new SqlDataAdapter();

cmd.Parameters.Add("@ProgramID", SqlDbType.Int);
cmd.Parameters["@ProgramID"].Value = programID;

cmd.CommandType = CommandType.StoredProcedure;

using (IDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
graphData = new GraphData();

graphData.label = Convert.ToString(dataReader["Date"].ToString());
graphData.value = Convert.ToString(dataReader["AmountPaid"].ToString());

graphDataList.ListOfGraphData.Add(graphData);
}
dataReader.Close();
}
}
}
catch (Exception ex)
{
Logging.LogError(ex);
}

return graphDataList;
}

As you can see in the this method I am calling a stored procedure and binding the GraphDataList with the returned values. Finally it returns the graphDataList.



Now we need to call this method from ProcessRequest method of the HttpHandler.



Here is the code for ProcessRequest method.

        public void ProcessRequest(HttpContext context)
{
System.Collections.Specialized.NameValueCollection forms = context.Request.Form;

string chartName = context.Request["GraphName"];

DataAccessLayer Dal = new DataAccessLayer();

int programID = 1;

if (!string.IsNullOrEmpty(chartName))
{
GraphDataList graphList = new GraphDataList();

switch (chartName)
{
case "line":
graphList = Dal.GetGraphData(chartName);
break;
case "donut":
graphList = Dal.GetGraphData(chartName);
break;
}

//oper = null which means its first load.
var jsonSerializer = new JavaScriptSerializer();
string data = jsonSerializer.Serialize(graphList.ListOfGraphData);
context.Response.Write(data);
}
}

As you can see I am retrieving the parameter I have passed from AJAX, from the context.Request. Then we are almost done.



Just call the GetGraphData(chartName) with the graph name and hold the returned data in a list, we just created before 2-3 minutes ago.



We are just 1 step away from generating a nice looking graph.



Finally serialize the list with JavaScriptSerializer and parse it back. now you will get a beutiful graphical representation of your data.



Here I have plotted a graph between the time frame and the sales volume of a organization. And the graph looks like below






Graph



Hopefully you got something from this article and demonstration. If you want a complete demo then feel free to download the source code from above link.



If you like the article, a +1 will be very much appreciated, that is present at the top of the Page.



Happy Coding...




Publisher: Tapan kumar - 5:55 AM

Monday, February 17, 2014

,

Renaming Multiple Files Present In A Folder In Windows Form Applicaion





Introduction





Today I got scenario where I have to rename 100+ files with their names starting with XYZ_ and my task is to replace that XYZ_ with  ABC_. But I don't have that luxury to spend around 1-2 hours on renaming the files. So I find a way to rename the files through codding.



I made an application that is capable of replacing some text with your desired text.



Find the patten in the below image which thing I want to replace.








Files wth a prifix of XYZ_





This is a folder present in "E:\Test\Files" directory of my computer. As you can see the files present there in the above image you can find that all the files have a prefix of XYZ_ that needs to be changed to ABC_.



So if I go to change this by selecting all for renaming then it does not work it renames all the files with what I typed.



I tried to find out a standard solutions from the web but did not find one suitable and efficient one. So I developed a windows application to do the job. And here it is.  





   Download Source Code Here




Behind The Scene






Find the below image how I want the output.






When "XYZ_" replaced with "ABC_"







In order to do this I choose Windows application where I took two Text Boxes, those take the input from the user for replacement work. Find the below image and then I will explain what control does what ?






The Form with all the controls







* Find Text will take the text which you want to replace.

* Replace Text will take the text which will be replaced.

* Select File Type will give you to the option to select the type of file you want to rename.

* Rename Files button will open a folder selection dialog to select the respective folder you want. 






When you click on the Rename Files button with appropriate inputs then a folder selection dialog will be opened like below where you need to select the folder.






Folder selection Dialog





OK, now we are done with the design part. lets move to the codding part. Once you click on the  Rename Files button it will invoke the btnRename_Click event.









private void btnRename_Click(object sender, EventArgs e)
{
{
//
// This event handler was created by double-clicking the window in the designer.
// It runs on the program's startup routine.
//
DialogResult result = folderBrowserDialog1.ShowDialog();

if (result == DialogResult.OK)
{
int count = 0;
lblError.Text = string.Empty;

// This will get the folder you have selected.
DirectoryInfo d = new DirectoryInfo(folderBrowserDialog1.SelectedPath);

// Check if the Dropdown has some value or not.
if (cmbFileType.SelectedText != "Select")
{
try
{
// get only those files with an extension of the selected one.
FileInfo[] infos = d.GetFiles("*" + cmbFileType.SelectedItem.ToString());

// Make a loop to replace and rename the files.
foreach (FileInfo f in infos)
{
// Do the renaming here
File.Move(f.FullName, Path.Combine(f.DirectoryName,
txtReplaceText.Text.Trim() + f.Name.Replace(txtFindText.Text.Trim(),"")));
count++;
}

// Show alert if no file with the selected extension is present.
if (infos.Count() == 0)
{
lblError.Text = "Destination folder has no " + " ' "
+ cmbFileType.SelectedItem.ToString() + " ' files.";
}
//Show success alert.
else if (count == infos.Count())
{
lblError.Text = "All ' "
+ cmbFileType.SelectedItem.ToString() + " ' files in '"
+ d +
" ' folder whose name contains a text of ' " + txtFindText.Text.Trim() +
" ' has been replaced with ' " + txtReplaceText.Text.Trim() + " '.";
}
}
catch (Exception ex)
{
lblError.Text = "Some error occured";
}
}
else
{
lblError.Text = "Please select a file type first.";
}
}
}
}







What I am doing in the above code ???



  1. In the above method I am getting the folder name from the the folder selection dialog and creating a DirectoryInfo .

  2. Selecting all the files with the extension selected from the combo box.

  3. Making a loop to replace the intended text with the desired text.

  4. Then show appropriate alert message to the user.


If you want to download the demo project then you can download it from the above download link.



Happy Coding...



Publisher: Tapan kumar - 7:02 AM

Wednesday, February 12, 2014

What is Impersonation and How to Use it in ASP.NET





Introduction





Impersonation is the process used by ASP.NET to execute code in the context of an authenticated and authorized user.



Basically when IIS gets a request it check for the authorization of the user if he/she is authorized or not, by default, all ASP.NET code is executed using a fixed machine-specific account. If you want to change it then you can do this by using Impersonation.


   


Behind The Scene






Lets go a bit dipper to understand the use of it. Each time a request goes to IIS server the ASP.NET runs a security check to find if the user is authorized or not. And mostly ASP.NET uses the machine specific user account.



Consider a senario where you are logged on to a web application through your credentials and there you are trying to access a page which has a web service, that is being called to another computer. In this case your identity will not be shown in the web service's server instead the network credential(IIS credential) will be used for authentication.



For this reason, you can use impersonation to use your credentials for authentication in the second computer instead the network credentials.



And in ASP.NET you can do this in two manners like below;


  • Use an anonymous internet user account/authenticated user account.

  • Use a specific user account.



This thing can be done by turning the impersonate attribute to "true" in the identity element of the web config file.



  <identity impersonate="true" />




In this case ASP.NET impersonates to the authenticated user or to an anonymous internet user account.


  <identity impersonate="true"  userName="domain\username" password=" password"/>



In this case ASP.NET impersonates to a specific user account.



Happy Coding...



Publisher: Tapan kumar - 12:13 AM

Friday, February 7, 2014

Simple API Integration In C# To Get IP Address




Introduction





API: Application Programing Interface provides a medium of interaction between software components. Now-a-days API programing is one of the most important component of software development.



Know more about API



API is something like URL that provides some intended data to the user. Let me explain it with some real world example.



Consider you have an account in Facebook and you want to access your friend list, status, photos through codding. Here Facebook is a total different entity which has no relation with your code(application), neither you can access Facebook's code nor its database. So how can you access those data in your FB account via your application ?



Here comes the role of API, Facebook provides an interface (URL/Graph API) that gives you all the intended details of your account, those can be used in any application. So your work is just to call the API provides by the client (here Facebook) and to use the response in your application. That's it.



In this article I will show you a simple API call process in C# to get the IP address of the device, where your application is being opened.



Here is the sample project you can download it and check.







   Download Source Code Here


   


Behind The Scene






The main aim of an API is to return some desired information to the user so that those can be used across any application. There are many ways in which the API gives the response to the user.



Mostly an API gives response in two formats


  • XML format

  • JSON format




 (Here I will show you a sample API call to get IP address using smart-ip.net API)



A sample example of XML response.





 <?xml version="1.0" encoding="UTF-8"?>
<geoip>
<source>smart-ip.net</source>
<host>193.178.146.17</host>
<lang>en</lang>
<countryName>Ukraine</countryName>
<countryCode>UA</countryCode>
<city>Kiev</city>
<region>Kyyivs'ka Oblast'</region>
<latitude>50.4333</latitude>
<longitude>30.5167</longitude>
<timezone>Europe/Kiev</timezone>
</geoip>





A sample example of JSON response.







  {
"source":"smart-ip.net"
"host":"193.178.146.17",
"lang":"en",
"countryName":"Ukraine",
"countryCode":"UA",
"city":"Kiev",
"region":"Kyyivs'ka Oblast'",
"latitude":50.4333,
"longitude":30.5167,
"timezone":"Europe/Kiev"
}





 In this example we will consider the JSON formatted response from the API. So lets start our implementation.



Our API to get the IP details is http://smart-ip.net/geoip-json?callback=?. You can find the response like below if you click on the above link.







  ?({
"source": "smart-ip.net",
"host": "111.93.167.67",
"lang": "en",
"countryName": "India",
"countryCode": "IN",
"city": "Calcutta",
"region": "West Bengal",
"latitude": "22.5697",
"longitude": "88.3697",
"timezone": "Asia\/Calcutta"
});


You can find out your IP address in the above JSON response from the API along with your location, time zone etc.



Now lets do codding to implement this in c#.



First create a class with the data members those you are expecting from the API response.





  public class ApiClass
{
public string host { get; set; }
public string countryName { get; set; }
public string city { get; set; }
}


Here is the method to get the json response and to deserialize it.





 protected void CallAPI()
{
// Createa request to call the dropbox api.
WebRequest request = WebRequest.Create(new Uri("http://smart-ip.net/geoip-json?callback=?"));
request.Method = "GET";
request.ContentType = "application/json";

// Get the response.
WebResponse response = request.GetResponse();

// Read the response.
string apiResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
apiResponse = apiResponse.Replace("?(", "").Replace(");", "");

// Deserialize the json object.
ApiClass apiObj = new JavaScriptSerializer().Deserialize<ApiClass>(apiResponse);

// Set the label text.
lblIP.Text = apiObj.host;
lblCity.Text = apiObj.city;
lblCountry.Text = apiObj.countryName;
}


In the above method I am creating a WebRequest object with the above API and mentioning the method and contentType.



Then get the response from the web request by calling GetResponse() method. Finally hold the response in a string and deserialize it to get the desired data.



That's it you have just learned how to call an API in C#. Download the sample source code from the above download link to see a live demo.



Happy Coding...


Publisher: Tapan kumar - 3:33 AM

Wednesday, February 5, 2014

,

Simple Error Logging Mecanism In .Net Using Log4Net




Introduction





Exception Handling is a very important concept in software development. It does not matter how efficiently and optimized code you are writing, there is one thing you can not ignore it and that is an Exception.



There are various ways for logging errors, here I will be showing you one of the simplest way to log error/exception using Log4Net. I will only explain how to code it in your code snippet and will not go through its concepts. If you want some more knowledge then here is a link you can go for it.

 Log4Net





Here is the sample project you can download it and check.







   Download Source Code Here


   


Behind The Scene






Lets consider a condition where an exception can be produce. OK, lets take the simple and common one Attempted to divide by zero.



Every time you try to divide a number by 0 it will give an exception Attempted to divide by zero.




Step 1




Just take a simple web form and add a reference to the log4net dll.(Download the demo project and you will find the dll inside the bin folder.)



I have taken a button and on clicking on it I m trying to generate the Attempted to divide by zero exception.



Step 2




Now take a new class file and give it a name of Logging and add it to the project. Put the below code in this class.



  internal static readonly ILog log = LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

/// <summary>
/// Log the Exceptions
/// </summary>
/// <param name="ex">Exception</param>
public static void LogError(Exception ex)
{
try
{
log.Info("<br/><hr/>Log Entry<hr/> ");
log.Error(string.Format("<br/><b>Error Message : </b>{0}", ex.Message));
log.Error(string.Format("<br/><b>Error StackTrace : </b>{0}", ex.StackTrace));

//Log inner exceptions.
while (ex.InnerException != null)
{
ex = ex.InnerException;
log.Error("<hr/><b>Inner Exception : </b>");
log.Error(string.Format("<br/>Error Message : {0}", ex.Message));
log.Error(string.Format("<br/>Error StackTrace : {0}", ex.StackTrace));
log.Error("<hr/>");
}

log.Info("<br/><hr/>");

}
catch (Exception logex)
{
log.Error(logex);
}
}

** Here in the while loop I am trying to iterate the exception if there is any inner exceptions.




Step 3





Just add the below line of code in the AssemblyInfo.cs class present in the Properties folder.

[assembly: log4net.Config.XmlConfigurator(Watch = true)



Step 4




Now add the below things to the web config file

 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 

** Add this in the configSections



And then add the below code inside configuration.

 <log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="Errors/error.html"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline"/>
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="FileAppender"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>

** this will create a folder named Errors in the root folder and then will add a html file named error.html for the first time to write the error. Next time it will append the error.html file with new exceptions.




Step 5





OK we are almost done just generate an exception in the web form and log it. Just add the below code and go to the browser and click the button. Here you will catch an exception which will be logged in the error.html file in Errors folder.






 protected void btnLogError_OnClick(object sender, EventArgs e)
{
try
{
int num1 = 10;
int num2 = 0;
int num3;

num3 = num1 / num2;

}
catch (Exception ex)
{
Logging.LogError(ex);
//Response.Redirect()
}
}






Now we ave successfully logged the error using log4net.




This is a working example of error logging mechanisim. you can download the source code from the above link.





Happy Coding...


Publisher: Tapan kumar - 4:45 AM

Thursday, January 23, 2014

,

Applying Custom Styles To Default GridView Pagination




Introduction




This article will demonstrate you how to add some customize styles to your asp.net GridView paging. In case you are using the default paging functionality in GridView/ListView/DataGrid then you may need this thing to make your website little cool and pretty.



 



Behind The Scene






Lets take the below grid view for our example. Here we are giving a CssClass to the default pager named "gridView"


 <asp:GridView ID="grd_MyExample" runat="server" CssClass="grid" AllowPaging="True" 
OnPageIndexChanging="grd_MySalesClaims_PageIndexChanging" GridLines="None" >
<PagerStyle CssClass="gridView"/>
<Columns>
<asp:BoundField DataField="UserID" />
<asp:BoundField DataField="UserName" />
</Columns>
</asp:GridView>





OK, when this GridView gets loaded in the web page we can find the pagination indices are coming inside a "tr". So what we have to do in order to give some customize styles to it ????



Lets check the below CSS...


        .gridView {
background-color: #fff;
padding: 2px;
margin: 2% auto;
}

.gridView a {
cursor: hand;
font-family: Verdana;
font-size: 12px;
padding: 2px 6px;
border: solid 1px #ddd;
text-decoration: none !important;
color: Black;
}

.gridView a:hover {
background-color: #5D88AC;
color: #fff;
font-family: verdana;
cursor: pointer;
}

.gridView span {
background-color: #5D88AC;
color: #fff;
font-family: verdana;
font-size: 14px;
padding: 2px 6px;
}

table.grid tr.gridView td {
padding: 0px;
}

Oh that's cool,Now if you look into the GridView in your webpage you can find a nice looking pagination is coming under it.



In the above CSS we have given some style to the elements like "td","tr","a" those present inside the element with class "gridView".



That's it we have just applied some customizes styles to the ASP.NET GridView.




Happy Coding...


Publisher: Tapan kumar - 12:23 AM

Wednesday, January 15, 2014

,

Search Functionality In ASP.NET GridView




Introduction




Data Grid(GridView), One of the most used data representation format in ASP.NET where data is represented in a tabular format. ASP.NET offers you some basic features to manipulate the GridView elements like Sorting/Paging/Edit/Delete/Update operations. But in some scenarios you might need a searching functionality to implement in the GridView when the loaded data amount is very large (say 500 records).





Lets consider the above case when your GridView has some 500 records and you are searching for a single record then it might be difficult for you to look into all the damn pages of the GridView or/else to look into each record one by one. Are you going to do this ????? No, I am not coz I have a little brain and that's still working.






Behind The Scene






Lets jump into the coding part now...




Its a common notion that while implementing the search functionality we all collect the search data and then call a stored procedure with those parameters and  bind the returned data to the gridview.





But we will not go for calling any stored procedure for this. We will save the data in a session variable while binding the grid for the first time and then will perform all the searching things on it by LINQ.




In this Example we will consider a GridView of  3 columns named 



  • ID

  • Name

  • Email




We need to search the grid according to the above 3 columns. So First design the interface for Search Options.





Lets take a drop down with the above column names and then a text box, where you need to give some input in order to search the grid. And finally a button that has a click event that triggers our code for searching.





These things are upto you. You need to do these things by yourself; Its not a big deal you know it ;)





OK, There may be two scenarios where your datasource is a DataTable or a List :)






When The Data Source Is A List









Hold the list in a session variable first, while binding the GridView for the very first time, that we are going to use later.


  // hold the list in session
Session["ClaimList"] = listClaim;


Now in the Search button click Event get the list from session variable first.

  // Get the claim list stored in session.
listClaim = (List<SalesClaim>)Session["ClaimList"];

 Ok that's cool, we have the list in our hand now. Its time to implement search using the LINQ.



Lets take a Switch Case for the above said search columns and use the LINQ for filtering.


  switch (ddlSearch.SelectedValue)
{
case "ID": // Filter By ID
listClaim = listClaim.Where(p => p.ID.Equals(txtSearch.Text.Trim())).ToList();
break;
case "Name": // By Name
listClaim = listClaim.Where(p => p.Name.ToUpper().Contains(txtSearch.Text.Trim().ToUpper())).ToList();
break;
case "Email": // By Email
listClaim = listClaim.Where(p => p.Email.ToUpper().Contains(txtSearch.Text.Trim().ToUpper())).ToList();
break;
}

* ddlSearch is the filtering dropdown we have discussed above with the item values such as ID, 

   Name and Email

* txtSearch is the text box where the search text has to be entered.

* Trim() function is used to remove unwanted white spaces from the search text.

* ToUpper() function is used to convert text to upper case.



Up to this we are all done for searching the list, now bind the gridview and set the session variable again for further use.


   // Bind the grid view
grdUser.DataSource = listClaim;
grdUser.DataBind();
grdUser.EmptyDataText = "No data found";

// Set the list in session.
Session["ClaimList"] = listClaim;

 That's all for the List data source. And lets see how to do this if data source is a DataTable







When The Data Source Is A DataTable








Everything will be same as above except the LINQ. Here store the data table in session while binding the GridView for the very first time.


  // hold the list in session
Session["ClaimTable"] = dt;


 Now in the Search button click Event get the list from session variable first.


  // Get the claim list stored in session.
dt= (DataTable)Session["ClaimTable"];

 Ok that's cool, we have the list in our hand now. Its time to implement search using the LINQ.



Lets take a Switch Case for the above said search columns and use the LINQ for filtering.


   // hold the dropdown value in a variable
string searchColumn = ddlSearch.SelecetedValue;

// hold the search text entered in a variable
string searchText = txtSearch.Text.Trim();

  Now lets apply LINQ to the DataTable.


   var result = (from myRow in dt.AsEnumerable()
where myRow.Field<string>(searchColumn ).Equals(searchText)
select myRow).AsDataView();

 Up to this we are all done for searching the list, now bind the gridview and set the session variable again for further use.


   // Bind the grid view
grdUser.DataSource = result;
grdUser.DataBind();
grdUser.EmptyDataText = "No data found";

// Set the list in session.
Session["ClaimList"] = listClaim;

That's it we have done everything to implement searching functionality in the ASP.NET GridView.




Happy Coding...


Publisher: Tapan kumar - 7:03 AM

Friday, January 10, 2014

, , ,

How To Call A JavaScript Method From C#




Introduction


This is very silly thing but used very often. Calling a JavaScript Method to do something from code behind(C#) is not so difficult.



You may need this thing in order to show a custom alert using jQuery modal pop up, or for custom redirection when you are in an IFrame.






Behind The Scene






Recently I was stuck in some redirection problems. The senario is something like, I was in some iframe but after session out I need to go back to the login page. But the control in not in my hand as I am inside an iframe.








I tried a lot of things but what resulted me is reloading or rendering the page I was referring inside the iframe. But my purpose was to redirect the whole page to login page.








So I did this using JavaScript, and I need to call a JavaScript function form the C# code when session is out.






There are some way in which you can call a JavaScript function from code behind.






  // redirect user to home page.
ScriptManager.RegisterStartupScript(this, GetType(), "load", "closeDocumentIFrame();", true);

*closeDocumentIFrame(); is the method written in the aspx page


  // redirect user to home page.
ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>closeDocumentIFrame();</script>"));

*closeDocumentIFrame(); is the method written in the aspx page


  // redirect user to home page.
ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>window.parent.location.href ='{0}' </script>", "http://www.google.com"));

You can too add the JavaScript code here instead of writing another method in page level.




Happy Coding...


Publisher: Tapan kumar - 12:21 AM

Monday, January 6, 2014

, ,

URL Rewrite Using .htaccess File (Removing Page Extensions)

Introduction

In one of my previous article I have explained how to rewrite your website URL in C#(.NET). Here I will show you a simple example of achieving this using the .htaccess file.

Behind The Scene

Very often you need to rewrite your website URL to make it search engine friendly. You may need to remove file extension from the pages.


Lets say you have a page named "services.aspx", If you look into the page then you might not get a proper idea what type of content your page is representing. Exactly the same way Search Engines also look in the pages and page names. So its very important to give a specific and user and/or SEO friendly URL names.

If we consider the above page then lets make it a bit user friendly by changing what it is representing actually. Lets change it to "seo-services-in-india.aspx", now you can see this name actually means something to users and/or Search Engines.

Another thing its a better to have pages with no extension, but you know its impossible to miss the file extension of a page (ie. .php, .html, .jsp, .aspx). So what you need you need to force the browser to render the "seo-services-in-india.aspx"  under the name of "seo-services-in-india".

In my previous article on URL Rewriting, we have achieved the same goal by giving the dummy page name according to our choice that does not depend on the real page name.

e.g we have rewritten a URL from "contact.aspx"  to "my-contect-details", where the page name actually changed from one to other programatically. But here we will not change it but we will remove the extension only.
 <IfModule mod_rewrite.c>
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteRule ^([^\.]+)$ $1.html [NC,L]
     RewriteRule ^([^\.]+)$ $1.aspx [NC,L]
     RewriteRule ^([^\.]+)$ $1.php [NC,L]
     RewriteRule ^([^\.]+)$ $1.jsp [NC,L]
 </IfModule>

Now put the above code into your .htaccess file, and this will remove all the .html extensions from all your pages automatically. and the pages can be rendered without a file extension of  ".html", ".aspx", ".php", ".jsp"


Happy Coding...


Publisher: Tapan kumar - 6:11 AM