Tuesday, November 5, 2013

wcf message security using certificates

=======================================================
WCF MESSAGE SECURITY USING CERTIFICATE PART 1 : SERVICE
=======================================================


1. Create a new Web Site.

2. Add a WCF web service to the site.

3. Change the DoWork function: (in both IService.cs and Service.cs)
string DoWork(int a)
{
return "You entered " + a.ToString();
}
4. In principle, following things are required to enable certificate
security at service level :
a. Define the security level : either transport or message
  This is defined in the binding configuration
b. Provide the certificate :
  This is done in ServiceBehaviors - ServiceCredentials tag.
c. Attach the above to Service.
  Attach message security by specifying bindingConfiguration in
  endpoint.
  Attach service certificate by specifying behaviorConfiguration
  in service.

4a.
<bindings>
      <wsHttpBinding>
        <binding name="mybind" >
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

4b.
<serviceBehaviors>
        <behavior name="my">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceCredentials>
            <serviceCertificate findValue="CN=tempCert" storeLocation="LocalMachine" storeName="My"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>


5. Mex endpoint : this is extra; but may be required.
a. In service behavior :
    <serviceMetadata httpGetEnabled="true" />
b. In <service> tag, add another endpoint for mex:
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" ></endpoint>

6. The total config should now look like following :
 <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="mybind" >
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="my">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceCredentials>
            <serviceCertificate findValue="CN=tempCert" storeLocation="LocalMachine" storeName="My"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
   
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Service" behaviorConfiguration="my" >
        <endpoint address="" binding="wsHttpBinding" contract="IService" bindingConfiguration="mybind"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" ></endpoint>
      </service>
    </services>
  </system.serviceModel>

7. Run the web site with Service.svc open. You should see familiar blue/white WSDL screen for the service.
   The url of the page looks something like "http://localhost:4348/WebSite1/Service.svc"

======================================================
WCF MESSAGE SECURITY USING CERTIFICATE PART 2 : CLIENT
======================================================

1. Create a new web site.

2. Add a Label Label1 on default.aspx.

3. Add a service reference to the project.
Right click the project in solution explorer, select "Add Service Reference".
Copy and paste the url of the service from the page displayed in step 7 above.
        Click "Go" in the "Add Service Reference" dialog.
The service should be seen in "Services" pane of the dialog.
Click "OK" to add the reference.
4. Add the following code to Page_Load event of Default.aspx :
        ServiceReference1.ServiceClient svc = new ServiceReference1.ServiceClient();
        Label1.Text = svc.DoWork(4);

5. Run the project. You should get "InvalidOperationException" exception:
"The client certificate is not provided. Specify a client certificate in ClientCredentials."

6. To correct this error, you need to provide a certificate to the client.
   This done in the endpoint behavior.
   So you need to create an endpoint behavior and attach it to endpoint.

7.Here we will the same certificate as that of service, since we are trying this on the same machine.
Add the following to the <system.serviceModel> section:
   <behaviors>
      <endpointBehaviors>
        <behavior name="myb">
          <clientCredentials>
            <clientCertificate findValue="CN=tempCert" storeLocation="LocalMachine" storeName="My"/>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>

8. Attach this behavior to the endpoint specified in <client> tag.
The total configuration looks like following :

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="myb">
          <clientCredentials>
            <clientCertificate findValue="CN=tempCert" storeLocation="LocalMachine" storeName="My"/>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
          <security mode="Message">
            <transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
            <message clientCredentialType="Certificate" negotiateServiceCredential="true" algorithmSuite="Default"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:4348/WebSite1/Service.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="ServiceReference1.IService" name="WSHttpBinding_IService" behaviorConfiguration="myb">
        <identity>
          <certificate encodedValue="AwAAAAEAAAAUAAAAJdm3kjyo+3IINpRcCcL18xAHDJMgAAAAAQAAAPMBAAAwggHvMIIBXKADAgECAhAJcTbJKUQFrkBJG29u5jGAMAkGBSsOAwIdBQAwFTETMBEGA1UEAxMKUm9vdENBVGVzdDAeFw0xMzEwMjkxMzI1MTlaFw0zOTEyMzEyMzU5NTlaMBMxETAPBgNVBAMTCHRlbXBDZXJ0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsThCFbp8o2lRth4OHqTYUZzvh08fnkEn+mlVKiJwe1uBOcPSCummedCI2SOkH/pCFc6VRcJcSv77UL1fI8KcQbJWgNwwlikrjJxJfuzQT8I/3ECWCaE3iZRqHMqE31BNgQR/dp/mRo8U3KSUzkgnmS/pcceDO4TA/ZX3gB399CQIDAQABo0owSDBGBgNVHQEEPzA9gBCKdgxdb66XAzRBYr0zZTZMoRcwFTETMBEGA1UEAxMKUm9vdENBVGVzdIIQp+Iu4taQ8a9NIeWKlHq9YDAJBgUrDgMCHQUAA4GBAAKB8SfWcyTkFeOdfx1YEEfjqYRuwgZBn7eHEhCk6lxFi5OZLtxZfxULR0bSbd6F4QMBDlcHM0LFaf6SKJ6JCXZQ5dfBHzgcJJ5j+Okj59be9DrYIbunut5uMLWJAx+nIFCItxe4hw452U+DAKEOSHI83OANdzzbFgAckiwFheOu"/>
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>


9.Run the project. Now it should run without exception and should show a message like following on default.aspx:
"You enetered 4".




NOTE 1 : In both service and client, you can use "CN=" prefix in certificate, You then need not to specify x509FindType.
specifying "CN=" is equivalent to x509FindType="FindBySubjectName".

NOTE 2: In general the certificate should be valid. To check this, double click on the certicate in MMC.
In the "General" tab, look at the "Certificate Information". This information should not be something like certificate not trusted,
certificate expired, etc.

In one of the cases, a certificate was having this info (status) as
"This CA Root certificate is not trusted because it is not in the Trusted Root Certification Authorities store."

This certificate was placed in LocalMachine TrustedPeople.

The exception received was SecurityNegotiationException :
"The caller was not authenticated by the service."

NOTE 3: Also verify that the certificate is having a private key.
This can be verified on the "General" tab, at the bottom you should see a message like :
"You have a private key that corresponds to this certificate."


Tuesday, July 30, 2013

: One to many relationship and ObjectStateManager error

Understand basic navigation with Entity Framework Code First (4.3) with 1 to many relationship


Entity Framework 4.3: An object with the same key already exists in the ObjectStateManager
http://patrickdesjardins.com/blog/entity-framework-4-3-an-object-with-the-same-key-already-exists-in-the-objectstatemanager

Microsoft Links : MVC 3, MVC 4 tutorials

Table of Contents

MVC 4

·         ASP.NET MVC 4 Mobile Features
·         Bundling and Minification
·         Custom MVC Template

MVC Music Store

·         Part 2: Controllers
·         Part 3: Views and ViewModels
·         Part 4: Models and Data Access

Getting Started with EF using MVC

·         ASP.NET Data Access Content Map

Views

·         Dynamic v. Strongly Typed Views

Controllers and Routing

·         Creating Custom Routes (C#)
·         Creating Custom Routes (VB)

Security

JavaScript

Deployment

Getting Started with ASP.NET MVC3

Older Versions

·         Getting Started With MVC
·         Models (Data)
·         ASP.NET MVC Views
·         Controllers and Routing
·         Deployment
·         Security
·         Unit Testing
·         Contact Manager
·         NerdDinner
·         Movie Database
·         JavaScript
·         Overview

Hands On Labs

·         What's New in ASP.NET MVC 4
·         ASP.NET MVC 4 Fundamentals

MVC 5

·         Introduction to ASP.NET MVC 5


Monday, July 22, 2013

Some More MVC links

1. Difference between MVC and ASP :

http://msdn.microsoft.com/en-us/library/dd381412(v=vs.98).aspx




2. Razor Syntax

MS Article : Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)

http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax


C# Razor Syntax Quick Reference



3. Shivaprasad MVC tutorials :

http://www.dotnetfunda.com/articles/article1846-mvc-tutorial-number-12-what-is-razor-in-mvc-3.aspx


4. A good basic tutorial and contains many links :

ASP.NET MVC3 Razor With jQuery For Beginners




5.httpnotfound

ASP.NET MVC 3: Using HttpNotFoundResult action result

http://weblogs.asp.net/gunnarpeipman/archive/2010/07/27/asp-net-mvc-3-using-httpnotfoundresult-action-result.aspx



6. Types of helpers in MVC :

form, url and html.



===========================
action is any public method in a controller.

If a public method in a controller is not supposed to work as action, it should be decorated with [NonAction] attribute.


Base to all action results is ActionResult

Types of ActionResult :
ViewResult
PartialViewResult
RedirectResult
RedirectToRouteResult
ContentResult
JsonResult
JavaScriptResult
FileResult
EmptyResult



========================
what is @Scripts.Render ?

what is RenderSection ?what is @RenderBody ?
what are <section> , <nav> tags ?

========================



Tuesday, May 28, 2013

MVC Links : Types of filters and other misc tech info

MVC

http://www.codeproject.com/Articles/577776/AplusBeginner-27splusTutorialplusforplusUnderstand


Type of filters

Now taking this discussion further, Let us first discuss the various types of filters that can be implemented to inject custom processing logic.
 • Authorization filter
• Action filter
• Result filter
• Exception filter



Order of Execution

IAuthorizationFilter.OnAuthorization
2. IActionFilter.OnActionExecuting
3. IActionFilter.OnActionExecuted
4. IResultFilter.OnResultExecuting
5. IResultFilter.OnResultExecuted

In case there is an exception, OnException will will be called as instead of the result filters.

===============

http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html

return View() vs return RedirectToAction() vs return Redirect() vs return RedirectToRoute()

================

http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html

RenderPartial vs RenderAction vs Partial vs Action in MVC Razor

================

MVC Step By Step Tutorial on codeproject link



http://www.codeproject.com/Articles/552846/Why-s-How-s-of-Asp-Net-MVC-Part-1

  1. Why(s) & How(s) of Asp.Net MVC Part 1 - MVC Basics
  2. Why(s) & How(s) of Asp.Net MVC Part 2 - Playing with Asp.Net MVC
  3. Why(s) & How(s) of Asp.Net MVC Part 3 - DB First
  4. Why(s) & How(s) of Asp.Net MVC Part 4 - Model First
  5. Why(s) & How(s) of Asp.Net MVC Part 5 - Code First



Learn MVC (Model view controller) Step by Step in 7 days – Day 2

MVC Error : CS0103: The name 'Scripts' does not exist in the current context



CS0103: The name 'Scripts' does not exist in the current context



Source Error:

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}


The solution is

1. Also install  "Microsoft ASP.NET Web Optimization Framework" package from NuGet
2. Include <add namespace="System.Web.Optimization"> in both web.configs.


Views Web.config

    <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Helpers"/>
      </namespaces>


Root Web.config


      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
        <add namespace="System.Web.Optimization"/>      
      </namespaces>






















Sunday, May 26, 2013

MVC uses other design patterns ....


A good point to ponder over; is this really so ?

http://www.codeproject.com/Articles/552846/Why-s-How-s-of-Asp-Net-MVC-Part-1


Design Patterns in MVC 

Even though MVC is design pattern itself, the entire MVC framework contains some design patterns itself. Below is a list of design parrens used in MVC (or Asp.Net MVC) regardless the platforms. Detaild description of these patterns in MVC are out of the scope of this post, I am sure you can google and could know much more about them.   
Front ControllerConsolidates all request handling by channeling requests through a central controller.
StrategyThe View-Controller relationship, The way conroller hookup view at runtime.
Factory MethodSpecify the default controller class for a view
DecoratorIn the context of MVC, decorator could fit into your views.
ObserverOne Model, Multiples views ( observers/subscribers ), and the publisher manages the communication
MediatorSeveral different Models, Several views, and the mediator manages the communications between them.

Monday, May 20, 2013

$.ajax : error trapping code


 success: function(result) { alert(result.d); },
                error: function(xhr, status, error) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }

Sunday, May 19, 2013

links for jquery and json web services



Using jQuery to Consume ASP.NET JSON Web Services




The article also has a compilation of other links at the bottom : 

36 Mentions Elsewhere

  1. Dew Drop - March 27 | Alvin Ashcraft's Morning Dew
  2. Reflective Perspective - Chris Alcock » The Morning Brew #61
  3. March 28th Links: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Visual Studio, Silverlight, .NET « .NET Framework tips
  4. Enlaces de Marzo: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Visual Studio, Silverlight, .NET « Thinking in .NET
  5. Wöchentliche Rundablage: WPF, Silverlight 2, ASP.NET MVC, .NET 3.5… | Code-Inside Blog
  6. Using jQuery to consume JSON Services « HSI Developer Blog
  7. Links do dia 28 de Março: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Visual Studio, Silverlight, .NET - ScottGu's Blog em Português
  8. Eye On .NET - Hisham Elbreky
  9. Using jQuery & JSON with ASP.NET at KeithRousseau.com
  10. Using jQuery to Consume ASP.NET « vincenthome’s Software Development
  11. 3 mistakes to avoid when using jQuery with ASP.NET AJAX
  12. jQuery with ASP.NET Json Web Services : { null != Steve }
  13. Mi primer plugin de jQuery = jQuery.dotNet « Walter Poch
  14. Good links: ASP .NET and JQuery - Programmatically Speaking ...
  15. My Portal Project » Blog Archive » ASP.NET Web Services from Javascript with jQuery (without the ScriptManager)
  16. Elegant Code » Calling Remote ASP.NET Web Services from JQuery
  17. Submitting an AJAX Form with ASP.NET MVC + jQuery « {Programming} & Life
  18. JavaScript Arrays via JQuery Ajax to an Asp.Net WebMethod | Elegant Code
  19. Integrating SmartGWT with ASP.NET JSON web service « Reminiscential: of or pertaining to remembrance
  20. JQuery Resources
  21. jQuery and ASP .NET MVC: browser issues | peterskim
  22. Amr ElGarhy » How I handle JSON dates returned by ASP.NET AJAX
  23. jQuery Tutorials ( Learn – Practice – Expert ) « Ramani Sandeep
  24. jQuery autocomplete plugin with ASMX web service and JSON « Adam Mokan's Development Blog
  25. links for 2009-12-23 « 2LeggedSpider
  26. Building an AJAX web part with jQuery (Part 2)
  27. Consuming a JSON WCF Service with jQuery « Me Too on .NET
  28. Using XML, LINQ and jQuery for a Google Maps Store Locator « Sam's Daily Life
  29. WCF and JSON « Wibber's Blog
  30. adam mokan / jQuery autocomplete plugin with ASMX web service and JSON
  31. ASP webservice in jQuery « Izdelava spletnih strani Blog
  32. ASP.NET JQuery AJAX « Code Kat ^..^
  33. Learning jQuery using jQuery Lab
  34. Successful jQuery $.ajax call returns JSON but throws “parsererror”| DautNet Blog
  35. JavaScript Arrays via JQuery Ajax to an ASMX WebMethod « mariuszrokita
  36. 70-480 - Programming in HTML5 with JavaScript and CSS3

230 Comments

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...