Encrypt Connection String in web.config

Never keep clear plain connectionstring in web.config file. The risk and consequences of this is self expalanatory. All you need to do is follow below steps and you are through with this.

Steps to be followed.

 

  1. Go to Visual Studio Command prompt in the “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\”path.
  1. Encrypt Web.Config connectionStrings using below command;
  1. aspnet_regiis -pef “connectionStrings” path of the physical folder where web.config resides (e.g. aspnet_regiis -pef “connectionStrings” D:\ProjectName)
  1. You will get the message “Encrypting configuration section… Succeeded!”
  1. Run Following Commands;
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “ASPNET”
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “NETWORK SERVICE”
  1. aspnet_regiis -pa “NetFrameworkConfigurationKey” “NT AUTHORITY\NETWORK SERVICE”
  1. Restart IIS

Bypass specific IP from rendering google analytics code

To bypass specific IP from rendering google analytics code, follow the following steps.

  1. List the IP which you wants to bypass from rendering into your web application, and add in web.config file

    e.g. <add key=ByPassUrl value=101.101.101.100/>

  2. Create a Usercontrol and named “GoogleAnalytics.ascx” replace your google analytics code with “<google analytics code here>“.

    <%@Control Language=”C#” AutoEventWireup=”true” CodeFile=”GoogleAnalytics.ascx.cs”
    Inherits=”Include_GoogleAnalytics”%>

    <script type=”text/javascript”>

    <% if (ConfigurationManager.AppSettings[“showGoogleAnalytics”] == “True”) {%>

    <% if (!strByPassUrl.Contains(requestUrl)) {%>

    var _gaq = _gaq || [];

    _gaq.push([‘_setAccount’, <google analytics code here>]);

    _gaq.push([‘_trackPageview’]);

    (function() {

    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;

    ga.src = (https: == document.location.protocol ? https://ssl : http://www) + ‘.google-analytics.com/ga.js’;

    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);

    })();

    <% } %>

    <% } %>

    </script>

     

  3. Declare following 2 public variable in “GoogleAnalytics.ascx.cs” file

    public string requestUrl = HttpContext.Current.Request.UserHostAddress.ToString();
    public
    string strByPassUrl = clsCommon.value(“ByPassUrl”);

  4. Add “GoogleAnalytics” user control in master page of the application within <Head></Head> tag.

    <head runat=”server”>

    <uc2:GoogleAnalytics ID=”GoogleAnalytics1″ runat=”server”/>

    </head>

Note :- 1) Before Copying Google analytics code verify with google analytics script, provided in google analytics account.

2) check if “showGoogleAnalytics” key is present in web.config file.

Windows Communication Foundation in Framework 4.0

Windows Communication Foundation (WCF) provides the following improvements:

  • Configuration-based activation: Removes the requirement for having an .svc file.
  • System.Web.Routing integration: Gives you more control over your service’s URL by allowing the use of extensionless URLs.
  • Multiple IIS site bindings support: Allows you to have multiple base addresses with the same protocol on the same Web site.
  • Routing Service: Allows you to route messages based on content.
  • Support for WS-Discovery: Allows you to create and search for discoverable services.
  • Standard endpoints: Predefined endpoints that allow you to specify only certain properties.
  • Workflow services: Integrates WCF and WF by providing activities to send and receive messages, the ability to correlate messages based on content, and a workflow service host.
  • WCF REST features:
    • Web HTTP caching: Allows caching of Web HTTP service responses.
    • Web HTTP formats support: Allows you to dynamically determine the best format for a service operation to respond in.
    • Web HTTP services help page: Provides an automatic help page for Web HTTP services, similar to the WCF service help page.
    • Web HTTP error handling: Allows Web HTTP Services to return error information in the same format as the operation.
    • Web HTTP cross-domain JavaScript support: Allows use of JSON Padding (JSONP).
  • Simplified configuration: Reduces the amount of configuration a service requires

WCF Architecture

The following figure illustrates the major components of WCF.


 
 

Contracts

Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

– Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

– It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

– Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

– Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

– It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior – Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior – Tells how and whether metadata is available to outside world.
  • Instance Behavior – Specifies how many instance of the service has to be created while running.
  • Transaction Behavior – Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior – Controls how a message is processed by the WCF Infrastructure.

Messaging

– Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels
    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
  • Protocol Channels
    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

– Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS
    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service
    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting
    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service
    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

Endpoints: Address, Bindings, and Contracts

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.

All the WCF communications are take place through end point. End point consists of three components which are known as ‘ABC’: ‘A’ for Address, ‘B’ for Binding and ‘C’ for Contracts.

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g

http://localhost/MyService/TestCalculator.svc

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

A binding has several characteristics, including the following:

  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) – Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) – Defines information to be used in the binding such as Security, transaction or reliable messaging capability

The following table gives some list of protocols supported by WCF binding.

Binding Description
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract

Contracts specifies the info for how the service is implemented and what it offers. Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

Example:

Endpoints will be mentioned in the web.config file on the created service.

<system.serviceModel>
<services>
      <service
        behaviorConfiguration="TestServiceBehavior">
       <endpoint
         address="http://localhost/MyService/TestCalculator.svc" contract="ITestService"
          binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

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.The main feature of WCF is it’s security.
WCF = Web services + .Net Remoting + MSMQ + (COM+)

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS,

windows activation service (WAS),

Self-hosting,

Managed 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 It Can be accessed only over HTTP Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

Delegates

Delegates is also known as Type Safe pointer.

To understand type Safe Pointer, you need to understand call back function used in C++. Call back function is generally implemented in Business Tier in 3-tier architecture. Once business logic is implemented, it requires memory address of the function or method to use it. This memory address does not have any information of Method signature, so it can be called as it is not Type Safe.

But Delegates has the feature of callback in Safe way, as it take cares of signature information.

How to define delegate,

Public Delegate Sub MakeDelegate (ByVal EmployeeID As String)

We are declaring public delegate, so it can be accessed from anywhere in the application.

Here we are going to define a Employee class which uses the delegates and method.

Public Class Employee
    Public FirstName As String
    Public LastName As String
 
    Public Sub ValidEmployee (ByVal objDelegate As MakeDelegate, _
                                ByVal EmployeeID As String)
        If EmployeeID.StartsWith ("MKT") Then
            objDelegate.Invoke(EmployeeID)
        End If
    End Sub
End Class

The method ValidEmployee is going to accept the EmployeeID and a Delegate Object of type "MakeDelegate" as the parameters and validate whether it is a Starting with E1 and invoke the Delegate Object accordingly.

Dim objEmployee As Employee = New Employee()

        Dim objDelegate As MakeDelegate
        objDelegate = AddressOf NotifyEmployee
 
        objEmployee .FirstName = txtFirstName.Text
        objEmployee.LastName = txtLastName.Text
 

objEmployee.ValidateEmployee(objDelegate, txtEmployeeID.Text)

We assign the local procedure "NotifyEmployee", which is declared and defined inside the Windows Form Class to the Delegate Object.
Private Sub NotifyEmployee(ByVal EmployeeID As String)

MsgBox("This Employee is from Marketing Department") End Sub

Once we assign the instance of the Delegate, we must provide the address of a method implementation with a matching method signature.

Serialization in the .NET Framework

Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system. This object will actually be an instance of a custom type, including any properties or fields you may have set.

The first step in any serialization process is to take the instance of the object and convert it to a memory stream. From there we have the ability to perform any number of operations with (file IO, database IO, etc.).

There are 2 types of serialization. Binary serialization and xml serialization

Core Serialization Methods

#region Binary Serializers

public static System.IO.MemoryStream SerializeBinary(object request) {

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

System.IO.MemoryStream memStream = new System.IO.MemoryStream();

serializer.Serialize(memStream, request);

return memStream;

}

public static object DeSerializeBinary(System.IO.MemoryStream memStream) {

memStream.Position=0;

System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =

new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

object newobj = deserializer.Deserialize(memStream);

memStream.Close();

return newobj;

}

#endregion

#region XML Serializers
 
public static System.IO.MemoryStream SerializeSOAP(object request) {
  System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer = 
  new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
  System.IO.MemoryStream memStream = new System.IO.MemoryStream();
  serializer.Serialize(memStream, request);
  return memStream;
}
 
public static object DeSerializeSOAP(System.IO.MemoryStream memStream) {
  object sr;
  System.Runtime.Serialization.Formatters.Soap.SoapFormatter deserializer = 
  new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
  memStream.Position=0;
  sr = deserializer.Deserialize(memStream);
  memStream.Close();
  return sr;
}
#endregion