Thursday, December 22, 2011

Using SQL Profiler

Goto Sql Server Management Studio.

Tools - >Sql Server Profiler




Click on "OK" and enjoy.


Wednesday, December 14, 2011

Difference between WCF and Web service


Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.

<endpoint address="http://localhost:8090/MyService/MathService.svc" contract="IMathService" binding="wsHttpBinding"/> <endpoint address="net.tcp://localhost:8080/MyService/MathService.svc" contract="IMathService" binding="netTcpBinding"/>

Tuesday, November 29, 2011

Useful SQL shortcuts

Move content to right
 CTRL +A & TAB


Move content to left
 CTRL +A & SHIFT + TAB

Convert text to UPPER CASE in sql editor
select the content and press CTRL+SHIFT+U



Convert text to LOWER CASE in sql editor
select the content and press CTRL+SHIFT+L
.
.
.
.
.
.
.
.
.
.
.



Sunday, November 27, 2011

Creating Custom HTML Helpers

Creating custom html code blocks which can be re-used in the entire project.

Step1:
Add a folder "App_Code" in the root directory.

Step2:
Add a .cshtml file in the App_Code folder "CustomHelpers.cshml"
  @helper   HomeHelper(){
        <h1>Home Page Helper</h1>
    }
Step3:
Call the newly added helper code in our existing .cshtml page


@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2> Home Page</h2>
<div>
    @CustomHelper.HomeHelper();
</div>

Friday, November 25, 2011

ASP.NET Routing


Introduction

In an ASP.NET application that does not use routing, an incoming request for a URL typically maps to a physical file that handles the request, such as an .aspx file. For example, a request for http://server/application/Products.aspx?id=4 maps to a file that is named Products.aspx that contains code and markup for rendering a response to the browser. The Web page uses the query string value of id=4 to determine what type of content to display.

In ASP.NET routing, you can define URL patterns that map to request-handler files, but that do not necessarily include the names of those files in the URL. In addition, you can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.

URL Patterns in MVC Applications

URL patterns for routes in MVC applications typically include {controller} and {action} placeholders.

When a request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler. The MvcHandler HTTP handler determines which controller to invoke by adding the suffix "Controller" to the controller value in the URL to determine the type name of the controller that will handle the request. The action value in the URL determines which action method to call.

For example, a URL that includes the URL path /Products is mapped to a controller named ProductsController. The value in the action parameter is the name of the action method that is called. A URL that includes the URL path /Products/show would result in a call to the Show method of the ProductsController class.

The following table shows the default URL patterns, and it shows examples of URL requests that are handled by the default routes.

For IIS 7.0, no file-name extension is needed. For IIS 6.0, you must add the .mvc file-name extension to the URL pattern, as in the following example:

{controller}.mvc/{action}/{id}

{resource}.axd/{*pathInfo} ->>http://server/application/WebResource.axd?d=...
The route with the pattern {resource}.axd/{*pathInfo} is included to prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
Handling a Variable Number of Segments in a URL Pattern
When you define a route, you can specify that if a URL has more segments than there are in the pattern, the extra segments are considered to be part of the last segment. To handle additional segments in this manner you mark the last parameter with an asterisk (*). This is referred to as a catch-all parameter. A route with a catch-all parameter will also match URLs that do not contain any values for the last parameter. The following example shows a route pattern that matches an unknown number of segments.
query/{queryname}/{*queryvalues}

Adding Constraints to Routes
In addition to matching a URL request to a route definition by the number of parameters in the URL, you can specify that values in the parameters meet certain constraints. If a URL contains values that are outside the constraints for a route, that route is not used to handle the request. You add constraints to make sure that the URL parameters contain values that will work in your application.


public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("",
        "Category/{action}/{categoryName}",
        "~/categoriespage.aspx",
        true,
        new RouteValueDictionary 
            {{"categoryName", "food"}, {"action", "show"}},
        new RouteValueDictionary 
            {{"locale", "[a-z]{2}-[a-z]{2}"},{"year", @"\d{4}"}}
       );
}

/US/08  ->>No match. The constraint on year requires 4 digits.
/US/2008 ->>Matched
ASP.NET Routing versus URL Rewriting
ASP.NET routing differs from URL rewriting. URL rewriting processes incoming requests by actually changing the URL before it sends the request to the Web page. For example, an application that uses URL rewriting might change a URL from /Products/Widgets/ to /Products.aspx?id=4. Also, URL rewriting typically does not have an API for creating URLs that are based on your patterns. In URL rewriting, if you change a URL pattern, you must manually update all hyperlinks that contain the original URL.
With ASP.NET routing, the URL is not changed when an incoming request is handled, because routing can extract values from the URL. When you have to create a URL, you pass parameter values into a method that generates the URL for you. To change the URL pattern, you change it in one location, and all the links that you create in the application that are based on that pattern will automatically use the new pattern.

Features of the ASP.NET MVC Framework

The ASP.NET MVC framework provides the following features:

  • Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD). All core contracts in the MVC framework are interface-based and can be tested by using mock objects, which are simulated objects that imitate the behavior of actual objects in the application. You can unit-test the application without having to run the controllers in an ASP.NET process, which makes unit testing fast and flexible. You can use any unit-testing framework that is compatible with the .NET Framework.
  • An extensible and pluggable framework. The components of the ASP.NET MVC framework are designed so that they can be easily replaced or customized. You can plug in your own view engine, URL routing policy, action-method parameter serialization, and other components.
  • Extensive support for ASP.NET routing, which is a powerful URL-mapping component that lets you build applications that have comprehensible and searchable URLs. URLs do not have to include file-name extensions, and are designed to support URL naming patterns that work well for search engine optimization (SEO) and representational state transfer (REST) addressing.
  • Support for using the markup in existing ASP.NET page (.aspx files), user control (.ascx files), and master page (.master files) markup files as view templates. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.
  • Support for existing ASP.NET features. ASP.NET MVC lets you use features such as forms authentication and Windows authentication, URL authorization, membership and roles, output and data caching, session and profile state management, health monitoring, the configuration system, and the provider architecture.

Friday, November 18, 2011

How do I get the application path in an ASP.NET application


Retrieve the application path

string appPath = HttpContext.Current.Request.ApplicationPath;

Convert virtual application path to a physical path

string physicalPath = HttpContext.Current.Request.MapPath(appPath);

                                                   OR

System.Web.HttpContext.Current.Server.MapPath("~/")

Wednesday, October 12, 2011

Difference between href="#" and href="javascript:void(0)"

href="" will link to the same page as the one you are currently on, effectively refreshing the page. href="#" will not refresh the page, but using the # will make the screen move to the top of the page (it is the browser effectively looking for an anchor with no name, ). javascript:void(0) will prevent anything happening on the link at all.

Returning Multiple Values in JAVASCRIPT

function myFunction() {
  var result = testFunction();
   alert(result[0]);//returns "1"
   alert(result[1]);//returns "2"
   alert(result[2]);//returns "3"
}

//This function returns multiple values(a,b,c) in the form of array.
function testFunction() {
  var a="1",b="2",c="3";
    return [a,b,c]
}

Tuesday, October 4, 2011

Calling Server Side Method Using jQuery/Ajax



With this post I would show how to call server side method from client side. Here we will use jQuery to utilize the Ajax Capabilities which will help us to get/post data to/from server Asynchronously. There are many methods available to perform an async callback to the server. Here I will show a simple example as in how to call a code behind Webmethod.
For simplicity I would be calling the code behind method on a Button Click. Here is the code:
Aspx markup:
   1: <asp:Button ID="Button1" runat="server" Text="Click" />
   2: <br /><br />
   3: <div id="myDiv"></div>
jQuery:
   1: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
   2:   <script type ="text/javascript">
   3:       $(document).ready(function () {
   4:           $('#<%=Button1.ClientID %>').click(function () {
   5:               $.ajax({
   6:                   type: "POST",
   7:                   url: "WebForm1.aspx/ServerSideMethod",
   8:                   data: "{}",
   9:                   contentType: "application/json; charset=utf-8",
  10:                   dataType: "json",
  11:                   async: true,
  12:                   cache: false,
  13:                   success: function (msg) {
  14:                       $('#myDiv').text(msg.d); 
  15:                   }
  16:               })
  17:               return false;
  18:           });
  19:       });
  20:   </script>
Code Behind (C#):
   1: [WebMethod]
   2:    public static string ServerSideMethod()
   3:    {
   4:        return "Message from server.";
   5:    }
In the above code, the aspx markup contains a button on click of which we would call the server side method named ServerSideMethod(). The div would show the message returned from the server. When you run the code above and click the button, it would the div would show the message "Message from server".
If you want to send parameters to your code behind method, you would change the line 8 in the above jQuery code as:
   1: data: "{'param1': 1}"
   2: data: "{'pageNumber' :'1','pageSize' : '10'}",
With the above line I would be sending a parameter with value as 1 to the server side method.
The method would change as:
   1: [WebMethod]
   2:    public static string ServerSideMethod(string param1)
   3:    {
   4:        return "Message from server with parameter:"+param1;
   5:    }
The output will now be:
Message from server with parameter:1
You could also call any webmethod method in your webservice by changing the url in the jQuery as:
   1: url: "WebService1.asmx/ServerSideMethod"
where WebService1 is your webservice and ServerSideMethod is your webmethod in WebService1.
Recently I have seen a lot of questions from members in the asp.net forums asking about how to call Javascript confirm on button click and then based on user selection ie Yes/No process code behind logic.
Here is another example of how to do so:
   1: function MyConfirmMethod() {
   2:         if (confirm('Are your sure?')) {
   3:             $.ajax({
   4:                 type: "POST",
   5:                 url: "WebForm1.aspx/ServerSideMethod",
   6:                 data: "{}",
   7:                 contentType: "application/json; charset=utf-8",
   8:                 dataType: "json",
   9:                 success: function (msg) {
  10:                     $('#myDiv').text(msg.d);
  11:                 }
  12:             });
  13:             return false;
  14:         }
  15:         else {
  16:             return false;
  17:         }
  18:     }
   1: protected void Page_Load(object sender, EventArgs e)
   2:   {
   3:       Button1.Attributes.Add("onclick", "return MyConfirmMethod();");
   4:   }
   5:   [WebMethod]
   6:   public static string ServerSideMethod()
   7:   {
   8:       return "Message from server!";
   9:   }
Above you will see I am calling javascript confirm on the button click. On pressing yes, jQuery calls code behind method ServerSideMethod and returns back the message. You could perform any server side logic/database operations here based on the user response. Note I use return false as it prevents postback to the server.

Saturday, October 1, 2011

"IN" operator in LINQ

SQL Query using IN operator


SELECT Members.Name
FROM Members
WHERE Members.ID IN ("1,2,3")
LINQ Query equivalent


string[] str = {"1","2"};
var list =
Members.Where(p=> str.Contains(p.ID)).Select(X => X);

Wednesday, September 28, 2011

LINQ To SQL - CASE Statements


Switch functionality can be accomplished by using "Ternary Operator"
The ternary operator takes the "if" statement and turns it into an expression.  Here's an example:
The syntax is <condition>  ? <true value> : <false value>
Now, let's add a basic case statement.  This will return the text "This is poisonous!" for plants with a 0 in the edible field, and "Okay to eat" otherwise.  By looking at the generated SQL using the debug visualizer, we can see that a CASE statement is in fact being generated.
Now the question will come up, "what if I want to have more than just one WHEN and an ELSE".  In other words, how do I add more cases.  Here's the trick:
By replacing the "if false" value of the ternary expression with another ternary expression we logically create the same effect as a SQL CASE statement.  Unlike the switch statement, this is an expression, and can be used on the right had side of the assignment operator.  LINQ to SQL is smart about handling this too.  It creates additional WHEN clauses inside of one CASE statement.  Just like you would if you were writing the SQL yourself.  The C# syntax forces you to have an ELSE clause.  That's a good thing.
Some people might opt for writing in extra parenthesis to clearly show each ternary expression.  I think writing the statements without the parenthesis more clearly shows our intent, that is, making a CASE statement.

Types of LINQ syntax


There are 2 types of LINQ Syntax:

  1. 1.Fluent syntax
  2. 2.Query syntax

string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
IEnumerable<string> query =
names.Where (name => name.EndsWith ("y"));
query.Dump ("In fluent syntax");

query =
from n in names
where n.EndsWith ("y")
select n;
query.Dump ("In query syntax");

Combining interpreted and local queries.


void Main()
{
// This uses a custom 'Pair' extension method, defined below.

IEnumerable<string> q = Customers
.Select (c => c.Name.ToUpper())
.Pair() // Local from this point on.
.OrderBy (n => n);

q.Dump();
}

public static class MyExtensions
{
public static IEnumerable<string> Pair (this IEnumerable<string> source)
{
string firstHalf = null;
foreach (string element in source)
if (firstHalf == null)
firstHalf = element;
else
{
yield return firstHalf + ", " + element;
firstHalf = null;
}
}
}

Tuesday, September 27, 2011

SQL to LINQ converter

Try this tool : 
http://www.linqpad.net/

Using LINQPad to test your LINQ to XML queries


Using LINQPad to test your LINQ to XML queries

Sunday, 6 February 2011 12:55 by mha
If you’re a LINQPad user you’re probably used to query your DBML (LINQ to SQL), but did you know that you can also use it for LINQ to Objects, LINQ to XML etc.
A simple example of how to do a query against a XML file (make sure language is set to C# Statements):
var xml = XElement.Load (@"c:\\inetpub\\GWportal\\src\\wwwBackend\\App_Data\\axCache\\ 
   GWDK\productprice-mha.xml");
var query = 
  from e in xml.Descendants("unittransaction").Descendants() 
    where (e.Attribute("name").Value == "ItemRelation" && e.Value.Equals("10020")) 
  select e.Parent; 
  
query.Dump();
Which gives this result: