Image

Using Fiddler to test restful service

5 Jun

Capture

The request headers are:

User-Agent: Fiddler
Content-Type: application/json; charset=utf-8;
Host: 10.50.96.221
Content-Length: 20

The request body is:

{“externalId”:”163″}

The url is http://10.50.96.221/MessagingServices/FacilityData.svc/GetFacilityId

Method is “POST”.

 

If in url, the format is similar http://10.50.96.221/MessagingServices/InmateData.svc/GetInmate?inmateId=0001&facilityId=1

To generate data transfer object manually

7 May

To create a Data Transfer Object / DTO, all you need to do is to create a new class which have public accessors for the properties you wish to publish. You can wish to fill a collection of these object by using it in the Select clause of the Linq to EF query. For example lets say you query the Customer table which has 10 columns but you only need three columns to be sent to the receiver of this collection then you can do this.

<pre>// DTO class
public class MyDTO
{
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string PhoneNo { get; set; }
}

List<MyDTO> customerDTO = (from c in db.Customer
                           select new MyDTO()
                           {
                               CompanyName = c.CompanyName,
                               ContactName = c.Contact,
                               PhoneNo = c.Phone
                           }).ToList();</pre>

Tricks to speed up your SQL query

29 Aug

Given below are little known tips that you can use to ensure your Transact-SQL queries are performing in the most efficient manner possible.

1. Avoid ‘*’ in select query.
Restrict the queries result set by returning only the particular columns from the table and not all the table’s columns. The sql query becomes faster if you use the actual columns names in SELECT statement instead of than ‘*’.

 

2. Avoid COUNT(*) in select statement to check the existence of records in table.
Instead use IF EXISTS() to check records.

– Write the query as:

   IF EXISTS (SELECT * FROM table_name WHERE column_name = ‘xxx’)

– Instead of :

   SELECT COUNT(*) FROM table_name WHERE column_name = ‘xxx’

 

3. Use alternate of SELECT COUNT (*). Use an alternative way instead of the SELECT COUNT(*) statement to count the number of records in table.
– SELECT COUNT(*) statement makes a full table scan to return the total table’s row count which can take an extremely long time for large tables.
Use alternate query to achieve the same

     SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2

 

4. Use TOP keyword or the SET ROWCOUNT to fetch first Nth row from table.
– TOP or SET ROWCOUNT clause restricts the number of result and returns the smaller result set. This helps to reduce the data trafic between server and client.

5. Use ORDER BY clause with Primary or Indexed column of table
– Fetching the result set order by primary column or Indexed column added big performance benefits as SQL server don’t have to perform the extra overheads to rearrange data. Also try to implement the ORDER BY clause on Integer column instead of VARCHAR or STRING column.

 

6. Avoid ORDER BY on multiple columns.
– Implementing the order by clause on multiple column degrade the query performance as the SQL server has to run data sorting algorithm independently on each column or result set.

7. Use ‘WHERE’ instead of ‘HAVING’
– ‘HAVING’ clause is used to filter the rows after all the rows are selected. It is just like a filter who filter data from selected list.
– ‘WHERE’ clause work along with select statement to select only respective rows Do not use HAVING clause for any other purposes.

 

8. Avoid Mathematical expression on column. Avoid mathematical expression on column in WHERE clause. We should avoid computation on columns as far as possible and hence we will get an index scan instead of a seek
– For example:

 SELECT * FROM Orders WHERE OrderID*3 = 33000

degrade the performace as query performing calculation on column

9. Minimize the number of subquery block in your query.
The more number of sub query makes the execution plan complicated. Keep the script logic as simple as possible.

 

10. Use ‘LIKE’ clause in query instead of SUBSTR() function.
The SUBSTR() function first extract the value from data and then matching result get added in result set. LIKE clause has potential great advantage over SUBSTR() whenever string data need to compare
– Write the query as:

SELECT id, first_name, age FROM student_details WHERE first_name LIKE 'ABC%'

– Instead of :

   SELECT id, first_name, age FROM student_details WHERE SUBSTR(first_name,1,3) = 'ABC';

11. Use ‘BETWEEN’ operator instead of >= and Temp. table object
@tempTable -> in-memory table variable
A table variable is created in memory, and so performs slightly better than #temp tables. Also because there is even less locking and logging in a table variable.
Table variables are automatically cleared when the procedure or function goes out of scope, so you don’t have to remember to drop or clear the data. The SQL server mentain very less log related table variable and log activity is truncated immediately.
while #temp table log activity persists until the log hits a checkpoint, is manually truncated, or when the server restarts

18. use UNION ALL statement instead of UNION, whenever possible
The UNION ALL statement is much faster than UNION, because UNION ALL statement does not look for duplicate rows, while the UNION statement does look for duplicate rows, whether they exist or not

19. Use DISTINCT only whenever it is neccessery to use.
DISTINCT clause filter the result for unique combination of all columns in result rows which results in some performance degradation. You should use this clause only when it is absolutely necessary and should be used with minimum columns on table.

20. Use Indexes on table
Database indexes are similar to those you can find in libraries. They allow the database to find the requested information faster, just like a library index will allow a reader to find what they’re looking for without loosing time.
An Index can be created on a single column or a combination of columns in a database table. A table index is a database structure that arranges the values of one or more columns in a database table in specific order.

String permutation

16 Aug

Method 1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringPermutation
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "abcdefg"; 
            
            var summary = permutations(input).Select(chars => new string(chars.ToArray()));
            foreach (var x in summary)
            {
                Console.WriteLine(x);
            }
            Console.ReadLine();
        }


        private static IEnumerable<IEnumerable<T>> permutations<T>(IEnumerable<T> source)
        {
            var c = source.Count();
            if (c == 1)
                yield return source;
            else
                for (int i = 0; i < c; i++)
                    foreach (var p in permutations(source.Take(i).Concat(source.Skip(i + 1))))
                        yield return source.Skip(i).Take(1).Concat(p);
        }
    }
}

Method 2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringPermutation
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "abc"; 
            
            var summary = GetPermutations(input);
            foreach (var x in summary)
            {
                Console.WriteLine(x);
            }
            Console.ReadLine();
        }

        private static IEnumerable<string> GetPermutations(string input)
        {
            if (string.IsNullOrEmpty(input)) yield break;
            if (input.Length == 1) yield return input;
            string first_char = input.Substring(0, 1);
            IEnumerable<string> permutations_of_rest = GetPermutations(input.Substring(1));
            foreach (string one_permutation in permutations_of_rest)
            {
                for (int i = 0; i < one_permutation.Length + 1; i++)
                {
                    yield return one_permutation.Substring(0, i) + first_char + one_permutation.Substring(i);
                }
            }
        }
    }
}

Cache VS Session VS Cookies

15 Aug
  • Session is used to store per-user information for the current Web session on the server. It supports using a database server as the back-end store.
  • Cookie should be used to store per-user information for the current Web session or persistent information on the client, therefore client has control over the contents of a cookie.
  • Cache object is shared between users in a single application. Its primary purpose is to cache data from a data store and should not be used as a primary storage. It supports automatic invalidationfeatures.
  • Application object is shared between users to store application-wide state and should be used accordingly.

 

In other words.

One important difference is, that items in the cache can expire (will be removed from cache) after a specified amount of time. Items put into a session will stay there, until the session ends.

ASP.NET can also remove items from cache when the amount of available memory gets small.

Another difference: the session state can be kept external (state server, SQL server) and shared between several instances of your web app (for load balancing). This is not the case with the cache.

Besides of these differences (as others have noted): session is per user/session while cache is per application.

Find the nth Fibonacci number? Recursive – in C#

14 Aug

In simple words each number must be the sum of the past two numbers so the numbers go: 1, 1, 2, 3, 5, 8, 13, 21…..

 Class fibonacci
 {
     public static int fib(int n)
     {
        if(n == 0 || n == 1)
            return n;
        else
            return ( fib(n-1) + fib(n-2) );
    }
 }
 

Interfaces and Abstract Classes

14 Aug

Interfaces

An interface is a reference type containing only abstract members. These can be events, indexers, methods or properties, but only the member declarations. A class implementing an interface must provide the implementation of the interface members. An interface cannot contain constants, constructors, data fields, destructors, static members or other interfaces. Interface member declarations are implicitly public.

Declaration

[attributes] [modifiers] 
   interface identifier [:base-type[,]]
   {
       body [;]
   }

The attributes is optional and is used to hold additional declarative information.

The modifier is optional. The allowed modifiers are public and internal, unless nested inside a class, then the allowed modifiers are public, protected, private and internal. If no modifier is supplied then a default of internal is used.

The keyword interface must be followed by an identifier that names the interface.

The base-type of an interface can be zero or more interfaces. When more than one base-type is used, then this is a comma-separated list of base-types.

The body contains the member declarations.
Implementation
An interface is defined using the keyword interface. It is common practice to start all interface names with a capital I. For example:

public interface IVehicle
{
  void Start();
  void Drive();
  void Park();
  void ChangeGear(int gear);
  void SwitchOff();
}

In order to implement the interface, every method must be implemented in the class, else a compiler error will ensue.

public class Vehicle : IVehicle
{
  public void Start()
  {
    Console.WriteLine("The vehicle has been started");
  }
 
  public void Drive()
  {
    Console.WriteLine("The vehicle is being driven");
  }
 
  public void Park()
  {
    Console.WriteLine("The vehicle is being parked");
  }
 
  public void ChangeGear(int gear)
  {
    Console.WriteLine("Gear changed to " + gear.ToString());
  }
 
  public void SwitchOff()
  {
    Console.WriteLine("The vehicle has been switched off");
  }
}

If a class implements more that one interface and the two interfaces have methods named the same, then each method must be implemented unless they have the same definition in which case only one implementation is needed to implement the methods.
Abstract classes
Like an interface, you cannot implement an instance of an abstract class, however you can implement methods, fields, and properties in the abstract class that can be used by the child class.

For example, we could create an abstract class for all vehicle to inherit from:

public abstract class Vehicle
{
  public void Start()
  {
    Console.WriteLine("The vehicle has been started");
  }
 
  public abstract void Drive();
  public abstract void Park();
  public abstract void ChangeGear(int gear);
 
  public void SwitchOff()
  {
    Console.WriteLine("The vehicle has been switched off");
  }
}

So each class that inherits from Vehicle will already be able to use the methods Start and SwitchOff, but they must implement Drive, Park and ChangeGear.

So if we were to implement a Car class, it may look something like this.

public class Car : Vehicle
{
  public Car()
  {
  }
 
  public override void Drive()
  {
    Console.WriteLine("The car is being driven");
  }
 
  public override void Park()
  {
    Console.WriteLine("The car is being parked");
  }
 
  public override void ChangeGear(int gear)
  {
    Console.WriteLine("The car changed gear changed to " + gear.ToString());
  }
}

The override keyword tells the compiler that this method was defined in the base class.

Summary
An Interface cannot implement methods.
An abstract class can implement methods.

An Interface can only inherit from another Interface.
An abstract class can inherit from a class and one or more interfaces.

An Interface cannot contain fields.
An abstract class can contain fields.

An Interface can contain property definitions.
An abstract class can implement a property.

An Interface cannot contain constructors or destructors.
An abstract class can contain constructors or destructors.

An Interface can be inherited from by structures.
An abstract class cannot be inherited from by structures.

An Interface can support multiple inheritance.
An abstract class cannot support multiple inheritance.

Follow

Get every new post delivered to your Inbox.