Pass data from user control to parent page using events and delegates

Using web user controls is quite a common approach in developing web applications. While using them, we often get into a situation, where we need to pass some kind of data from the user control to the parent page, when any operation is performed on the user control. For ex, we may need to pass data, on OnClick event of a button on the user-control, to the parent page. In order to achieve such a functionality, delegates are one of the most helpful ways of doing this. So let’s create a sample application to discuss this approach.

Our example will consist of a Default.aspx page and ChildControl.ascx user-control. This user-control will have a button with OnClick event attached to it. On click of this button, we will send current datetime to the parent page. So for initial setup, add a button on the user-control and place the user-control on page.

To achieve this, our logic has to be, to notify the parent page that some action has been performed on the user-control. For this, our page must subscribe or attach itself to the user-control, using some kind of mechanism. This mechanism which will be the events in our case. This is similar to the concept of subscribing to newsletters or event notifications on any website. When any newsletter is published or some event happens on a website, you get an email notification of it. Similar is the case here. Whenever the event (to which parent page has subscribed) is fired, subscriber will receive notifications. So let’s start the code step wise.

Step 1 : Create a delegate on the user-control, that can encapsulate a method which takes no input and returns DateTime type. Also, declare an event on the user control, which is of the delegate type which we created.

Pass data from user control to parent page using events and delegates

Step 2 : Our main page will subscribe to the event that we created on the user-control, to get notification of when the event is fired on the user control.

Pass data from user control to parent page using events and delegates

Step 3 : Next, when the button click functionality is done, we explicitly execute the event by calling the GetDataFromChild event, passing the required data.

Pass data from user control to parent page using events and delegates

Step 4 : Run the application and click the button. On clicking of button, when we make the explicit call to the event from the user control, parent page receives the notification through the ucChild_GetDataFromChild method.

Pass data from user control to parent page using events and delegates

How it works ?

Now that we have successfully created the sample application, let’s discuss how this process is actually working. To start with, we have used the combination of event and delegates. We create a delegate of type ChildControlDelegate and an event of the same type, on the user-control. Our parent page attaches itself, to this event. Whenever the user-control finishes its task on button click, it executes the event by calling GetDataFromChild and the main page receives the notification in a method named ucChild_GetDataFromChild.

Like we discussed an example at the start of the article, when we subscribe for any newsletter on any website, we get the notification emails of it. Same is the case here.

Important point to note here is that when we attached the event on the parent page (using += syntax), it is like we are actually adding a method, which this event will execute when it is fired. This method is added with the help of a delegate. It basically acts as a receiver for the parent page. So whenever we explicitly call the event from the user-control, using the  GetDataFromChild(DateTime.Now) statement, Default page will invoke the receiver method on it (which in this case is ucChild_GetDataFromChild ) to get receive the results from the user control.

So this was how we can pass data from user-control to parent page. Hope you enjoyed reading it…!!!

var vs dynamic keywords in C#

Programming languages can be normally considered to be either statically typed or dynamically typed. A static (Not to be mixed with static keyword, used for classes) typed language validates the syntax or checks for any error during the compilation of the code. On the other hand, dynamically typed languages validate the syntax or checks for any error, only at the run time. For ex, C# & JAVA are a static type and javascript is dynamic type language.

C# was earlier considered as a statically typed language, as all the code written was validated at the compile time itself. But, with the introduction of the dynamic keyword in C# 4.0, it became a dynamic typed language also. The two concepts of static and dynamic types in C# can be illustrated with the use of two keywords named var and dynamic.  Let’s discuss about some basic differences between these two, based on some of their characteristics.

1. When were they introduced :

  • var was introduced in C# 3.0
  • dynamic was introduced in C# 4.0

2. Type inference of variables :

  • var is a statically type variable. It results in a strongly typed variable i.e. the data type of these variables are inferred at compile time. This is done based on the type of value, with which these variables are initialized.
  • dynamic are dynamically typed variables. This means, their type is inferred at run-time and not the compile time in contrast to var type.

3. Initialization of variables :

  • var type of variables are required to be initialized at the time of declaration or else they run in compile time error as : Implicitly-typed local variables must be initialized.
  • dynamic type variables need not be initialized, when declared.

4. Changing type of value assigned:

  • var does not allows to change the type of value assigned, which is once assigned to it. This means, if we assign an integer value to a var, we cannot assign string value to it. This is because, on assigning the integer value, it will be treated as of integer type thereafter. So further any other type of value cannot be assigned. For ex, following code will give a compile time error

var vs dynamic in C#

  • dynamic allows to change the type of value, assigned to it initially. In the above code, if we use dynamic instead of var, it will not only compile, but will also work at run-time. This is because, at run time, the value to the variable is first inferred as Int32 and when its value is changed, it is inferred as string type.

var vs dynamic in C#

5. Intellisense help :

  • Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, compiler has all the information related the type. So we have the intellisense help available. See the code below. We have a var variable initialized with a string value. So its type is known to the compiler and we have the appropriate intellisense help available for it.

var vs dynamic in C#

  • Intellisense help is not available for dynamic type of variables as their type is unknown till run time. So intellisense help is not available. Even you will be informed by compiler as - This operation will be resolved at run-time. See the code below :

var vs dynamic in C#

6. Restrictions on the usage :

  • dynamic variables can be used to create properties and return values from a function.
  • var variables cannot be used for property or return value from a function. They can be only used as local variables in a function.

var vs dynamic vs object ?

If we closely observe dynamic type, it is performing pretty much the same task which the object type (which is the base type of all other types) does. Then what is the difference between object type and var then ? Also, why we need var when we have the object type. Let’s discuss these points by doing some comparisons.

  1. While using object type, compiler provides only generic information, functionality or functions related to the type it holds, until it is being type cast into its actual type. This means, even if we have stored any integer or string values in an object type, we will get their related functions, only if we convert the object type into its actual type. See the code below :

var vs dynamic in C#
Here, we only have generic properties and functions available for the type of value stored in it, which we will have, even if we store any integer or other type of value in it. Now, let’s convert it to its actual type i.e. string.

var vs dynamic in C#

Now after explicit conversion, we have the properties & functions specific to the string type. In case we use the var type to store the same value, we would not be required to do the explicit conversion, as compiler already infers its type from the value initialized and we will have its functions and properties.

2.  Based on the above point, object types increase the overhead of boxing and un-boxing, before we can use the actual values stored in it or use any function related to it. But this is not the case with var, as we already know its type at the time of use. For ex, in above code, we get to use the functions related to string only after we convert the object into string. So this results in un-boxing. On the other hand, for dynamic types, we only need to know that the function or property we are using, actually exists for the type of value being stored in it.

var vs dynamic in C#

For example, in above code, if we know that dynamic variable will be storing string type, then we can use Length type property, even if it is not available in the intellisense help.

3. Next, we need to be careful while casting or converting the values, when using the dynamic or object type variables. Any wrong casting can result in run time errors. On the other hand, var type will give a compile time error with wrong conversion. So any run time error is not possible.

var vs dynamic in C#

Here, object type stored string value, but we are trying to cast into integer type. So will throw run time error.

var vs dynamic in C#

Similarly, we are storing back the string value, into integer type. So it would again result in error.

4.  In terms of interoperability with different frameworks, earlier we required object type to be used to get the underlying object type and then use reflection to access the related methods or functions. But with the introduction of dynamic keyword, we only need to know that a function or property exists on the underlying object and rest we simply need to make a call to these properties or functions.

5. As per MSDN,  “…..As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time….”.

From these points, we cannot conclude which specific type we should use. It all depends on requirements whether we should go for var or dynamic or object type.

So this was all about the basic differences between var and dynamic keywords. Hope you enjoyed reading it…!!!

Message Contract in WCF

Few years back, when WCF was introduced, i was very eager to learn about this technology. I got few chances to work on it and i came across the concept of FaultContract and MessageContract. But was not able to dig deep into these concepts. Finally, I decided to spend some time to these concepts of MessageContracts as well.

What is Message Contract

While using wcf service, in order to send the data, like any custom class data, developers don’t have to do anything except adding the DataContract & DataMember attributes on the type of data, which is to be transferred. Developer need not to be concerned about serializing the data, converting it into SOAP xml and sending to the client. To check this, let’s create a sample application.

Add a new WCF application and add 2 classes named RequestData and ResponseData. RequestData is having a property named EmployeeId and ResponseData is having properties representing the details about the Id being sent by the client.In order to serialize this data and transfer it using SOAP, we will only add DataContract and DataMember attributes to these classes and there properties respectively.

Message Contract in WCF

Next, we will add a method in our service interface, which will take an input of type RequestData and return output of type ResponseData. Depending on the EmployeeId received in the request, it will return data of the user. So our implementation will be like the following :

Message Contract in WCF

Now, run the wcf test client, set a sample EmployeeId and invoke the method to see the results. We can see that the request and response SOAP xml’s contain the EmployeeId that we had set and its corresponding details respectively.

Message Contract in WCF

This is the normal way of sending the data through the SOAP. Sometimes we may have situation, where we need to control the way data is being sent, like we may need to send the data in the header of the SOAP or control the overall structure of what data is being sent in the header or body etc. In that case, using DataContract & DataMember is not the solution.

So let’s change some of our existing requirement and approach, where, we would like to send the EmployeeId in the header of the request xml and get back the EmployeeName, EmployeeDesignation in body of the response xml and EmployeeUserName in the header of response xml. To do this, we need to alter our RequestData and ResponseData classes slightly and decorate them with MessageContract and its related attributes named MessageHeader and MessageBodyMember attributes. For the data which we want to send in the header, we add MessageHeader attribute and for data that we want to send in body xml, we add MessageBodyMember attribute. On the whole, we add the MessageContract attribute on these classes, so that these can be serialized for transfer. So our changed code becomes :

Message Contract in WCF

So all set now. We just need to run the wcf test client and invoke the method again and we can see the results.

Message Contract in WCF

This what we changed the code for. We have the EmployeeId in request header xml and EmployeeUserName in the response header xml. Other details are added in the response body xml. But using this process has got certain restrictions on it. These are :

  • Any method involving MessageContract types, can have only one input parameter and that too has to be a MessageContract type.
  • The return value can be either be void or any type that is of MessageContract type.

So this is the basic implementation of MessageContract. If you need to control the overall structure of the SOAP xml being used, you need to use MessageContract. Hope you enjoyed reading it…!!!

Fault Exception and Fault Contract in WCF

It is quite common to use try/catch exception in our methods and display a user friendly message at the UI. Actual technical error is never displayed to the front end user. But consider the case of service oriented applications, which act as an api and provide services to the clients. If any error occurs at the service end, we can simply catch the exception and perform the required action. But what about client ? Client which uses this service, will receive a long exception message, of which he has no idea about. Also, a good application should never display error messages at the front end. WCF provides a way of handling these situations, by the use of Fault Contract.

So let’s try to understand some basics of this concept.

What is Fault Exception ?

For this, we will create 2 applications. One will be our WCF service named Demo and another is WCF client, which will consume this service. Our service will be exposing an operation to client (named DivideNumber), to divide a number by zero. This is intentionally done to raise an exception in the service operation. We will not add any try-catch block in either of the applications. So when our service is ready, then add its reference in the client application and invoke the service method DivideNumber. Now run the application and see what happens.

Fault Contract in WCF

A big bang and the yellow screen will appear. But this will not give any idea to us, about what happened in the service. So we will do, what it suggests. We go to our service web.config and navigate to the serviceBehaviors section and change the setting includeExceptionDetailInFaults to true. 

Fault Contract in WCF

By setting this property to true allows the actual exception details to be sent to the client, consuming the service. Now, update the service reference in the client application and run the application again and we can see what was the actual exception and resolve it.

WCFFaultContract3

The error message that gets transferred in both the cases above, is passed through the <faultstring> tag in the response SOAP xml. We can test this through the WCF Test client. Run the service test client, invoke the method and we can see the exception string in the XML generated for the SOAP response.

Case 1, includes where we have not passed the details of the exception.

Case1

Case 2, is where we have passed the actual exception to the client, by setting includeExceptionDetailInFaults to true, in service web.config

Case2

But this kind of process should be only followed for the development environment and never in production environment. The reason being, a service oriented application should never expose about what exactly is happening behind the scenes. Exposing any exception like this can expose the logic you are using in your application, to the client. Also, displaying the exceptions to the client is never a good thing. 

Although its not a good thing to send the error information to the client, but still, the client should also get to know whether the operation he called for has succeeded or not. But the point is, if our service is being used by different languages like php, JAVA etc, then passing the actual .NET based exceptions to the client, is also not feasible or advisable. So here the role of FaultException class comes into the picture. The fault exception is used to pass the custom error message from the server to the client, inside the SOAP response xml. When the response is received by the client, the custom exception message set by the service, is also available in the <fault> tag in the SOAP.

In order to do this, the service needs to throw a new instance of the FaultException class, with the custom message set in its constructor. Let’s say, we pass the custom message “Service was unable to divide by zero.” in the constructor.

Fault Contract in WCF

Now run the test client and see the response xml. The custom message that we have added, will be now carried to the client, by the <fault> tag.

Fault Contract in WCF

It is more of like adding a try-catch on the entire communication between the client and the service. Exception is caught at the service level and is propagated to the client by using throw, via SOAP message . Client catches the exception and gets the exception details.

Now, update the service reference in the client application and run again. It will display the message set by the service. Even if we keep the setting includeExceptionDetailInFaults in web.config  to true or false, it will still display the message from the FaultException class, which the service has added. So the client will never come to know how exactly your service is working, but still get to know about the status of his request. 

Fault Contract in WCF

Fault Contract and strongly typed FaultExceptions

Now that we have the know that we can send exceptions to the client, wouldn’t it be great if we could send extra information related to the exception, apart from the custom exception message or send strongly typed exceptions, with selected information. Good news is that it is possible. WCF provides us FaultContract attribute to achieve this requirement. This attribute provides the ability to create strongly typed fault exceptions or in other words, we can create different custom classes to represent different types of exceptions which we can have in our application and allow them to propagate to the client application.

To do so, we will add a new class to represent our exception type and 3 properties to it, which will represent the entire exception to the client. Our class will be named ExceptionFaultContract and properties will be StatusCode, a user defined message and its description. Next, we need to add DataContract and DataMember attributes to this class.

Fault Contract in WCF

To pass this class as a strongly typed FaultException for this method, we need to add the FaultContract attribute on our method and specify its type using typeof expression. It is like List<String> represents a generic List of string type, setting the typeof property represents the FaultException of the type ExceptionFaultContract. This is what is meant by strongly typed FaultException.

It is mandatory to provide the typeof property with FaultContract. Also, if no fault contract attribute is applied, the default exception that will be returned by wcf will be of type FaultException.

Fault Contract in WCF

Our method implementation will now also change slightly to catch the exception and return the custom fault exception in the form of ExceptionFaultContract. For strongly typed fault exceptions, FaultException class uses FaultException<TDetail>, where TDetail represents the custom type. Compare this with the example of List<string> that we discussed above. So our code becomes like :

Fault Contract in WCF

Run the wcf test client and invoke the method. We can see the details of the custom message that we had set.

WCFFaultContract14

Now in the client application, we will catch the exception using the reference of this exception type defined in the service. Run the application and see the exception. This exception fault will be accessible through the Detail property of the FaultException instance.

Fault Contract in WCF

So we can see the details of the exception, that we had set in the service.

Why use FaultExceptions ?

This type of solution is very helpful in situations where client and server are of different platforms. For ex, you might have client applications in JAVA or php. So, if there is any .NET specific exception in the service, we can’t send the fault exception to the client directly, as client will have no about .NET based exceptions. They only need to know that an exception has occurred and if possible, a reason for the same. So it becomes very important to use FaultExceptions normally only or use the strongly typed fault exceptions.

So this was all about the basic concept of WCF fault exceptions and fault contracts. Hope you enjoyed reading it.

Compiled Query in LINQ


While using entity framework, it is very common to write a method and call it multiple times from different modules/sections of the applications. For ex: in a application, we may be fetching the list of States/Cities etc. So when we write a linq query to perform this operation, behind the scenes, this linq query is first checked for any syntax error, then it is converted into its SQL equivalent and finally executed in the database to fetch the results.

So imagine the situation, when this type of query is fired every-time, for each request it receives. The type of data it returns could be a list of thousands of records at a time. To add to the overhead of this operation, linq query will be first parsed, then converted into sql and finally executed in the database. So it can result in performance issues. One thing we could have done is using the stored procedures to handle this situation. Another alternative is to use compiled queries. So let’s discuss the second approach.

What is a Compiled query in LINQ ?

A compiled query is a cached version of the actual query, that we use to get the results. We write the query. For the first time it is parsed or verified for any kind of syntax error in linq, then converted into SQL version and is added into cache. So every subsequent request for this query, cached version of this query is used and thus avoids parsing and conversion of the linq query into its sql version.

Creating a compiled linq query 

To create a compiled query, we have a static method named Compile in System.Data.Objects.CompiledQuery namespace. It is a static function with 16 overload versions & it returns a generic Func delegate type. See the list of its definitions.

1

There are some important points to be noted here :

  • In the above definitions list, it specifies that TArg0 must be of type ObjectContext. This means that the first parameter passed to this method should be an instance or context of our entities which we are using.
  • TArg1…TArgn is the list of any other input parameters that are used to query the results or we can say, add to the filter condition of the query.
  • TResult is the final result or output that we expect from the query. It could be the list of cities or users etc. from the database.
  • The delegate variable we use to cache the query, will have the same signature as that of the Compile method, as it will act as a pointer to the function or we can say it is basically the return type of the method. Its like we have INT32 return type of a function and storing it in an INT32 type static variable.
  • The delegate variable which this method returns must be declared as static. By making this variable static, the sql version of the query is stored or cached in this variable. Any further requests to this query are then handled using this static variable.

An example to create a compiled LINQ query :

Let’s say we want to get the list of all the users of our application, who have their Id greater than 50. Our first step will be to write the Compile method, with signatures, having 2 input parameter of type context of entities and an integer type variable and returns us the list of the users. So our method will look like the following :

CompiledQuery2

By comparing the above code with the overload definitions of the Compile method(previous image), we can see that we have TArg0 as our object context of entities, TArg1 is a filter condition and TResult is the output of the query or List of the Users, in our example. Like TArg0 and TArg1, we can have up-to TArg15 as input parameters in the query.

Next, we will store the returned values in a delegate variable with same signatures, as that of our Compile method, returning the list of users. Make sure that the variable we declare is of static type. So our code becomes :

LINQ compiled Query

This is it. Now we just need to create a method in order to call this query again and again. In our case we will add a method named GetUsersByCompiledQuery. This will invoke our delegate, which will further execute the Compile method.

LINQ compiled Query

The point to note here is that for the very first time, this query may also take same amount of time for execution, as it would have done in case of normal linq query. But subsequent calls will take much less time then the first call, as it will be already compiled by then and its cache plan will be used. Another point to be mentioned, as per MSDN, Starting with the .NET Framework 4.5, LINQ queries are cached automatically.

So this was about the concept of Compiled Query in LINQ. Hope you enjoyed reading it.