<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Sampath Kumar Kamati's Blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/sakamati/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/sakamati/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 03:50:09 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>ASP.NET In-Proc Session State vs Out-Proc Session State</title>
      <link>https://docs.microsoft.com/archive/blogs/sakamati/asp-net-in-proc-session-state-vs-out-proc-session-state</link>
      <pubDate>Tue, 30 Aug 2016 16:35:52 GMT</pubDate>
      <dc:creator><![CDATA[Sampath Kumar Kamati]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/sakamati/?p=75</guid>
      <description><![CDATA[Recently we faced a scenario, where a piece of code in ASP.NET MVC application works fine in local...]]></description>
      <content:encoded><![CDATA[Recently we faced a scenario, where a piece of code in ASP.NET MVC application works fine in local development machine and same code fails to work in test environment. The code is pretty simple and can't behave odd in test environment. During the troubleshoot process, we have decided to use in-proc session state in test environment instead of custom out-proc session state (App Fabric Session State provider to be specific), since this is the last difference we could see between local development machine and test environment. To our surprise this did in fact worked and same code works fine now in test environment after changing the session state mode to in-proc.

This interesting scenario raised a question, if there is any difference between in-proc session state and out-proc session state. After further analysis, it is identified that there is indeed a difference in the way complex objects are stored in in-proc session state and out-proc session state.

Lets consider an example to understand the difference better. In this example we have two classes named Employee and Address. Employee class has a property of type Address along with other string type properties.

<img src="https://msdnshared.blob.core.windows.net/media/2016/08/ClassStructure.jpg" alt="ClassStructure" width="487" height="216" class="aligncenter size-full wp-image-85" />

&nbsp;

When the objects (or instances) of above types is stored in session state using the lines of code depicted below, you may notice the difference between the memory layout of objects in In-Proc session state and Out-Proc session state.

<img src="https://msdnshared.blob.core.windows.net/media/2016/08/SessionStateDifference.jpg" alt="SessionStateDifference" width="1268" height="1261" class="aligncenter size-full wp-image-95" />

&nbsp;

In case of In-Proc session state, the objects when storing in session, gets stored in the local memory space of W3WP process whereas in case of Out-Proc session sate, the objects gets serialized and stored in database or some other back-end storage. When accessing the session state data in case of Out-Proc, object gets deserialized first and then loaded into process memory. Hence if you notice, the Address object is loaded two times into process's memory in case of out-proc session state.One instance as a reference of Employee object and another as a stand-alone Address object.

So, <strong>Session["Employee"].Location</strong> and <strong>Session["Address"]</strong> point to two separate memory locations in case of Out-Proc and same memory location in case of In-Proc session state.

Consider that below line gets executed to change/modify the city of employee to Singapore:

<strong>Session["Employee"].Location.City = "Singapore";</strong>

Now, when reading the city of employee using the below line gives two different results:

<strong>Session["Address"].City </strong><em>// Returns "Singapore" in case of  in-proc session state and old/unmodified value in case of out-proc session state</em>

Please be careful in these scenarios, and I personally recommend to test your application by using SQL Session state instead of in-proc session state in local development box before shipping the code to test/staging environment.

It is very easy to configure your local ASP.NET application to use SQL Session state. Follow <a href="https://support.microsoft.com/en-sg/kb/317604">https://support.microsoft.com/en-sg/kb/317604</a> to configure SQL Server to store ASP.NET session state.

Happy Programming !!!

&nbsp;]]></content:encoded>
    </item>
    <item>
      <title>Little strange thing</title>
      <link>https://docs.microsoft.com/archive/blogs/sakamati/little-strange-thing</link>
      <pubDate>Sun, 06 Mar 2016 07:01:00 GMT</pubDate>
      <dc:creator><![CDATA[Sampath Kumar Kamati]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/sakamati/2016/03/06/little-strange-thing/</guid>
      <description><![CDATA[Last week, my colleague and I were working on an issue in which we had to restrict user from...]]></description>
      <content:encoded><![CDATA[<p>Last week, my colleague and I were working on an issue in which we had to restrict user from clicking the same submit button (on a form rendered in a browser) multiple times. We thought of handling it through the client side JavaScript. It was&nbsp;a simple fix to handle onClick event of the submit button and disable the button. We did it by using jQuery and the code shown below:</p>
<pre class="scroll"><code class="js">$("#submitButton").on("click", function()<br />{<br /> $(this).attr('disabled','disabled');<br />});</code></pre>
<p>We had tested the fix and was working fine. So, went back home.</p>
<p>THE NEXT DAY !!!</p>
<p>The next day we started seeing that user is unable to submit the form at all. (STRANGE !) After a bit of analysis we figured out that, this is happening only in Chrome browser while we had verified it in Internet Explorer.</p>
<p>This is interesting. (<strong>PROBLEM</strong>) Disabling the submit button on client-side using JavaScript is completely blocking the form from submitting in Chrome while it works well in IE and Firefox. (Not tested in other browsers).</p>
<p>To understand this correctly, I have created a simple HTML page - Page1.html has a form and submit button, which upon clicking submits the form to another page.</p>
<p><strong>(FIX)&nbsp;</strong>Hence, as a work around, we had used setTimeOut() function of JavaScript as shown in the code below:</p>
<pre class="scroll"><code class="js">$("#submitButton").on("click", function()<br />{<br />setTimeout(function(that){ <br />$(that).attr('disabled','disabled'); <br />}, 1, this); <br />});</code></pre>
<p>So, this way browser does not block the form from submitting and submit button gets disabled after 1 milli second from the button click action. This works well in three of the browsers - Chrome, IE, Firefox.</p>
<p>Attaching the HTML page used for this little experiment.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/67/12/16/Page1.html" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-67-12-16/Page1.html">Page1.html</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Semantic Logging in ASP.NET MVC</title>
      <link>https://docs.microsoft.com/archive/blogs/sakamati/semantic-logging-in-asp-net-mvc</link>
      <pubDate>Sat, 23 Jan 2016 22:30:00 GMT</pubDate>
      <dc:creator><![CDATA[Sampath Kumar Kamati]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/sakamati/2016/01/23/semantic-logging-in-asp-net-mvc/</guid>
      <description><![CDATA[Overview  

This post gives you an introduction to Semantic Logging and also provides step by...]]></description>
      <content:encoded><![CDATA[<strong> <span style="font-size: medium">Overview </span> </strong>

This post gives you an introduction to Semantic Logging and also provides step by step guide to use Semantic Logging in an application.

Semantic Logging helps us to log structured information to variety of logging destinations. Logging plays major role in an application during troubleshooting or debugging. Poor logging causes problems while troubleshooting an issue in production application.

.NET 4.5 framework introduced a class <strong>EventSource </strong>in the namespace <strong>System.Diagnostics.Tracing </strong>which helps us in consuming the Event Tracing for Windows (ETW) infrastructure. ETW infrastructure is built into Windows Operating System to collect events and is proven to be strong for many years now.

Semantic logging can be done in two different ways:
<ol>
 	<li><strong>In-Process</strong>In this scenario, all the components run in the same process as your application. Hence the event generator (application), event listeners and event sinks all run in the sample process. If the applicaiton process crashes for some reason, we can not guarantee if the event gets logged in the destination, since all the buffered logs which are yet to be written to the log destination are gone. Enterprise Library Semantic Logging Application Block (SLAB) provides a set of destinations (sinks) to store events. Sinks include SQL server database, rolling file. SLAB also helps us to create custom sink.</li>
 	<li><strong>Out-of-Process</strong>In this scenario, application interacts with ETW infrastructure of windows to log the events to log destinations. Hence the event generator (application) runs in a different process than event listener. Event listener processes the events to log them to destinations. Enterprise Library Semantic Logging Application Block (SLAB) provides an out-of-proc windows service and console host to process the events generated from ETW.</li>
</ol>
<div>The below diagram from MSDN highlights the difference between above two approaches:</div>
<div><img title="Dn775006.DB3051973644F4C0F4D5986EE419A2D9(en-us,PandP.10).png" id="DB3051973644F4C0F4D5986EE419A2D9" alt="Dn775006.DB3051973644F4C0F4D5986EE419A2D9(en-us,PandP.10).png" src="https://msdn.microsoft.com/dynimg/IC742364.png" /></div>
&nbsp;
<div><strong> <span style="font-size: medium">Developing ASP.NET MVC Application using the Semantic Logging Application Block in Out-of-Proc mode</span> </strong></div>
<div>
<ol>
 	<li>Create an ASP.NET MVC project in Visual Studio</li>
 	<li>Add one more Class Library project to this solution.</li>
 	<li>Create custom event source in this class library project.
<pre>    [EventSource(Name = "Sample-EventSource")]
    public class SampleEventSource : EventSource
    {
        public class Keywords
        {
            public const EventKeywords Application = (EventKeywords)1;
            public const EventKeywords Service = (EventKeywords)2;
            public const EventKeywords Database = (EventKeywords)4;
        }

        public class Tasks
        {
            public const EventTask Page = (EventTask)1;
            public const EventTask DBQuery = (EventTask)2;
        }

        private static SampleEventSource _log = new SampleEventSource();
        private SampleEventSource()
        { }

        public static SampleEventSource Log
        {
            get
            {
                return _log;
            }
        }

        [Event(101, Keywords = Keywords.Application,
            Level = EventLevel.Critical,
            Message = "Application failure: {0} ")]
        public void Failure(string message)
        {
            if (this.IsEnabled(EventLevel.Critical, Keywords.Application))
            {
                this.WriteEvent(101, message);
            }
        }

        [Event(102, Keywords = Keywords.Application,
            Level = EventLevel.Informational,
            Message = "Information: {0}")]
        public void Information(string message)
        {
            if (this.IsEnabled(EventLevel.Informational, Keywords.Application))
            {
                this.WriteEvent(102, message);
            }
        }
    }</pre>
</li>
 	<li>Add reference of class library project to ASP.NET MVC application</li>
 	<li>In ASP.NET MVC application, add one controller and few action methods to generate events from application
<pre>    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Test()
        {
            return View();
        }

        public ActionResult LogError()
        {
            SampleEventSource.Log.Failure("Error raised from LogError action method of Home controller.");
            return View();
        }

        public ActionResult LogInformation()
        {
            SampleEventSource.Log.Information("Information raised from LogInformation action method of Home controller.");
            return View();
        }
    }</pre>
</li>
 	<li>Download and Install PerfView tool from Microsoft Download Centre to view traces collected by ETW</li>
 	<li>Open PerfView tool, click <strong>Collect </strong>menu item to start collecting the ETW events</li>
 	<li><img width="512" height="394" class="size-full wp-image-135 aligncenter" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/PerfView-Start-1.jpg" /></li>
 	<li>In the new window, enter the provider name / event source name (with star symbol at the start). Click <strong>Start Collection </strong>button to start collecting the ETW events.</li>
 	<li><img width="1080" height="597" class="aligncenter size-full wp-image-145" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/PerfView-Start-2.jpg" /></li>
 	<li>Now, run the sample ASP.NET MVC application, and generate few events from the application</li>
 	<li>Go back to PerfView, click <strong>Stop Collection </strong>button to stop collecting events</li>
 	<li><img width="1080" height="597" class="aligncenter size-full wp-image-146" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/PerfView-Start-3.jpg" /></li>
 	<li>After few seconds, PerfView tool creates and ETL file, in which we can see the events generated by the application.</li>
 	<li><img width="519" height="427" class="aligncenter size-full wp-image-155" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/PerfView-Start-4.jpg" /></li>
 	<li>Click <strong>Events </strong>under the ETL file to see the events captured by PerfView tool. Search for the specific event source to see events generated by our application.</li>
 	<li><img width="1920" height="270" class="aligncenter size-full wp-image-165" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/PerfView-View-Events.jpg" /></li>
 	<li> An advantage of using PerfView tool during development is too see if there are any issues with the custom event source. For example, my initial custom event source had an issue which I figured out by running PerfView tool.</li>
 	<li><img width="1919" height="321" class="aligncenter size-full wp-image-126" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/PerfView-Error.jpg" /></li>
 	<li>Now, let us see how to setup SLAB out-of-process windows console to log the events to flat file destination</li>
 	<li>Back to Visual Studio, install the Nuget package - <strong>Semantic Logging Application Block - Out-of-process Service</strong><strong>
</strong></li>
 	<li><img width="1109" height="742" class="aligncenter size-full wp-image-175" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/Install-OOP-Service.jpg" /></li>
 	<li>Run PowerShell script i<strong>nstall-packages.ps1 </strong>from the installed nuget package location to resolve additional dependencies<strong>
</strong></li>
 	<li><img width="1110" height="293" class="aligncenter size-full wp-image-105" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/Install-OOP-Service-2.jpg" /></li>
 	<li>Update the <strong>SemanticLogging-svc.xml</strong> file with the required event source and sinks. Let us configure it to receive events from our sample event source and log to a flat file.
<pre>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration xmlns="https://schemas.microsoft.com/practices/2013/entlib/semanticlogging/etw"
               xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="https://schemas.microsoft.com/practices/2013/entlib/semanticlogging/etw SemanticLogging-svc.xsd"&gt;
  &lt;traceEventService/&gt;
  &lt;sinks&gt;    
    &lt;flatFileSink name="svcRuntime" fileName="SemanticLogging-svc.runtime.log" &gt;
      &lt;sources&gt;        
        &lt;eventSource name="Sample-EventSource" level="Error"&gt;&lt;/eventSource&gt;
      &lt;/sources&gt;
      &lt;jsonEventTextFormatter formatting="Indented"/&gt;
    &lt;/flatFileSink&gt;
  &lt;/sinks&gt;
&lt;/configuration&gt;</pre>
</li>
 	<li>Run the out-of-process windows console to capture the events generated from our MVC application. Use the following command to run the console host <strong>SemanticLogging-svc.exe -c</strong><strong>
</strong></li>
 	<li><img width="983" height="666" class="aligncenter size-full wp-image-116" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/Install-OOP-Service-4.jpg" /></li>
 	<li>Once again run the sample ASP.NET MVC application, and generate few events from the application. These events are captured by out-of-process console program and are written to flat file. In fact, only Errors are written to flat file since we specified Level=Error in <strong>SemanticLogging-svc.xml</strong></li>
 	<li>Let us see one of the events stored in flat file. We see the event in JSON format, because we specified JSONEventTextFormatter in <strong>SemanticLogging-svc.xml</strong></li>
 	<li><img width="1782" height="659" class="aligncenter size-full wp-image-125" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/01/Install-OOP-Service-5.jpg" /></li>
 	<li>Source code is available in my github <a href="https://github.com/skamati/ASP.NET-MVC/tree/master/SemanticLoggingSample">here</a></li>
</ol>
</div>]]></content:encoded>
    </item>
    <item>
      <title>Creating OWIN based WS-Federation application</title>
      <link>https://docs.microsoft.com/archive/blogs/sakamati/creating-owin-based-ws-federation-application</link>
      <pubDate>Mon, 06 Jul 2015 23:59:00 GMT</pubDate>
      <dc:creator><![CDATA[Sampath Kumar Kamati]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/sakamati/2015/07/06/creating-owin-based-ws-federation-application/</guid>
      <description><![CDATA[Introduction
Recently I have worked on an ASP.NET MVC application which uses OWIN middleware...]]></description>
      <content:encoded><![CDATA[<p><span style="font-size: medium;"><strong>Introduction</strong></span></p>
<p>Recently I have worked on an ASP.NET MVC application which uses OWIN middleware components for WS-Federation authentication. This post gives you an overview about OWIN and step-by-step guide to create basic WS-Federation application using OWIN middleware components.</p>
<p><span style="font-size: medium;"><strong>What is OWIN?</strong></span></p>
<p>Open Web Interface for .NET (OWIN) defines an abstraction between .NET web servers and web applications. OWIN is a community-owned specification, not an implementation.&nbsp;The Katana project is a set of open-source OWIN components developed by Microsoft.</p>
<p>OWIN divides an application into four logical layers.</p>
<ol>
<li><em><strong>Host</strong></em>- manages the underlying process and orchestrates the request execution.
<p>Three primary hosting options as of now are (a)IIS (b)Custom Host (c)OwinHost.exe</p>
</li>
<li><em><strong>Server</strong></em>- opens a network socket, listens for requests, and sends them through the pipeline of OWIN components. These list of OWIN compoents (aka middleware) are specified in OWIN startup class.&nbsp;
<p>OWIN server is also responsible for populating the environment dictionary -&nbsp;<strong>IDictionary&lt;string, object&gt;</strong>. Currently, Katana project includes two server implementations:</p>
</li>
<ol>
<li>
<p><strong>Microsoft.Owin.Host.SystemWeb</strong>&nbsp;- Used by IIS</p>
</li>
<li>
<p><strong>Microsoft.Owin.Host.HttpListener - </strong>Used by Self-Host and OwinHost.exe</p>
</li>
</ol>
<li><em><strong>Middleware</strong></em>- is an independent component sits in the pipeline and does its work. We as developers build these middleware components to do specific and focused tasks and plug them in the pipeline. These middleware components can be visualized as traditional HTTPModules.
<p>The security related HTTPModules have moved to be OWIN middleware. Hence the functionality provided by traditional Windows Identity Foundation - WIF (two HTTP Modules -&nbsp;WSFederationAuthenticationModule,&nbsp;SessionAuthenticationModule) modules is already available as OWIN middleware components.&nbsp;</p>
<p>And this blog post explains steps to create a basic OWIN based application which uses OWIN middleware components for WS-Federation authentication.</p>
</li>
<li><strong><em>Application</em></strong>&nbsp;- OWIN based application is no different from the any web application except the fact that, it gets the context about the request from the environment dictionary and registers list OWIN middleware components in Startup class.</li>
</ol>
<div>To summarize, OWIN is an abstraction to decouple application programming models and frameworks from server and hosting infrastructure. The separation of middleware components from each other and from the underlying infrastructure components enables the components to evolve in their own pace.</div>
<p><span style="font-size: medium;"><strong>Create simple ASP.NET MVC Application</strong></span></p>
<p>Create an empty ASP.NET MVC project in Visual Studio</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/0741.1.CreateProject.JPG" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/0741.1.CreateProject.JPG"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/0741.1.CreateProject.JPG" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x550/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/0741.1.CreateProject.JPG" alt="" border="0" /></a></p>
<p>Install the following OWIN related Nuget packages in the project using the Package Manager Console.&nbsp;These packages are required for the WS-Federation authentication.</p>
<ol>
<li>Install-Package <strong>Microsoft.Owin.Host.SystemWeb</strong></li>
<li>Install-Package <strong>Microsoft.Owin.Security.WsFederation</strong></li>
<li>Install-Package <strong>Microsoft.Owin.Security.Cookies</strong></li>
</ol>
<p>The above commands installs the OWIN hosting infrastructure and WS-Federation related middleware components.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/7840.2.InstalledPackages.JPG" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/7840.2.InstalledPackages.JPG"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/7840.2.InstalledPackages.JPG" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x550/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/7840.2.InstalledPackages.JPG" alt="" border="0" /></a></p>
<p>Add OWIN startup class by using Add -&gt; OWIN Startup class item on the context menu of project in Visual Studio.</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/5557.3.AddStartup.JPG" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/5557.3.AddStartup.JPG"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/5557.3.AddStartup.JPG" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x400/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/5557.3.AddStartup.JPG" alt="" border="0" /></a></p>
<p>In the Startup class add the following method to register two middleware components in OWIN pipeline to handle WS-Federation protocol.</p>
<pre class="scroll"><code class="csharp">public class Startup<br />{<br /> public void Configuration(IAppBuilder app)<br /> {<br /> // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888<br /> ConfigureAuth(app);<br /> }<br /> <br /> public void ConfigureAuth(IAppBuilder app)<br /> {<br /> app.UseCookieAuthentication(<br /> new CookieAuthenticationOptions<br /> {<br /> AuthenticationType = CookieAuthenticationDefaults.AuthenticationType<br /> });<br /> app.UseWsFederationAuthentication(<br /> new WsFederationAuthenticationOptions<br /> {<br /> MetadataAddress = "<span style="background-color: #ffff00;">https://login.microsoftonline.com/2c2a63d4-465c-464d-b7f5-6ccfd0dce5b8/federationmetadata/2007-06/federationmetadata.xml</span>",<br /> Wtrealm = "<span style="background-color: #ffff00;">https://testService.local/</span>",<br /> });<br /> <br /> app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);<br /> }<br />}</code></pre>
<p>Note that the MetadataAddress and Wtrealm are the values specific to my application and the STS I used in this sample. These values needs to be modified according to the application.</p>
<p>The&nbsp;two middleware components&nbsp;are involved in the&nbsp;WS-Federation authentication pipeline as&nbsp;mentioned below:</p>
<ul>
<li>WS-Federation authentication component&nbsp;- Handles the SAML tokens received from STS and redirects user to STS if not authenticated.</li>
<li>Cookie authentication component -&nbsp;Creates and drops a cookie (.AspNet.Cookies)&nbsp;on to users browser and manages the session between client browser and the relying party application.</li>
</ul>
<p>Note that in the above code snippet, we are setting the default authentication type to CookieAuthentication. If it is not so, you will see an infinite (actually 6)&nbsp;redirects between your application and STS and finally STS throws error.</p>
<p>Now, add a controller to the&nbsp;MVC application and decorate it with [Authorize] attribute.</p>
<pre class="scroll"><code class="csharp">[Authorize]<br />public class HomeController : Controller<br />{<br /> // GET: Home<br /> public ActionResult Index()<br /> {<br /> ViewBag.ClaimsIdentity = System.Threading.Thread.CurrentPrincipal.Identity;<br /> var claimsIdentity = System.Threading.Thread.CurrentPrincipal.Identity as ClaimsIdentity;<br /> ViewBag.DisplayName = claimsIdentity.Claims.First(c =&gt; c.Type == ClaimTypes.GivenName).Value;<br /> return View();<br /> }<br /> <br /> public ActionResult LogOff()<br /> {<br /> if (User.Identity.IsAuthenticated)<br /> {<br /> var owinContext = this.Request.GetOwinContext();<br /> var authProperties = new AuthenticationProperties();<br /> authProperties.RedirectUri = new Uri(this.HttpContext.Request.Url, new UrlHelper(this.ControllerContext.RequestContext).Action("PostLogOff")).AbsoluteUri;<br /> owinContext.Authentication.SignOut(authProperties);<br /> return View();<br /> }<br /> else<br /> {<br /> throw new InvalidOperationException("User is not authenticated");<br /> }<br /> }<br /> <br /> [AllowAnonymous]<br /> public ActionResult PostLogOff()<br /> {<br /> return View();<br /> }<br />}</code></pre>
<p><span style="font-size: small;">The above controller does not do much, just displays the list of claims received from the STS. Below CSHTML (View) actually displays the claims in a table format:</span></p>
<pre class="scroll"><code class="html">&lt;h2&gt;Welcome: @ViewBag.DisplayName&lt;/h2&gt;<br /> &lt;h3&gt;Values from Identity&lt;/h3&gt;<br /> &lt;table&gt;<br /> &lt;tr&gt;<br /> &lt;th&gt;<br /> IsAuthenticated<br /> &lt;/th&gt;<br /> &lt;td&gt;<br /> @ViewBag.ClaimsIdentity.IsAuthenticated<br /> &lt;/td&gt;<br /> &lt;/tr&gt;<br /> &lt;tr&gt;<br /> &lt;th&gt;<br /> Name<br /> &lt;/th&gt;<br /> &lt;td&gt;<br /> @ViewBag.ClaimsIdentity.Name<br /> &lt;/td&gt;<br /> &lt;/tr&gt;<br /> &lt;/table&gt;<br /> &lt;h3&gt;Claims from ClaimsIdentity&lt;/h3&gt;<br /> &lt;table border="1"&gt;<br /> &lt;tr&gt;<br /> &lt;th&gt;<br /> Claim Type<br /> &lt;/th&gt;<br /> &lt;th&gt;<br /> Claim Value<br /> &lt;/th&gt;<br /> &lt;th&gt;<br /> Value Type<br /> &lt;/th&gt;<br /> &lt;th&gt;<br /> Subject Name<br /> &lt;/th&gt;<br /> &lt;th&gt;<br /> Issuer Name<br /> &lt;/th&gt;<br /> &lt;/tr&gt;<br /> @foreach (System.Security.Claims.Claim claim in ViewBag.ClaimsIdentity.Claims)<br /> {<br /> &lt;tr&gt;<br /> &lt;td&gt;<br /> @claim.Type<br /> &lt;/td&gt;<br /> &lt;td&gt;<br /> @claim.Value<br /> &lt;/td&gt;<br /> &lt;td&gt;<br /> @claim.ValueType<br /> &lt;/td&gt;<br /> &lt;td&gt;<br /> @claim.Subject.Name<br /> &lt;/td&gt;<br /> &lt;td&gt;<br /> @claim.Issuer<br /> &lt;/td&gt;<br /> &lt;/tr&gt;<br /> }<br /> &lt;/table&gt;</code></pre>
<p><span style="font-size: medium;"><strong>Setup Relying Party in AD FS</strong></span></p>
<p>I used Azure Active Directory (AAD) as the Security Token Service (STS) and registered my sample MVC application as relying party. You can use any available STS.</p>
<p>While registering the relying party application be careful about the relying party URL/identifier. In my case I have used application URI (<a href="https://testService.local/">https://testService.local/</a>)&nbsp;as both URL and Identifier. You can also get the federation metadata URL from the STS. In case AAD, it is listed in the Metadata section of relying party application.</p>
<p>We use this federation metadata URL of STS as the MetadataAddress in the Startup class of MVC application.</p>
<p><strong><span style="font-size: medium;">Running the application</span></strong></p>
<p>I run the application by hosting it in my local IIS but that is just a personal preference. You can run it by pressing F5 in visual studio. However, based on this we need to update the Relying party application URL in STS and also in the Startup class of sample MVC application.</p>
<p>When you run the application, browser sends request to /Home/Index action of our MVC application. Since this action method is decorated with [Authorize] attribute, and since user is not authenticated yet, application throws 403 Forbidden error.</p>
<p>This 403 Forbidden error is caught by OWIN middleware component, and turns it into 302 Redirect to STS application by reading the Federation Metadata XML which we have specified in the Startup class.</p>
<p>Now user is redirected to STS website and user provides correct credentials to login to STS. Once STS validates the credentials, it constructs and sends the SAML token to the application via HTTP POST (this is done by auto-submitted &lt;form&gt;).</p>
<p>This POST request to our application along with SAML Token is again caught by OWIN middleware component. OWIN component now reads the SAML token constructs a session cookie&nbsp;(.AspNet.Cookies) out of it. This cookie is sent back to the browser establishing a session between our application and client browser.</p>
<p>Hence subsequent request to protected page (like /Home/Index) does not need to go through entire cycle. Whenever the request from client includes a valid session cookie, application decodes it and constructs the Identity out of it.</p>
<p><strong><span style="font-size: medium;">Sign out from the application</span></strong></p>
<p><span style="font-size: small;">To sign out from the application, I have used one more action method in the Home controller called - LogOff(). This method invokes the SignOut() method of OWIN authentication manager with an instance of AuthenticationProperties class. I have set a property - RedirectUri of authentication properties to redirect user back to our application page after sign out.</span></p>
<p><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">var</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;"> owinContext = </span></span><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">this</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">.Request.GetOwinContext();</span></span></p>
<p><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">var</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;"> authProperties = </span></span><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">new</span></span></span><span style="color: #2b91af; font-family: Consolas; font-size: small;"><span style="color: #2b91af; font-family: Consolas; font-size: small;"><span style="color: #2b91af; font-family: Consolas; font-size: small;">AuthenticationProperties</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">();</span></span></p>
<p>authProperties.RedirectUri = <span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">new</span></span></span><span style="color: #2b91af; font-family: Consolas; font-size: small;"><span style="color: #2b91af; font-family: Consolas; font-size: small;"><span style="color: #2b91af; font-family: Consolas; font-size: small;">Uri</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">(</span></span><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">this</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">.HttpContext.Request.Url, </span></span><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">new</span></span></span><span style="color: #2b91af; font-family: Consolas; font-size: small;"><span style="color: #2b91af; font-family: Consolas; font-size: small;"><span style="color: #2b91af; font-family: Consolas; font-size: small;">UrlHelper</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">(</span></span><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;"><span style="color: #0000ff; font-family: Consolas; font-size: small;">this</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">.ControllerContext.RequestContext).Action(</span></span><span style="color: #a31515; font-family: Consolas; font-size: small;"><span style="color: #a31515; font-family: Consolas; font-size: small;"><span style="color: #a31515; font-family: Consolas; font-size: small;">"PostLogOff"</span></span></span><span style="font-family: Consolas; font-size: small;"><span style="font-family: Consolas; font-size: small;">)).AbsoluteUri;</span></span></p>
<p>owinContext.Authentication.SignOut(authProperties);</p>
<p>&nbsp;</p>
<p>The &nbsp;above code snippet is used to redirect user back to our application after sign out.</p>
<p>I hope this blog post helps you understand about OWIN and implement WS-Federation authentication using OWIN in an MVC application. Attached the source code of my sample project.</p>
<p>Solution is now available in Git at the following location - <a href="https://github.com/skamati/ASP.NET-MVC/tree/master/SampleOWINApp">GitHub</a></p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Components.PostAttachments/00/10/62/61/01/SampleOWINApp.zip" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-62-61-01/SampleOWINApp.zip">SampleOWINApp.zip</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Customizing ADFS 3.0 Sign-in Page</title>
      <link>https://docs.microsoft.com/archive/blogs/sakamati/customizing-adfs-3-0-sign-in-page</link>
      <pubDate>Mon, 22 Jun 2015 06:18:00 GMT</pubDate>
      <dc:creator><![CDATA[Sampath Kumar Kamati]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/sakamati/2015/06/22/customizing-adfs-3-0-sign-in-page/</guid>
      <description><![CDATA[Introduction
In ADFS 3.0 (aka ADFS in Windows Server 2012 R2) customization of Sign-in page is...]]></description>
      <content:encoded><![CDATA[<p><span style="font-size: medium;"><strong>Introduction</strong></span></p>
<p><span style="font-size: small;">In ADFS 3.0 (aka ADFS in Windows Server 2012 R2) customization of Sign-in page is quite different from the earlier versions of ADFS. This&nbsp;post gives an overview of Sign-in page customization in ADFS 3.0.</span></p>
<p><br /><span style="font-size: medium;"><strong>Customization Options</strong></span></p>
<p><span style="font-size: small;">In ADFS 3.0 there is no dependency on IIS. Hence, there is no IIS available in the ADFS 3.0 Server. Because of this, you do not have any .aspx or .master page in the file system which you can go ahead and edit directly to apply the customizations you need.</span></p>
<p><span style="font-size: small;">In this version of ADFS 3.0, any customization should be done by using PowerShell commands and all the customizations are stored in the ADFS configuration database instead of file system. The advantage is that there is no need to update the files in individual ADFS instances in a farm kind of scenario. Execute the PowerShell commands once and all the ADFS instances in&nbsp;the farm are reflected with the customizations.</span></p>
<p><span style="font-size: small;"><img src="https://i-technet.sec.s-msft.com/dynimg/IC666077.png" alt="" /></span></p>
<p><span style="font-size: small;"><strong>Figure</strong>: General Sign-in page ADFS 3.0</span></p>
<p><span style="font-size: small;">There are two options for customizing the sign-in page.</span></p>
<p><strong><span style="font-size: small;">Customizing Logo, Footer Links, Sign-in description using PowerShell&nbsp;commands</span></strong></p>
<ul>
<li><span style="font-size: small;">PowerShell commands for customizing individual parts of the sign-in page are documented in Microsoft TechNet article - <a href="https://technet.microsoft.com/en-in/library/dn280950.aspx">https://technet.microsoft.com/en-in/library/dn280950.aspx</a></span></li>
<li><span style="font-size: small;">Though these PowerShell commands give you quick way to customize Logos and descriptions, sometimes you might need to customize the entire theme of the sign-in page by applying new styles.</span></li>
<li><span style="font-size: small;">I had a similar requirement to completely change the look of sign-in page. As we don't have much control using this option of customization, I had used the second option - using Custom Web Themes to customize sign-in page.</span></li>
</ul>
<p><strong><span style="font-size: small;">Custom Web Themes</span></strong></p>
<p style="padding-left: 30px;"><span style="font-size: small;">Using this option of customizing the sign-in page gives you much control since you now have control of the CSS and JavaScript files used in the sign-in page. The&nbsp;final sign-in page after applying custom web theme looks as below.</span></p>
<p style="text-align: justify; padding-left: 30px;"><span style="font-size: small;"><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/4338.ADFS-SignIn.png" original-url="https://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/4338.ADFS_2D00_SignIn.png"><img src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/01/71/70/4338.ADFS-SignIn.png" original-url="https://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-01-71-70/4338.ADFS_2D00_SignIn.png" alt="" border="0" /></a></span></p>
<p style="padding-left: 30px;"><span style="font-size: small;"><strong>Figure</strong>: ADFS 3.0 Sign-in page after applying custom web theme</span></p>
<p style="padding-left: 30px;">Custom web theme allows us to customize the CSS Style Sheet, Logos, and JavaScript file which are used in the construction of Sign-in page. Below is the procedure to build a custom web theme.</p>
<ol>
<li value="1">Export the files used in Default web theme of ADFS. Default web theme comes by default out-of-box with ADFS.</li>
</ol>
<p style="padding-left: 30px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <code class="csharp">Export-AdfsWebTheme &ndash;Name default &ndash;DirectoryPath c:\custom-theme</code></p>
<ol>
<li value="2">Create a new theme and name it as you like (Ex: custom-theme)</li>
</ol>
<p style="padding-left: 60px;">&nbsp;&nbsp; <code class="cplusplus">New-AdfsWebTheme -Name "custom-theme" -SourceName default</code></p>
<ol>
<li value="3">Now, edit the files exported in Step-1. You can edit style.css, onload.js and add images. The theme folder structure is as below:&nbsp;</li>
</ol>
<p style="padding-left: 60px;">ThemeRoot</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-css</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-style.css</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-style.rtl.css</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-images</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-logo.png</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-script</p>
<p style="padding-left: 60px;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; |-onload.js&nbsp;</p>
<ol>
<li value="4">After modifying the logo, you can apply it to the custom-theme using the PowerShell command below.&nbsp;</li>
</ol>
<pre class="scroll" style="padding-left: 60px;"><code class="cplusplus">Set-AdfsWebTheme -TargetName "cusotm-theme" -Logo @{Locale="";path="C:\custom-theme\images\logo.png"}</code></pre>
<ol>
<li value="5">After modifying the style sheet (style.css and style.rtl.css) apply the same to the new theme.</li>
</ol>
<p style="padding-left: 60px;">&nbsp;<code class="cplusplus">Set-AdfsWebTheme -TargetName "custom-theme" -StyleSheet @{Locale="";path="C:\custom-theme\css\style.css"} -RTLStyleSheetPath "C:\custom-theme\css\style.rtl.css"</code></p>
<ol>
<li value="6">After modifying the JavaScript file (onload.js) apply the same to the new theme.</li>
</ol>
<p style="padding-left: 60px;">&nbsp;<code class="cplusplus">Set-AdfsWebTheme -TargetName $ThemeName -AdditionalFileResource @{Uri="/adfs/portal/script/onload.js";path="C:\custom-theme\script\onload.js"}</code></p>
<ol>
<li value="7">And finally activate the new custom theme in ADFS to start seeing the changes</li>
</ol>
<p style="padding-left: 60px;">&nbsp;<code class="cplusplus">Set-AdfsWebConfig -ActiveThemeName "custom-theme"</code></p>
<ol>
<li value="8">If you are not satisfied with the changes you have done, update the files again and apply them to the custom-theme as mentioned in the above steps.&nbsp;</li>
</ol>
<p>&nbsp;&nbsp;</p>]]></content:encoded>
    </item>
  </channel>
</rss>