Sunday, 21 August 2016
Action Filters in MVC
Sometimes you want to perform or inject some logic either before an execution of action method or after an execution of action method. so to achieve this , ASP.NET MVC provides action filters.
Action filters are custom attributes that provide a declarative means to add pre-action and post-action behavior to controller action methods.
The base class fo any filter the ASP.NET MVC framework includes a base
The base
Action filters are custom attributes that provide a declarative means to add pre-action and post-action behavior to controller action methods.
The base class fo any filter the ASP.NET MVC framework includes a base
ActionFilterAttribute
class. This class implements both the IActionFilter
and IResultFilter
interfaces and inherits from the Filter
class. The base
ActionFilterAttribute
class has the following methods that you can override:- OnActionExecuting – This method is called before a controller action is executed.
- OnActionExecuted – This method is called after a controller action is executed.
- OnResultExecuting – This method is called before a controller action result is executed.
- OnResultExecuted – This method is called after a controller action result is executed.
There are some in build action filters in MVC:
ASP.NET MVC provides the following types of action filters:
- Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class is one example of an authorization filter.
- Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
- Result filter, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.
- Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. TheHandleErrorAttribute class is one example of an exception filter.
How to implement custom action filter:
Step 1: Create a custom class and inherit with "ActionFilterAttribute" class and override its method.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace CustomActionFilter.Models
{
public class CustomAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted method call", filterContext.RouteData);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting method call", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted method call", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting method call", filterContext.RouteData);
}
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Custom Action Filter Log");
}
}
}
Step 2: add custom class as an attribute for a action method.
public class HomeController : Controller
{
//
// GET: /Home/
[CustomAttribute]
public ActionResult Index()
{
return View();
}
}
Now run the application and you will see the out put which you have mention in custom class.
Thursday, 14 July 2016
Reason of Creating WCF
Modern Application[Distributed Application] development we use different architechtures and technologies for communication
i.e:
· COM+
· .NET Enterprise Services
· MSMQ
· .NET Remoting
· Web Services
As there are various technologies. they all have different architechtures. so learning all them are tricky and tedious.
one need to focus on each technologies to develop rather than the application business logic
so microsoft unifies the capabilities into single, common, general service oriented programming model for Communication. WCF provides a common approach using a common API which developers can focus on their application rather than on communication protocol.
Now-a-days we call it WCF.
What Exactly WCF Service Stands For?
WCF lets you asynchronus messages transform one service endpoint to another.
The Message Can be simple as
· A Single Character
· A word
sent as XML
· complex data structure as a stream of binary data
Windows Communication Foundation(WCF) supports multiple language & platforms.
WCF Provides you a runtime environment for your services enabling you to expose CLR types as Services and to consume other Services as CLR Types.
A few sample scenarios include:
· A secure service to process business transactions.
· A service that supplies current data to others, such as a traffic report or other monitoring service.
· A chat service that allows two people to communicate or exchange data in real time.
· A dashboard application that polls one or more services for data and presents it in a logical presentation.
· Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
· A Silverlight application to poll a service for the latest data feeds.
Why on Earth We Should Use WCF?
· from a Code Project Article, thanks to @Mehta Priya I found the following Scenarios to illustrate the concept. Let us consider two Scenario:
· The first client is using java App to interact with our Service. So for interoperability this client wants the messages in XML format and the Protocol to be HTTP.
· The Second client uses .NET so far better performance this clients wants messages in binary format and the protocol to be TCP.
Without WCF Services
now for the stated scenarios if we don't use WCF then what will happen let's see with the following images:
· Scenario 1 :
· Scenario 2:
These are two different technologies and have completely differently programming models. So the developers have to learn different technologies. so to unify & bring all technologies under one roof. Microsoft has come with a new programming model called WCF.
How WCF Make things easy ?
one implement a service and he/she can configure as many end points as it required to support all the client needs. To support the above 2 client requirements -we would configure 2 end points -we can specify the protocols and message formats that we want to use in the end point of configuration
Tuesday, 5 July 2016
Difference Between IEnumerable and IEnumerator
The IEnumerable interface contains an abstract
member function called GetEnumerator() and return an interface IEnumerator
on any success call. This IEnumerator interface will allow us to iterate
through any custom collection.
·
IEnumerable contains a single method,
GetEnumerator, which returns an IEnumerator.
·
The foreach statement of the C# language hides the complexity of the enumerators.
Therefore, using foreach is recommended instead of directly manipulating the
enumerator.
·
IEnumerators can be used to read the data in the
collection, but they cannot be used to modify the underlying collection.
·
Initially, the enumerator is positioned before
the first element in the collection. You must call the MoveNext method
to advance the enumerator to the first element of the collection before reading
the value of Current;
otherwise, Current is
undefined.
sets Current to
the next element.
·
If MoveNext passes the end of the collection,
the enumerator is positioned after the last element in the collection and
MoveNext returns false. When the enumerator is at this position, subsequent
calls to MoveNext also return false. If the last call to MoveNext returned
false, calling Current throws an exception.
IEnumerable
doesn’t remember the state, which row or record it is iterating while IEnumerator remember it.
Let us see with
example:
public class Program
{
public void PrintAgeUpto30(IEnumerator<int> age_IEnumerator)
{
while
(age_IEnumerator.MoveNext())
{
Console.WriteLine(age_IEnumerator.Current);
if (age_IEnumerator.Current > 20)
{
Console.WriteLine("PrintGreaterThan30 is
called");
PrintGreaterThan30(age_IEnumerator);
}
}
}
public void PrintGreaterThan30(IEnumerator<int> age_IEnumerator)
{
while
(age_IEnumerator.MoveNext())
Console.WriteLine(age_IEnumerator.Current);
}
public static void Main()
{
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);
Program p=new Program();
IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
p.PrintAgeUpto30(age_IEnumerable.GetEnumerator());
}
}
Output is:
Example with
IEnumerable:
Here we are writing
the same program by using IEnumrable and the output is different
public class Program
{
public void PrintUpto30(IEnumerable<int> age_IEnumerable)
{
foreach (int age in age_IEnumerable)
{
Console.WriteLine(age);
if (age > 20)
{
Console.WriteLine("PrintGreaterThan30 is
called");
PrintGreaterThan30(age_IEnumerable);
}
}
}
public void PrintGreaterThan30(IEnumerable<int> age_IEnumerable)
{
foreach (int age in age_IEnumerable)
Console.WriteLine(age);
}
public static void Main()
{
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);
Program p=new Program();
IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
p.PrintUpto30(age_IEnumerable);
}
}
Conclusion:
1. IEnumerator use While, MoveNext, current to get current
record.
2.
IEnumerable doesn’t remember state for current index.
3.
IEnumerator persists state means which row it is reading currently.
4.
IEnumerator cannot be used in foreach loop.
5. IEnumerable is the base interface for all non-generic
collections that can be enumerated.
6. IEnumerator is the base interface for all non-generic
enumerators.
What is difference between Generic and Non generic collection
Non - generic and generic collection?
Generic collections - These are the collections that can hold data of same type and we can decide while initializing what type of data that collections can hold.
Advantages - Type Safe, Secure, reduced overhead of implicit and explicit conversions.
Non generic collections: it hold elements of different datatypes, it hold all elements as object type.
so it includes overhead of implicit and explicit conversions.There can be runtime errors
so it includes overhead of implicit and explicit conversions.There can be runtime errors
Saturday, 2 July 2016
Early Binding and Late Binding
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;//used for late binding
using India;//used for early binding
namespace TestEarlyAndLateBinding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//early binding
private void button2_Click_1(object sender, EventArgs e)
{
Employee emp = new Employee();
MessageBox.Show(emp.EmployeeName());
}
//late binding
private void button1_Click_1(object sender, EventArgs e)
{
Assembly ptr = Assembly.LoadFrom(@"D:\TestBinding\LateBinding\Employee.dll");
Type type = ptr.GetType("India.Employee");//import name space and its class
object obj = Activator.CreateInstance(type);
MethodInfo mInfo = type.GetMethod("EmployeeName");
MessageBox.Show(mInfo.Invoke(obj, null).ToString());
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;//used for late binding
using India;//used for early binding
namespace TestEarlyAndLateBinding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//early binding
private void button2_Click_1(object sender, EventArgs e)
{
Employee emp = new Employee();
MessageBox.Show(emp.EmployeeName());
}
//late binding
private void button1_Click_1(object sender, EventArgs e)
{
Assembly ptr = Assembly.LoadFrom(@"D:\TestBinding\LateBinding\Employee.dll");
Type type = ptr.GetType("India.Employee");//import name space and its class
object obj = Activator.CreateInstance(type);
MethodInfo mInfo = type.GetMethod("EmployeeName");
MessageBox.Show(mInfo.Invoke(obj, null).ToString());
}
}
}
Message Layer security in WCF
Message layer security:
Message security uses the WS-Security specification to secure
messages. The specification describes enhancements to Simple Object
Access Protocol (SOAP) messaging to ensure confidentiality, integrity, and
authentication at the SOAP message level (instead of the transport level).
Message security is available on all of the bindings except
for netNamedPipeBinding and MSmqIntegrationBinding.
When using Windows authentication, message security uses the
service’s Windows token to provide message security. When using non-Windows
authentication such as username, certificate, or issue token authentication,
you have to configure a service certificate as service credentials. Message
security uses the service certificate for message protection.
“Message level security encrypts request /
response messages using WS-Security specifications. It encloses security
credentials and claims with every message. Each message either signed or
encrypted. Message Security provides end-to-end channel security and is
independent of transport protocol.”
- Message Security
is not dependent on WCF protocols. It provides the security regardless of binding
used.
Lets see how to implement Message level
security in WCF.
Step1: vs command prompt run as
administrator:
We need to create both
Server certificates.
c/> makecert -sr
currentuser -ss My -a sha1 -n cn= WCfMsgTestServer -sky exchange –pe
Note: In order to do so, you need to install SDK
tools from microsoft. If you install , you may findmakecert.exe
in "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin".
in "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin".
here in above command
1. Currentuser is storeLocation
2. My is storeName
3. vinodCertificateServer1 is findValue.
Step2:
The certificates is
created but it is not still under trusted category. For that Open Microsoft
Management Console. Go to Run --> execute "MMC"
Now console is opened, go to File --> Click on "Add/Remove Snap-in" --> Now select Certificates on left pane and click "Add" button. open certificate window.
Now console is opened, go to File --> Click on "Add/Remove Snap-in" --> Now select Certificates on left pane and click "Add" button. open certificate window.
c>mmc
fileàadd/remove
certificateàcertificateàaddàfinish:
main window of mmcàcertifieàpersonalàcertificate
(now you will get certificate that created in step 1)
Now, certificates were
added to console view. There will be different categories of certificates. If
you open Personal folder, we can find the certificates we created in earlier
steps. Copy them to Trusted People folder.
Step3: Insert
below code snippets in you server config file.
add bindings
<bindings>
<wsHttpBinding>
<binding name="MyMessage">
<security>
<message clientCredentialType="None"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
Step 5: map
binding into end point.
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyMessage"
contract="TestMessageLayerSecurity.IService1">
Step 7: Add service
credential into behavior tag
Update behavior
section
<behaviors>
<serviceBehaviors>
<behavior>
[--Add service credential--]
<serviceCredentials>
<clientCertificate>
<authentication
certificateValidationMode="None"/>
</clientCertificate>
<serviceCertificate
findValue="vinodCertificateServer1"
storeLocation="CurrentUser" storeName="My"
x509FindType="FindBySubjectName"></serviceCertificate>
</serviceCredentials>
[--END--]
</Behaviour>
</serviceBehaviors>
</behaviors>
Step 8:
Add this at clien end:
NameSpace: using System.ServiceModel.Security;
Service1Client svcc = new Service1Client();
svcc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode
= X509CertificateValidationMode.None;
Step 9:
Remove identity section in wcf web config file
<identity>
<dns value="localhost"/>
</identity>
http://pratapreddypilaka.blogspot.in/2011/10/wcf-implementing-message-level-security.html
http://pratapreddypilaka.blogspot.in/2011/10/wcf-implementing-message-level-security.html
Subscribe to:
Posts (Atom)
Contact Us: | |
Email: |
Vinodkumar434@gmail.com, vinodtechnosoft@gmail.com |
Skype Name: |
vinodtechnosoft |