Friday, 28 August 2015

Calling Method in Parent Page from User Control


Use delegate by below way.

n ASP.Net, we develop custom user control as a reusable server control independent of any containing parent aspx page. User control has its own public properties, methods, delegates, etc that can be used by parent aspx page. When a user control is embedded or loaded into a page, the page can access
In ASP.Net, we develop custom user control as a reusable server control independent of any containing parent aspx page. User control has its own public properties, methods, delegates, etc that can be used by parent aspx page. When a user control is embedded or loaded into a page, the page can access public properties, methods, delegates, etc that are in user control. After loading the user control, there a situation may arise like calling methods in page itself. But when a user control is developed, it has no knowledge of containing page. So it becomes a trick to call the page method.
In .Net, Delegate class has one method DynamicInvoke. DynamicInvoke method is used to invoke (late-bound) method referenced by delegate. We can use this method to call a method in parent page from user control. Let’s try with this example.
First create a user control called CustomUserCtrl. Its code will look some thing like this:
public partial class CustomUserCtrl : System.Web.UI.UserControl
{
private System.Delegate _delWithParam;
public Delegate PageMethodWithParamRef
{
set { _delWithParam = value; }
}

private System.Delegate _delNoParam;
public Delegate PageMethodWithNoParamRef
{
set { _delNoParam = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void BtnMethodWithParam_Click(object sender, System.EventArgs e)
{
//Parameter to a method is being made ready
object[] obj = new object[1];
obj[0] = “Parameter Value” as object;
_delWithParam.DynamicInvoke(obj);
}

protected void BtnMethowWithoutParam_Click(object sender, System.EventArgs e)
{
//Invoke a method with no parameter
_delNoParam.DynamicInvoke();
}
}
Then add this user control into an aspx page. The code behind of this page is as:
public partial class _Default : System.Web.UI.Page
{
delegate void DelMethodWithParam(string strParam);
delegate void DelMethodWithoutParam();
protected void Page_Load(object sender, EventArgs e)
{
DelMethodWithParam delParam = new DelMethodWithParam(MethodWithParam);
//Set method reference to a user control delegate
this.UserCtrl.PageMethodWithParamRef = delParam;
DelMethodWithoutParam delNoParam = new DelMethodWithoutParam(MethodWithNoParam);
//Set method reference to a user control delegate
this.UserCtrl.PageMethodWithNoParamRef = delNoParam;
}

private void MethodWithParam(string strParam)
{
Response.Write(“<br/>It has parameter: ” + strParam);
}

private void MethodWithNoParam()
{
Response.Write(“<br/>It has no parameter.”);
}
}
BtnMethodWithParam and BtnMethowWithoutParam are two different buttons on the user control that are invoking the methods in the parent page. On Page_Load of the page, we are setting the references of page class methods to delegate type properties in the user control. Click different buttons of user control, you will see MethodWithParam(string strParam) and MethodWithNoParam() methods called.
This is all we have to do to call page class methods from user control in ASP.Net.


How MVC application works

Introduction
This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.
MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.



Inside MVC Architecture
The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?
1.     MVC model is basically a C# or VB.NET class
2.    model is accessible by both controller and view
3.    model can be used to pass data from Controller to view
4.    view can use model to display data in page.

What is a View?
1.     View is an ASPX page without having a code behind file
2.    All page specific HTML generation and formatting can be done inside view
3.    One can use Inline code (server tags ) to develop dynamic pages
4.    A request to view (ASPX page) can be made only from a controller’s action method

What is a Controller?
1.     Controller is basically a C# or VB.NET class which inherits system.mvc.controller
2.    Controller is a heart of the entire MVC architecture
3.    Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
4.    Controller can access and use model class to pass data to views
5.    Controller uses ViewData to pass any data to view



MVC File Structure & File Naming Standards
MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
·         Root [directory]
o    Controller [directory]
§  Controller CS files
o    Models [directory]
§  Model CS files
o    Views [directory]
§  View aspx/ascx files
o    Global.asax
o    Web.config
ASP.NET MVC Execution Life Cycle
Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:




Browser Request (Step 1)
Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/
Job of Global.asax – MVC routing (Step 2)
The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [xyz.com]/home/index/:
·         Controller = home
·         Action = index()
·         ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string
Controller and Action methods (Step 3)
MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.
Call to View (Step 4)
Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.







App Config structure in WCF


Below Nodes are there in WCF basic bidning
  1. Configuration 
  2. System.ServiceModel
  3.  Services 
  4. Service =>  Name, Behavior Configuration 
  5. endpoint => address, binding , contract 
  6. host => base address 
  7. behaviors => Service behaviors  



<configuration>
     <system.serviceModel>
         <services>
             <service name="WcfCustomerService.CustomerService"
               behaviorConfiguration = "CustomerServiceMEXBehavior" >
                 <endpoint address =""
               binding="basicHttpBinding"
               contract="WcfCustomerService.ICustomerService"/>

                 <endpoint address ="net.tcp://localhost:8090/CustomerService"
                 binding="netTcpBinding"
                 contract="WcfCustomerService.ICustomerService"/>

                 <host>
                     <baseAddresses>
                         <add baseAddress ="http://localhost:8081/CustomerService"/>
                         <add baseAddress ="net.tcp://localhost:8090/CustomerService"/>
                     </baseAddresses>
                 </host>
             </service>
         </services>
         <behaviors>
                 <serviceBehaviors>
                     <behavior name="CustomerServiceMEXBehavior" >
                         <serviceMetadata httpGetEnabled="true" />
                     </behavior>
                 </serviceBehaviors>
             </behaviors>
     </system.serviceModel>
 </configuration  >

Wednesday, 26 August 2015

Implementing 2 interface with same method name.


When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type.





Why should prefer REST based services over SOAP?

1-REST permits many different data formats whereas SOAP only permits XML.
2-JSON usually is a better fit for data and parses much faster. REST allows better support for browser clients due to its support for JSON.
3-REST has better performance and scalability.
4-REST reads can be cached, SOAP based reads cannot be cached.
5-SOAP is a protocol its Simple Object Access Protocol and rest is an Architecture .REST stands for Representational State Transfer.


1. The RESTful Web services are completely stateless. This can be tested by restarting the server and checking if the interactions are able to survive.

2. Restful services provide a good caching infrastructure over HTTP GET method (for most servers). This can improve the performance, if the data the Web service returns is not altered frequently and not dynamic in nature.

3. The service producer and service consumer need to have a common understanding of the context as well as the content being passed along as there is no standard set of rules to describe the REST Web services interface.

4. REST is particularly useful for restricted-profile devices such as mobile and PDAs for which the overhead of additional parameters like headers and other SOAP elements are less.

5. REST services are easy to integrate with the existing websites and are exposed with XML so the HTML pages can consume the same with ease. There is hardly any need to refactor the existing website architecture. This makes developers more productive and comfortable as they will not have to rewrite everything from scratch and just need to add on the existing functionality.

7. REST permits many different data formats where as SOAP only permits XML.

6. REST-based implementation is simple compared to SOAP.

Anonymous Types in C#

Nice article on Anonymous types

http://www.c-sharpcorner.com/UploadFile/ff2f08/anonymous-types-in-C-Sharp/


Ref Vs Out Parameter

Introduction
The keywords ref and out are used to pass arguments within a method or function. Both indicate that an argument / parameter is passed by reference. By default parameters are passed to a method by value. By using these keywords (ref and out) we can pass a parameter by reference. 

Ref Keyword
The ref keyword passes arguments by reference. It means any changes made to this argument in the method will be reflected in that variable when control returns to the calling method.

Example code
public static string GetNextName(ref int id){
    string returnText = "Next-" + id.ToString();
    id += 1;
    return returnText;
}
static void Main(string[] args){
    int i = 1;
    Console.WriteLine("Previous value of integer i:" + i.ToString());
    string test = GetNextName(ref i);
    Console.WriteLine("Current value of integer i:" + i.ToString());
}
Output
Ref Output

Out Keyword
The out keyword passes arguments by reference. This is very similar to the ref keyword.

Example Code
public static string GetNextNameByOut(out int id)
{
    id = 1;

    string returnText = "Next-" + id.ToString();
    return returnText; 
}
static void Main(string[] args)
{
    int i = 0;

    Console.WriteLine("Previous value of integer i:" + i.ToString());

    string test = GetNextNameByOut(out i);

    Console.WriteLine("Current value of integer i:" + i.ToString());

}

Output
Out

Ref Vs Out
 
RefOut
The parameter or argument must be initialized first before it is passed to ref.It is not compulsory to initialize a parameter or argument before it is passed to an out.
It is not required to assign or initialize the value of a parameter (which is passed by ref) before returning to the calling method.A called method is required to assign or initialize a value of a parameter (which is passed to an out) before returning to the calling method.
Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.
It is not compulsory to initialize a parameter value before using it in a calling method.A parameter value must be initialized within the calling method before its use.
When we use REF, data can be passed bi-directionally.When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).
Both ref and out are treated differently at run time and they are treated the same at compile time.
Properties are not variables, therefore it cannot be passed as an out or ref parameter.
Ref / Out keyword and method Overloading
Both ref and out are treated differently at run time and they are treated the same at compile time, so methods cannot be overloaded if one method takes an argument as ref and the other takes an argument as an out.

Example code
public static string GetNextName(ref int id)
{
    string returnText = "Next-" + id.ToString();

    id += 1;

    return returnText;

}

public static string GetNextName(out int id)
{
    id = 1;

    string returnText = "Next-" + id.ToString();

    return returnText;

}

Output when the code is compiled:
compile the code

However, method overloading can be possible when one method takes a ref or out argument and the other takes the same argument without ref or out.

Example Code
public static string GetNextName(int id)
{
    string returnText = "Next-" + id.ToString();

    id += 1;

    return returnText;

}

public
 static string GetNextName(ref int id)
{

    string returnText = "Next-" + id.ToString();

    id += 1;

    return returnText;

}

Summary
The out and ref keywords are useful when we want to return a value in the same variables as are passed as an argument. 

Why we use MessageContract when DataContract already is there?

1. What is Data Contract?
·         Data Contracts are used to describe the data types used by a service. Interoperability is possible through this since it uses metadata of the services in background. Data Contracts can be used to describe either parameters or return values.
·         Data contracts are used to define the data structure. Messages that are simply a .NET type, let’s say lain old CLR object, and generate the XML for the data you want to pass.
·         Data Contracts describes the data types used by a service.
·          Data Contracts can be used to describe either parameters or return values.
·         Data Contracts are unnecessary if the service only uses simple types
·         Data contracts enable interoperability through the XML Schema Definition (XSD) standard.
·         Example
        Basic DataContract is defined:

1.                  [DataContract] 
2.                  public class Shape { } 
3.                   
4.                  [DataContract(Name = "Circle")] 
5.                  public class CircleType : Shape { } 
6.                   
7.                  [DataContract(Name = "Triangle")] 
8.                  public class TriangleType : Shape { } 

2. What is message contract?
·         Message contracts are preferred only when there is a need to "control" the layout of your message (the SOAP message); for instance, adding specific headers/footer/etc to a message.
·         Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body.
·         Whereas data contracts enable interoperability through the XML Schema Definition (XSD) standard, message contracts enable you to interoperate with any system that communicates through SOAP.
·         While, MessageContract(s) describes the structure of SOAP messages(since SOAP is context oriented - passing-on complete information about object) sent to/from a service and enable you to inspect and control most of the details in the SOAP header and body.
·         1. Generic - MessageContract enables you to interoperate with any system that communicates through SOAP.

2. Control - Using message contracts, we get complete control over SOAP messages sent to/from a service by having access to the SOAP headers and bodies. 3. Object Context - This(SOAPing) allows use of simple or complex types to define the exact content of the SOAP.
·         Example
Following is a simplest message contract:


[MessageContract] 
public class BankingDepositLog 
  [MessageHeader] public int numRecords 
  [MessageHeader] public DepositRecord records[]; 
  [MessageHeader] public int branchID; 




Why we use MessageContract when DataContract already is there?

A very simple answer to the question is, when you need a higher level of control over the message, such as sending custom SOAP header, you then use MessageContract instead of DataContract. But in my opinion, most of the messaging needs can be catered by DataContracts.
Sometimes complete control over the structure of a SOAP message is just as important as control over its contents. This is especially true when interoperability is important or to specifically control security issues at the level of the message or message part. In these cases, you can create a message contract that enables you to use a type for a parameter or return value that serializes directly into the precise SOAP message that you need.
why it is useful to use MessageContract(s), that is, to pass information in SOAP headers, you will have to dive into the SOAP advantages

We Can’t Mix Data and Message contract
Most important thing is we can’t mix Data and Message contract Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it return a MessageContract, or specify a MessageContract as the input argument to an operation and have it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service.

Answer is


When we need a higher level of control over the message, such as sending custom SOAP header, then we can useMessageContract instead of DataContract . But in general cases, most of the messaging needs can be fulfilled by DataContracts.