Implement Exception Handling in jQuery While Calling Web Service

If you are using an Ajax Web service call in jQuery and if you make a small syntax or typo mistake then it will be tedious to determine the exact root cause of the problem. Even if you debug in a browser it will not show the exact error message.

But if you write proper exception handling code in the jQuery web service call then you can easily determine the exact problem in your code.

Here we can implement exception handling in two ways.

Approach 1:

error: function (XMLHttpRequest, textStatus, errorThrown) {  

                           var err = eval("(" + XMLHttpRequest.responseText + ")");  

                           alert(err.Message)  

                       } 

Approach 2:

error: function (response) {  

                           var r = jQuery.parseJSON(response.responseText);  

                           alert("Message: " + r.Message);  

                           alert("StackTrace: " + r.StackTrace);  

                       } 


<script type="text/javascript">  

       $(function () {  

           $("#txtEmpName").autocomplete({  

               source: function (request, response) {  

                   var param = { empName1: $('#txtEmpName').val() };  

                   $.ajax({  

                       url: "WebForm1.aspx/GetEmpNames",  

                       data: JSON.stringify(param),  

                       dataType: "json",  

                       type: "POST",  

                       contentType: "application/json; charset=utf-8",  

                       dataFilter: function (data) { return data; },  

                       success: function (data) {  

                           response($.map(data.d, function (item) {  

                               return {  

                                   value: item  

                               }  

                           }))  

                       },  

   

                       //Approach 1  

                       error: function (XMLHttpRequest, textStatus, errorThrown) {  

                           var err = eval("(" + XMLHttpRequest.responseText + ")");  

                           alert(err.Message) ; 

                       }  

   

                       //Approach 2  

                       //error: function (response) {  

                       //    var r = jQuery.parseJSON(response.responseText);  

                       //    alert("Message: " + r.Message);  

                       //    alert("StackTrace: " + r.StackTrace);  

                       //}  

                   });  

               },  

               minLength: 2 //This is the Char length of inputTextBox  

           });  

       });  

   </script> 


[WebMethod]  

      public static List<string> GetEmpNames(string empName)  

      {  

          List<string> Emp = new List<string>();  

          string query = string.Format("SELECT EmpName FROM tblEmp WHERE EmpName LIKE '%{0}%'", empName);  

          using (SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True"))  

          {  

              using (SqlCommand cmd = new SqlCommand(query, con))  

              {  

                  con.Open();  

                  SqlDataReader reader = cmd.ExecuteReader();  

                  while (reader.Read())  

                  {  

                      Emp.Add(reader.GetString(0));  

                  }  

              }  

          }  

          return Emp;  

      } 

Online Payment Gateways For Indian eCommerce Websites

A service that processes all online payments is called a payment gateway. For this to happen, customers send their credit/debit card information at the final stage of purchase that is transmitted to the store and at last to the bank.
Additionally, you get a notification from the payment gateway about the approval of the payment. If the payment is not approved, the amount will get cancelled. Then the payment amount is deducted from the customer’s account and deposited in your store account.
Depending on the bank’s response, the payment authorization request can be either accepted or rejected. This response is sent to the payment gateway via the merchant server and the server response enables the customers to proceed with the purchase.
Usually, most of the WooCommerce stores offer the same payment solutions. But it is important to select some different options to stand unique among your competitors by offering other means of payment to your customers. So, here’s a list of the best WooCommerce payment gateways for your online store.
WooCommerce is now the most popular free eCommerce platform on the web. WooCommerce is an open-source e-commerce plugin for WordPress. It is designed for small to large-sized online merchants using WordPress.

RANK() Function in SQL Server

The RANK() function is a window function could be used in SQL Server to calculate a rank for each row within a partition of a result set. 

The same rank is assigned to the rows in a partition which have the same values. The rank of the first row is 1. The ranks may not be consecutive in the RANK() function as it adds the number of repeated rows to the repeated rank to calculate the rank of the next row. 

Syntax : 

RANK() OVER (

   [PARTITION BY expression, ]

   ORDER BY expression (ASC | DESC) );


Example :
SELECT Name, 
RANK () OVER (
ORDER BY Name
) AS Rank_no 
FROM geek_demo;

Using ListBox in Silverlight

First,

Create aclass called Person
  public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
 Then, in xaml,
<ListBox x:Name="lbPeople" Grid.Row="0" Grid.Column="0"  Height="250" Width="300" HorizontalAlignment="Left"
                              ScrollViewer.HorizontalScrollBarVisibility="Hidden" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                            <ColumnDefinition Width="100" />
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Margin="10" Text="{Binding FirstName}" />
                        <TextBlock Grid.Column="1" Margin="10" Text="{Binding LastName}" />
                        <TextBlock Grid.Column="2" Margin="10" Text="{Binding Age}" />
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

In C# code,
   void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            lbPeople.ItemsSource = GetPeople();
        }

        public List<Person> GetPeople()
        {
            string[] firstNames = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" };
            string[] lastNames = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11" };
            List<Person> people = new List<Person>();
            Random r2 = new Random();
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                int index = r.Next(0, 11);
                Person p = new Person
                {
                    FirstName = firstNames[index],
                    LastName = lastNames[index],
                    Age = r2.Next(10, 90)
                };
                people.Add(p);
            }
            return people;
        }

Using BusyIndicator in Silverlight

Use namespace :  using System.Threading;
 

In xaml code,

 <Grid x:Name="LayoutRoot" Background="White">      
            <toolkit:BusyIndicator HorizontalAlignment="Center" VerticalAlignment="Center"
                                Name="busyIndicator" IsBusy="False">
                <StackPanel>
                    <Button x:Name="btnClick" Content="Click Here" Width="100" Height="25"
                        Click="btnClick_Click"/>
                </StackPanel>
            </toolkit:BusyIndicator>           
    </Grid>


In Button Click c# code,

 busyIndicator.IsBusy = true;
 busyIndicator.BusyContent = "Fetching Data...";
 \\ Here you can add youw own text

 ThreadPool.QueueUserWorkItem((state) =>
 {
 Thread.Sleep(3 * 1000);
 Dispatcher.BeginInvoke(() => busyIndicator.IsBusy = false);
});

ASP.NET Page Life Cycle

Following are the different stages of an  ASP.Net page :
  • Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
  • Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
  • Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
  • Page load . at this stage, control properties are set using the view state and control state values.
  • Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
  • Postback event handling . if the request is a postback (old request), the related event handler is called.
  • Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.
  • Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.




Using Image with Button in Silverlight


In xaml page,

<Button Height="33" Name="btnAdd" Width="78" Margin="54,0,0,0 >
  <!--<Button.Content>-->
       <StackPanel>
          <Image Height="15" HorizontalAlignment="Left" Name="imgTest" Stretch="Fill" VerticalAlignment="Top" Width="47" Source="Images/Puts.png" />
          <TextBlock Name="txtAdd" Margin="5,0,0,0">Add</TextBlock>
       </StackPanel>
  <!--</Button.Content>-->
</Button>

Instead of stack panel, we can use ‘Button.Content’ also depending on the situations.

Inserting Data in SQL Server from Text file


To insert data from a text file, we have to keep a fully formatted text file with appropriate data’s which are to be inserted.

The query for creating table,
CREATE TABLE Employee
(
   FirstName varchar (100) NOT NULL,
LastName varchar (100) NOT NULL,
Email varchar (100) NOT NULL
)

Then we have a text file with the bulk data’s like as follows,

sibin,thomas,sibinthomask@gmail.com
emp1FirstName,emp1LastName,emp1@company.com
emp2FirstName,emp2LastName,emp2@company.com
emp3FirstName,emp3LastName,emp3@company.com
emp4FirstName,emp4LastName,emp4@company.com
emp5FirstName,emp5LastName,emp5@company.com
emp6FirstName,emp6LastName,emp6@company.com
emp7FirstName,emp7LastName,emp7@company.com
emp8FirstName,emp8LastName,emp8@company.com
emp9FirstName,emp9LastName,emp9@company.com
emp10FirstName,emp10LastName,emp10@company.com
emp11FirstName,emp11LastName,emp11@company.com
emp12FirstName,emp12LastName,emp12@company.com

Put the name of the file as 'EmployeeList.txt'

Now the query for inserting data is,
BULK INSERT Employee FROM 'c:\EmployeeList.txt' WITH (FIELDTERMINATOR = ',')

View the inserted data from table 'Employee',
select * from Employee

Application types in WPF

Windows Presentation Foundation Application differs from traditional Windows Forms Application in several ways. The most notable is that code for the user interface is separated from the code for application functionality. Although the code for project can be done in C#.net , vb.net, etc but the user interface of a WPF project is typically defined using a relatively new declarative syntax called Extensible Application Mark Up Language(XAML). Wpf development support three kinds of application:

    1. Windows Application
    2. Navigation Application
    3. XAML Browser Application(XBAPs)

Let us check when and where to select which type of application.

When to use Windows Application ?
For a user experience that most closely resembles a traditional Windows Form application Menu driven, multiwindow application that combines the rich functionality of a desktop with the rich UI that WPF provides.

When to use Navigation Application ?
For user experience that more closely resembles a Web site, you should choose a page-based application. Navigation applications and XBAP applications provide built in navigation functionality that allows you to structure the application paralleling a task, such as in an Internet shopping application or wizard.
If application require to access System Resources that fall outside the Internet Security Zone, then XBAP is not a good choice, a better choice would be a Windows application or Navigation application.

When to use XBAP Application ?
When you want to deploy the application to a WebServer and have users start if from the hyperlink, thus making it easily accesible to a large-scale audience.  If your application does not require access to system resources, XBAP might be good choice.

Windows Presentation Foundation (WPF)

                             Now I am working on Windows Presentation Foundation (WPF) application. It is a good opportunity to work on this technology. Microsoft Silverlight utilizes WPF to provide embedded web controls comparable to Adobe Flash, but with more focus on a UI object model and less on animation. 3D runtime rendering is unsupported in Silverlight, but available to embedded WPF applications.
                           WPF has a built-in set of data services to enable application developers to bind and manipulate data within applications. It supports three types of data binding: as in Silverlight.
one time: where the client ignores updates on the server.
 one way: where the client has read-only access to data.
 two way: where client can read from and write data to the server

http://www.wpftutorial.net/ . This site helped me a lot to work in WPF controls

Get List of Printers Using c#


using System.Drawing.Printing;

PrintDocument prtdoc = new PrintDocument();
//Here we get the default printer
string strDefaultPrinter = prtdoc.PrinterSettings.PrinterName;
foreach (String strPrinter in PrinterSettings.InstalledPrinters)
{
         //here we can put the list in combo box.
         cbPrintername.Items.Add(strPrinter);
         if (strPrinter == strDefaultPrinter)
         {
                cbPrintername.SelectedIndex = cbPrintername.Items.IndexOf(strPrinter);
          }
}

Difference between DataReader and DataSet and DataAdapter in C#

DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader is used to iterate through resultset that came from server and it will read one record at a time because of that memory consumption will be less and it will fetch the data very fast when compared with dataset.

DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.

DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. 


DataTable:
A DataTable is an in-memory representation of a single database table which has collection of rows and columns  DataTable fetches only one TableRow at a time  As DataTable is a single database table, so there is no DataRelation object in it. In DataTable, there is no UniqueConstraint and ForeignKeyConstraint objects available.  In DataTable, DataSource cannot be serialized.