WCF and ASMX services and consuming using IP, Siteminder, Kerberos and SSL Authentication

WCF and
ASMX services and consuming using IP, Siteminder, Kerberos and SSL Authentication…

1.       Proxy

a.       Any type of Proxy (WCF or ASMX) can be created for a ASMX svc

b.      Any type of Proxy (WCF or ASMX) can be created for a WCF svc

2.       To create a proxy, we use VS..Create Ref…

3.       For WCF svc, use …/abc.svc?wsdl to get the wsdl (using which the proxy is generated)

4.       WCF Test Client is a tool to send request to wcf svc and invoke it

5.       For asmx svc u can use fiddler etc to invoke the svc.

6.       To consume a svc using its proxy all u have to do is to instanciate the Client : abcClient
svc = new abcClient(“abcBinding”, endpoint);

And call the remote method: svc.StringEcho(ref
testString); //Getting the response from the StringEcho method.

Authentication

The above pt 6 is valid when the svc does
not have any auth. Enabled, or maybe uses IP Auth.

But there are other auth mechanisms that
need the client to do special thigs:

A.
SITEMINDER
AUTH.

In the web.config, the following should be present:

A.      BINDING

                 <system.serviceModel>
                 <bindings>
                 <basicHttpBinding>
<!--For IP and SM Auth-->
                                   <binding name=" abcBinding " closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                                            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                                            <security mode="None">
                                                     <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
                                                     <message clientCredentialType="UserName" algorithmSuite="Default"/>
                                            </security>

                        </binding>

</basicHttpBinding>

                          </bindings>
<client>
                          <!--For IP and SM Auth-->
                          <endpoint address="" contract="sdsde" name="abcBinding" binding="basicHttpBinding" bindingConfiguration="abcBinding" behaviorConfiguration="abcEndpointBehavior"/>
         </client>
                 <!--ForSiteminder-->
                 <extensions>
                          <behaviorExtensions>
                                   <add name="SMCookieBehavior" type="myNamespace.SM_BehaviorExtensionElement, Service Bus Checks, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
                          </behaviorExtensions>
                 </extensions>
                 <behaviors>
                          <endpointBehaviors>
                                   <behavior name="abcEndpointBehavior">
                                            <SMCookieBehavior asdf="test asdf"/>
                                   </behavior>                                 
                          </endpointBehaviors>
                 </behaviors>
         </system.serviceModel>

B.      Now
for SM auth the code is :

1.  add a Behavior and its Behavior Extension Element for SM Authentication
 
 namespace myNamespace 
{
public class SM_BehaviorExtensionElement : BehaviorExtensionElement
    {

        public override Type BehaviorType
        {
            get
            {
                return typeof(SM_EndpointBehavior);

            }
        }

 
 
        protected override object CreateBehavior()
        {
            return new SM_EndpointBehavior(asdf);
        }

        [ConfigurationProperty("asdf", IsRequired = true)]
        public string ASDF
        {
            get { return (string)base["asdf"]; }
            set { base["asdf"] = value; }
        }
    }
}
2.  Add an Endpoint  Behavior for SM Authentication
    public class SM_EndpointBehavior : IEndpointBehavior
    {
        private string m_asdf;
        public SM_EndpointBehavior(string asdf)
        {
           this.m_asdf = asdf;
        }
        #region IEndpointBehavior Members
        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {        }
        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            SM_UserAgentMessageInspector inspector = new SM_UserAgentMessageInspector(this.m_userAgent);
            clientRuntime.MessageInspectors.Add(inspector);
        }
          public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {}
         public void Validate(ServiceEndpoint endpoint)
        {}
        #endregion
    }
 
3.  Add a Message Inspector for SM Authentication
 public class SM_MessageInspector : IClientMessageInspector
    { 
        private const string USER_AGENT_HTTP_HEADER = "user-agent"; 
        private string m_asdf;
        public SM_UserAgentMessageInspector(string asdf)
        { 
           this.m_asdf = asdf; 
        }
 
       #region IClientMessageInspector Members
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {        }
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
Console.log("in MessageInspector");
            }
            HttpRequestMessageProperty httpRequestMessage;

            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {                
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;                
                HttpRequest Request = HttpContext.Current.Request;
                string SMCookie = null;
                SMCookie = Request.Headers["Cookie"];
                if (SMCookie != null)
                {
                    Console.write("SMCookie is :" + SMCookie);
                    httpRequestMessage.Headers["Cookie"] = SMCookie;
                    console.log("Cookie added :" + SMCookie);
                }
                else
                {
                   Console.write("SMCookie is null");
                }
            }

            else
            {                
                httpRequestMessage = new HttpRequestMessageProperty();
                HttpRequest Request = HttpContext.Current.Request;
                string SMCookie = null;
                SMCookie = Request.Headers["Cookie"];
                if (SMCookie != null)
                {
                    httpRequestMessage.Headers["Cookie"] = SMCookie;                
                }
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }
            return null;
        } 
        #endregion
    }

C.      To
consume a svc using its proxy over SM
all u have to do is to instanciate
the Client : abcClient svc = new abcClient(“abcBinding”, endpoint);

And call the remote method: svc.StringEcho(ref
testString); //Getting the response from the StringEcho method.

 

B.
KERBEROS
AUTH.

a.       For
this the client needs to do:

A.  WEB.CONFIG
<system.serviceModel>
                 <bindings>
                          <basicHttpBinding>
                                   <binding name="BasicHttpBinding_IKerberosService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                                            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                                            <security mode="TransportCredentialOnly">
                                              <transport clientCredentialType="Windows" realm=""/>
                                              <message clientCredentialType="UserName" algorithmSuite="Default"/>
                                      </security>
                                   </binding>

Now Client:

<client>         
                          <!--For Kerberos Auth-->
                          <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IKerberosService contract="abc.IKerberosService" name="BasicHttpBinding_IKerberosService">
                          </endpoint>

Now in code u have to do:

 EndpointIdentity identity = null;
                identity = EndpointIdentity.CreateSpnIdentity(“HTTP/a.b.com@p.q.r.COM”);
                string endpoint = “http:// a.b.com@p.q.r.COM:1234/abc/MyKerberosService.svc
”;

                EndpointAddress address = null;
                address = new EndpointAddress(new Uri(endpoint), identity);

                MyKerberosService Client client = new MyKerberosServiceClient("BasicHttpBinding_IKerberosService ", address);

                try
                {                    
                    String response = client.echoString("HELLO");

C.  SSL
AUTH

Web.config change:
<system.serviceModel>
                 <bindings>
                          <basicHttpBinding>
         <!--For SSL-->
                                   <binding name="abcSoap">
                                            <security mode="Transport">
                                                    <transport clientCredentialType="Certificate"/>
                                            </security>
                                   </binding>
Then
         <client>                  
                          <!--ForSSL-->
                          <endpoint address="" binding="basicHttpBinding" bindingConfiguration="GetFieldsMulRecSoap" contract="a.b" name="SSLAuthSvc"/>
                 </client>
Code :
1.   
        protected void validateCert(string CertSubject)
//HERE WE ARE SIMPLY ACCEPTING ALL THE SERVER SERTIFICATES THAT CONTAIN THE CERTIFICATE WE ARE LOOKING FOR USING CertSubject. THIS IS JUST BASIC VALIDATION. For PROPER VALIDATION, WE MAY WANT TO CHECK FOR SOME OTHER PROPERTY. Note that THE SERVER’S PUBLIC CERTI IS DEPLOYED IN 
        {
            //trust sender
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => cert.Subject.Contains(CertSubject));
 //cert sub can be found from the cert props.It’s of format: a.b.com
Console.write(“Server Certificate Validated by Subject”);
 
        }
Main Code:
 string CertThumbprint = "12 12 41 c6 39 52 4e 59 6y 78 a6 2u c6 56";
string endpoint = “https://a.b.com:4208/p/q/r”;
var svc = new MySSLSvcClient(“SSLAuthSvc”, endpoint);
response = svc.myMethod(); 
svc.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, CertThumbprint);
 
//OK, SO WHAT WE ARE DOING HERE IS SIMPLY FINDING OUR OWN CERTIFICATE IN “StoreLocation.LocalMachine, StoreName.My”. NOTE THAT StoreName.My ACTUALLY REFERS TO PERSONAL FOLDER IN THE CERT STORE…
FINALLY WE ARE SENDING THE CERT WITH EVERY REQUEST
 
GENERAL DEPLOYMENT INSTRUCTIONSINSTALLATION:

1. Create a New Virtual Directory in IIS to host the site.
2. Create a new App Pool and run it under a sepcific service account (if needed)
3. Associate the VD with this App Pool
4. Convert the VD to Application from its Properties in intemgr.

 

DEPLOYMENT INSTRUCTIONS SPECIFIC TO CERT INSTALLATION:
  1. Install the
    Certificate of the Service Account under which the Application Will Run by
    running install.cmd*
  2. Next Install
    the Public Certificate of SERVER (Certificate Name: A.B.com.cer, in the location:
    storeName=”TrustedPeople” storeLocation=”LocalComputer”.

Note THAT IF YOU ARE RUNNING YOUR APPLICATION VD UNDER A SPECIFIC USER, CREATE A NEW APP
POOL AND IN THAT GIVE THE SPECIFIC  USER’S CREDENTIALS AND THEN RUN THE VD
UNDER THAT NEW APP POOL

ALSO, Add
the SPECIFIC USER account to the local IIS_WPG group.

* NOTE That
install.cmd is :

@echo off

certutil
-addstore ROOT QWER.cer  <THIS IS THE PARENT OF CLIENT CERTI>

certutil
-addstore ROOT ASDF.cer  <THIS IS THE PARENT OF SERVER CERTI>

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -i MY_CERT.pfx
-c LOCAL_MACHINE\MY -p test -a administrators

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -g -c
LOCAL_MACHINE\MY -s ” MY_CERT” -a MY_CERT

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -g -c
LOCAL_MACHINE\MY -s ” MY_CERT” -a Administrators

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -g -c
LOCAL_MACHINE\MY -s ” MY_CERT” -a System

call
“C:\Program Files\Windows Resource Kits\Tools\winhttpcertcfg” -l -c
LOCAL_MACHINE\MY -s ” MY_CERT”

pause

 

Advertisements

Asp.Net Tips and Tricks


1.
Call remote methods: This can be done in 2 ways,

a.    1st
that u have a restful svc like a webAPI that binds every HTTP verb to a method

b.    2nd in
other cases like mine, where I had a simple asp.net web app, my home.aspx was
calling svc.aspx and passing the method to be executed as  a “action” query
string : AJAXResponse.aspx?action=btn1_Clk&ID=” + iD;

Now in the c# code, in case u have called AJAXResponse.aspx, then first make sure that in its aspx file all u have is : <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AJAXResponse.aspx.cs" Inherits="RFBAppUsingInterface.AJAXResponse" %>

 

 And in it’s .cs file’s Page_Load(),
check the action and call the method:

string action = HttpContext.Current.Request["action"];

            if (action == " btn1_Clk")
            {
                string ID = HttpContext.Current.Request["iD"];
                if (ID != null)
                    btn_Clk(ID);
            }
 

2.
SESION

a.       Read
from session:  HttpContext.Current.Session[“abc”])

3.  Response
JSON

          Response.Clear(); //MAKE SURE U DO THIS

            RESULT = PerformAction(dfd);

 
            var json = new JavaScriptSerializer();

            var resp = new JSONResponse();

            resp.a = df;
            resp.b = 
            resp.c = 
            Response.Write(json.Serialize(resp));
        }
    }

    public class JSONResponse
    {
        public string a { getset; }
        public string b { getset; }
        public string c { getset; }
    }

4.  Load the file at runtime: string path = HostingEnvironment.MapPath(@"~/App_Data/abc_" + Environment + ".xml");
                                                 var stream = new StreamReader(path);
                                                   config = Helper.LoadRBFConfiguration(stream);

5.  Role
of Global.asax:Whatever needs to be done only at Application Start should be put in Application_Start() of Global.asax.cs.

Also, if you want something to persist, create it here, Eg. If u want int a globally, all u have to do in home.aspx is : Global.a

6.  TO register anything: Page.ClientScript.RegisterStartupScript(GetType(), “ex”,

                                                                "alert('" +
                                                                "U don’t have access"');"true);

7.  In
home.aspx.designer.cs, add:

/// <summary>
        /// GroupPnl control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel GroupPnl;

Below are some changes to it:

a.  GroupPnl.Height = Unit.Percentage(100);
b.  GroupPnl.BackColor = System.Drawing.Color.Silver;
c.  CheckPanel.BackColor = Color.FromArgb(207, 238, 248);
d.  abc.BorderStyle = BorderStyle.Double;
e.  sd.OnClientClick = "CheckAll_ClkXMLHttpReq(event);return false;";// Note that in case you don’t do return false; here, it will do a page reload even though onclk u are executing a js function..
f.  GroupPnl.Controls.Add(new LiteralControl(
                            "

&nbsp;    

 +
                            pair.Key + "</span></span></p>");
g.  GroupCheckStatus.Click += new EventHandler(CheckGroup_Click); //Server Side Event
h.  GroupCheckStatus.Click += (sender, e) => CheckGroup_Click(sender, e); //Server Side Event
i.  If you hide some element on server side (ie in aspx page), then its not send over in the html, so u cannot show it using js latr..hence hide and show using js only…
j.   var Response = new TextBox(); Response.Wrap = true; OR  DetailsText.TextMode = TextBoxMode.MultiLine; // Show multi line in textbox

8.
If a solution has multiple projects, say A is dll proj and B is web
app (asp.net), the A can read the web.config from B

9.
To be able to override any machine.config tag in ur app, the
registration of that tag in m.c (under <configSections>)should be set as allowDefinition=MachineToApplication” or allowDefinition=Everywhere

10.

11.

 

 

 

–>

Error accessing SQL compact .sdf DB from MVC4 app

I have a SQL server compact setup (see this). Now when i try to access this from my MVC 4 App, i got Access Denied.

My app’s VD is hosted on IIS 7.5 on Win 7 and running under Default App Pool (4.0 Classic Pipeline) and NETWORK SERVICE credentials.

 

Here are a two other suggestions:

  • Try to run your Visual Studio as administrator
  • Check if the ‘readonly’ attribute is set on the sdf file

 

From <http://stackoverflow.com/questions/3647663/sql-compact-edition-3-5-access-to-the-database-file-is-not-allowed>

 

I have given Everyone and  NETWORK SERVICE  full access on .sdf file and its parent dir.

Still i see this.

Finally i  got it working by putting the same code in a console app and so by changing App Pool credentials (for my web app) to My Name.

Strange…

Advanced .Net Debugging Training May 13

Tools :

session will cover 32-bit debugging tools.

1)      Install Windows SDK
2)      Install DebugDiag (DebugDiagx64.msi)
3)      Copy SysinternalsSuite.zip and extract it to a suitable location
4)      Copy Tools.zip and extract it to a suitable location. Run ADNDv1.3.1_LabFiles.msi from the extracted Tools folder to install the lab files that would be used during the practical sessions.
Also please make sure that all features of IIS are installed.
DebugDiagx64.msi & DebugDiagx86.msi
SysinternalsSuite.zip
WinDbg (dbg_x86_6.11.1.404)
ILSpy : ILSpy_1.0.0.943_Beta_Binaries.zip
Managed Stack Explorer
ProcDump
PSSCOR
Public Symbols : symcache.zip & Windows_Win7SP1.7601.17514.101119-1850.X86CHK.Symbols.msi
Reflector7.4.1.179.zip
Self Study :
Holy Grail

IIS (6 and 7) and Asp.Net debugging Training Feb 13

Introduction and Overview
  • Windows Architecture
  • IIS Architecture
  • ASP.NET Architecture
ASP.NET Health Check Practices
  • Basic Debugging
  • Exception Best Practices
  • Memory Best Practices
  • Native Leak Best Practices
  • Performance Optimizations
  • Profiling Tips and Tricks
  • Threading Best Practices
IIS Platform Best Practices

  • Performance
  • Security
  • Reliability / Operations
  • Log Analysis
  • Configuration
  • IIS/System Health
Tools Covered : WinDbg, DebugDiag, Perfmon….

AngularJS with ASP.Net MVC4

http://tarkus.me/post/32121691785/angularjs-with-asp-net-mvc-4

ASP.NET Web API

http://www.asp.net/web-api

http://harouny.wordpress.com/2013/02/03/using-angularjs-to-consume-webapi-service-in-mvc4-project/

http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster.pdf

Web Servicesa

1. WCF : Soap over HTTP
2. ASMX :
3. REST

web service protocols

Steps to study this :

1. http://en.wikipedia.org/wiki/Web_services_protocol_stack

summary :  A web-service protocol uses  a particular syntax and language for encoding messages in a common XML format (Eg. Soap, JSON etc. ) for service description, requests and responses.

2. http://en.wikipedia.org/wiki/List_of_web_service_protocols

Go throught this next :
#Angular-MVC-Cookbook
##Angular.js and ASP.NET MVC Cookbook.

This repository contains examples of integrating [Angular.js](http://angularjs.org/)
and [ASP.NET MVC](http://www.asp.net/mvc). The AngularJS/MVC Cookbook found at GitHub at
https://github.com/Wintellect/Angular-MVC-Cookbook

##Examples
– [Basic Project](./BasicProject) – provides a basic MVC 4 application that includes AngularJS
and other components. Other examples build upon this.
– [Simple Routing](./SimpleRouting) – example of simple routing of dynamic views and unit testing
controllers.
– [CRUD Operations](./CRUDOperations) – example of CRUD operations.

##Blog Posts (Newest First)
– [AngularJS/MVC Cookbook Simple Binding](http://blog.dfbaskin.com/2013/03/angularjsmvc-cookbook-simple-binding.html)
– [AngularJS/MVC Cookbook CRUD Operations](http://blog.dfbaskin.com/2013/03/angularjsmvc-cookbook-crud-operations.html)
– [AngularJS/MVC Cookbook Running Unit Tests](http://blog.dfbaskin.com/2013/02/angularjsmvc-cookbook-running-unit-tests.html)
– [AngularJS/MVC Cookbook Unit Testing](http://blog.dfbaskin.com/2013/02/angularjsmvc-cookbook-unit-testing.html)
– [AngularJS/MVC Cookbook Simple Routing](http://blog.dfbaskin.com/2013/02/angularjsmvc-cookbook-simple-routing.html)
– [AngularJS/MVC Cookbook Basic Project](http://blog.dfbaskin.com/2013/02/angularjsmvc-cookbook-basic-project.html)
– [Cookbook for ASP.NET MVC and Angular.js Web Apps](http://blog.dfbaskin.com/2013/02/cookbook-for-aspnet-mvc-and-angularjs.html)

##License
– AngularJS/MVC Cookbook – http://opensource.org/licenses/mit-license.html

##Contact
– Email: dbaskin@wintellect.com

##Changelog
– v1.3 – upgraded projects to AngularJS v1.1.4.
– v1.2 – added CRUD Operations example.
– v1.1 – added Simple Routing example.
– v1.0 – initial version.

asp.net MVC4 TO DO app with AngularJS

Hi,
So finally i found a easy (i wish) tutorial for this : http://jphoward.wordpress.com/2013/01/04/end-to-end-web-app-in-under-an-hour/

But when i started it, i spend an hour trying to get rid of issues like :

1. Controler creation was failing for no reason and then wheni tried again after cleaning, rebuilt and all that crap and created fresh model, it worked.

2. Next once C was ready, trying to access  : http://localhost:55764/api/ToDo gave error : (Access is denied.) while attempting to open or create the physical file .mdf’. CREATE DATABASE

Well, by now i have learnt to get over this by giving full access to everyone in the secutity section of the project properties.

3.  Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration. You can use the Add-Migration command to write the pending model changes to a code-based migration.

Theni enabled automatic migration by writing >automatic-migration
then also the webapi was giving 404…

Ok, so now its 4 hrs later and i finally completed the whole thing in 10 min by creating a new solution and following the steps in the tuts…

Moving On to Part 2 :

http://www.youtube.com/watch?v=6WbVn_gYwQo