Archive for December, 2010

Graph Database

Posted: December 22, 2010 in Database, Performance
Tags: , ,

Most applications today handle data that is deeply associative, i.e. structured as graphs (networks). The most obvious example of this is social networking sites, but even tagging systems, content management systems and wikis deal with inherently hierarchical or graph-shaped data.

This turns out to be a problem because it’s difficult to deal with recursive data structures in traditional relational databases. In essence, each traversal along a link in a graph is a join, and joins are known to be very expensive. Furthermore, with user-driven content, it is difficult to pre-conceive the exact schema of the data that will be handled. Unfortunately, the relational model requires upfront schemas and makes it difficult to fit this more dynamic and ad-hoc data.

A graph database uses nodes, relationships between nodes and key-value properties instead of tables to represent information. This model is typically substantially faster for associative data sets and uses a schema-less, bottoms-up model that is ideal for capturing ad-hoc and rapidly changing data.

Neo4J ecosystem is Graph Database. Read more from here …

http://www.oscon.com/oscon2009/public/schedule/detail/8364

MongoDB is another Graph Database which is a scalable, high-performance, open source, document-oriented database. Read more from …

http://www.mongodb.org/

http://en.wikipedia.org/wiki/MongoDB




Simple, thread safe and the best performance solution …

public sealed class Singleton
{
    public static readonly Singleton instance = new Singleton();

    Singleton()
    {
    }     
}

  • A single constructor, which is private and parameterless to prevent other classes from creating instance.
  • The class is sealed. It may help the JIT to optimise things.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary – not used in above example and made static variable instance directly public, but for correct use we can have public static property or method to access the instance which will give more control for future
  • Explicit static constructor to tell C# compiler not to mark type as beforefieldinit – not used in above example

There are many ways of creating Singleton object. Refer below link for more details with explanation on each variation …

http://www.yoda.arachsys.com/csharp/singleton.html

Following link has simple and good information about how Authentication/Authorization can be done on web pages/web services in intranet and internet enviroments using IIS, Web.config …

http://www.15seconds.com/issue/020312.htm

Brief conclusion of above link (follow the link for step by step trails …)

Authentication

  • Windows authentication
    • Integrated Windows authentication – client machine computes a hash value by encrypting the user’s credentials and send it to the server
    • Basic and basic with SSL authentication – client does not generate hash value but values will be first encoded using base64 before transmitting. Its not secure bcos anyone who knows how to decode base64 string can easily decode it. So Basic wih SSL is secure.
    • Digest authentication – New type of authentication available from W2k OS and IE5+. In this user credentials will be sent on wire after encrypting them using MD5 (Message digest 5) hashing mechanism.
    • Client Certificate authentication – There are two types of certificates — server certificates and client certificates. Server certificates ensure that the identity of the server is valid and we can trust it; similarly client certificates ensure that the identity of the client is valid and the client can be trusted.
  • Forms authentication – ASP.NET redirects the unauthenticated users to a login page that can be configured in the Web.config file which intern authenticate the user by checking the provided user ID and password against some user database
  • Passport authentication – Passport authentication, a centralized service provided by Microsoft, offers a single logon point for clients. Unauthenticated users are redirected to the Passport site. Similar to the Forms authentication, this redirection might create problems for clients, unless they are programmed to handle the case of redirection.
  • None or Custom Authentication – Out of the all authentication methods, except for Forms and Passport authentications all other methods require Windows accounts for implementing security. Creating and maintaining Windows accounts for a Web application might create problems when scaling an application for more Web servers because we also have to duplicate all the Windows accounts and permissions on other Web servers.

There are some ways to provide custom authentication for our Web Services, for example –

  1. Accept a username and password as a parameter to our method calls
  2. Provide a logon method for our clients to call before they call any other business method. In that logon method, we can verify their credentials and issue them some kind of key to use in future method calls.
  3. Use SOAP headers for passing authentication information

Authorization

  • Windows NTFS file authorization – use that ACL (Access Control List) for authorization services
  • ASP.NET URL authorization – access is granted or denied for web page or service urls based on different application criterias defined in Web.config file.

More advanced ideas …

For securing SOAP header which may have sensitive  info like user id/pwd, you can use SOAP Extension to intercept the SOAP message and encrypt/decrypt at client/server side using SoapExtension class + ChainStream, GetInitilizer, Initialize, ProcessMessage methods. Refer below link for step by step trails ..

http://www.c-sharpcorner.com/UploadFile/sovonnath/SOAPHeaderandSOAPExtensionsinaWebService11162005021034AM/SOAPHeaderandSOAPExtensionsinaWebService.aspx

Refer below link for customizing ASP.NET security and writing our own HTTP handlers and modules …

http://www.15seconds.com/issue/020417.htm

WCF – Links

Posted: December 14, 2010 in WCF
Tags: , ,

http://www.wcftutorial.net

http://beyondrelational.com/blogs/dhananjaykumar/archive/2011/02/11/walkthrough-on-creating-wcf-4-0-service-and-hosting-in-iis-7-5.aspx

http://www.howtocreate.co.uk/

1. Using bind, trigger functions we can implement simple Publish/Subscribe pattern in JQuery
2. Below example shows how to create Subscribers (generally the script on page sections or modules) by subscribing to a common custom event called buttonClick through JQuery bind method and it also shows how to publish the custom event on some action (manual or automatic – here on click of button which is manual action) which intern fires all subscriber’s Action methods through JQuery trigger method.
3. There is already a plug-in available in JQuery site for achieving this by simply calling $.subscribe, $.publish and with few other functions. Refer http://www.dotnetoutsource.com/Download/jQuery/Publish-subscribe.aspx for sample. Our custom functions can be extended on top of native JQuery code using Plug-ins to access them directly on $ operator, like $.subscirbe.

<input type=”button” value=”Click Button & Publish Button Click Event” id=”myfield2″/>
<script type=”text/javascript” src=”http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.js“></script>
<script language=”javascript”>
    // Publisher script can be at page level. Actual publish action will be invoked through either user actions or through callback functions in case of ajax calls
    var Publisher = {
        Publish: function (eventName, args) {
            $(document).trigger(eventName, args);
        }
    };

    // Subscriber1/Subscriber2 can be part of page sections i.e. user controls (in case of asp.net page)
    var Subscriber1 = {
        subscribe: function () {          
            $(document).bind(‘buttonClick’, Subscriber1.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber1 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber1.subscribe();

    var Subscriber2 = {
        subscribe: function () {           
            $(document).bind(‘buttonClick’, Subscriber2.Action);           
        },

        Action: function (event, a, b, c) {
            alert(“Subscriber2 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    }
    Subscriber2.subscribe();

    $(document).ready(function () {
        // Binding publish method for button click event
        $(‘#myfield2’).unbind(‘click’).bind(‘click’, function () { Publisher.Publish(‘buttonClick’, [‘1’, ‘2’, ‘3’]); });       
    });
</script>

Following code is a simple example of publish subscriber modal using Javascript. Subscriber1, Subscriber2 are 2 subscribers for an event “PublishOnClick”. User is the publisher who publishes the event by clicking “Click Button & Publish Button Click Event” button. Publisher javascript code provides framework for adding/executing subscribers by different other modules in the same page. For example Subscriber1 can be in one module and Subscriber2 can be in another module and both can subscribe to single button action on the main page.

<input type=”button” value=”Click Button & Publish Button Click Event” id=”myfield2″/>
<script language=”javascript”>
    var Publisher = {
        subscribers: {},       
        Subscribe: function (event, callback) {
            if (Publisher[event] && typeof callback === “function”) {
                if (Publisher.subscribers[event]) {
                    Publisher.subscribers[event].callbacks.push(callback);
                }
                else {
                    Publisher.subscribers[event] = { callbacks: [callback] };
                }
            }
        },
        Publish: function (event, callback) {
            if (Publisher.subscribers[event].callbacks) {
                for (var callback in Publisher.subscribers[event].callbacks) {
                    Publisher.subscribers[event].callbacks[callback].apply(null, arguments);
                }
            }
        },
        // PublishOnClick – name should be same as subscribing event name. Similar to this method we can have different method for each new publishing event
        PublishOnClick: function (event, arguments) {
            Publisher.Publish(event, arguments);
        }
    };

    var Subscriber1 = {
        initialize: function () {
            if (Publisher.Subscribe) {
                Publisher.Subscribe(“PublishOnClick”, Subscriber1.Action);
            }
        },
        Action: function (a, b, c) {
            alert(“Subscriber1 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    };
    Subscriber1.initialize();

    var Subscriber2 = {
        initialize: function () {
            if (Publisher.Subscribe) {
                Publisher.Subscribe(“PublishOnClick”, Subscriber2.Action);
            }
        },
        Action: function (a, b, c) {
            alert(“Subscriber2 Action – arg1: ” + a + “, arg2: ” + b + “, arg3: ” + c);
        }
    };
    Subscriber2.initialize();

    var fld2 = document.getElementById(“myfield2”); 
    if (fld2.addEventListener) {
        fld2.addEventListener(“click”, function () { Publisher.PublishOnClick(“PublishOnClick”, [‘1’, ‘2’, ‘3’]); }, false); // publish thru button click event
    }
    else if (fld2.attachEvent) {
        fld2.attachEvent(“onclick”, function () { Publisher.PublishOnClick(“PublishOnClick”, [‘1’, ‘2’, ‘3’]); }); // publish thru button click
    }
</script>

ASP.NET State Management

Posted: December 6, 2010 in ASP.NET
Tags:

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip. For example, if a user enters information into a text box, that information would be lost in the round trip from the browser or client device to the server.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options that help you preserve data on both a per-page basis and an application-wide basis. These features are as follows:

  • View state
  • Control state – is not affected when view state is disabled by a page developer.  When developing new custom control we can extend the PageStatePersister class and override Save/Load methods, and you can use page adapters to configure your ASP.NET application to use different view state persistence mechanisms based on the type of client to which a page is served. If you need to serialize view state and control state to a string, you can use the IStateFormatter object that is accessed using the StateFormatter property. It efficiently serializes and deserializes object state information to a Base64-encoded (similar to what ViewState does) string. You can also override the StateFormatter property to supply your own object state serialization mechanism.
  • Hidden fields
  • Cookies
  • Query strings
  • Application state
  • Session state
  • Profile Properties – allow you to manage user information without requiring you to create and maintain your own database. In addition, the ASP.NET profile feature makes the user information available using a strongly typed API that you can access from anywhere in your application.

I gave little explanation about Control State, Profile Properties methods as most of the developers or small projects or sites that are not user rich may not know/use them.

View state, control state, hidden fields, cookies, and query strings all involve storing data on the client in various ways. However, application state, session state, and profile properties all store data in memory on the server. Each option has distinct advantages and disadvantages, depending on the scenario.

For more information refer …

http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

.NET platform is an umbrella of languages. Many times developers who work in .NET  will have or find code in one language  when they need it in different language.

Many sites provide language conversion options which is very handy for developers and following link is one of such link …

http://www.developerfusion.com/tools

public void PrimeNumberCheck(object sender, ServerValidateEventArgs args)
{
int iPrime = Convert.ToInt32(args.Value);
int iLoop = 0;
int iSqrt = Convert.ToInt32(Math.Sqrt(iPrime));

for (iLoop = 2; iLoop <= iSqrt; iLoop++) {
if (iPrime % iLoop == 0) {
args.IsValid = false;
return;
}
}

args.IsValid = true;
}

A ValidationSummary control is displayed when the IsValid property of the page is false. It “polls” each of the validation controls on the page and aggregates the text messages exposed by each.  It does this through the Page.Validators collection; each validation control is added to this collection, and the validation summary can use this to determine which validators have errors.

When the user’s input is processed (for example, when the form is submitted), the Web Forms framework passes the user’s entry to the associated validation control or controls based on the ValidationGroup property. The validation controls test the user’s input and set a property to indicate whether the entry passed the validation test. After all validation controls have been processed, the IsValid property on the page is set; if any of the controls shows that a validation check failed, the entire page is set to invalid.

The following sample illustrates displaying errors with a ValidationSummary

<form id=”form1″ runat=”server”>
<div>
Age:<br />
<asp:TextBox runat=”server” id=”txt3″ />
<asp:RequiredFieldValidator runat=”server” id=”reqtxt3″ controltovalidate=”txt3″
errormessage=”Age” ValidationGroup=”234″ Display=”Static”>*</asp:RequiredFieldValidator>
<asp:RangeValidator runat=”server” id=”rangetxt3″ controltovalidate=”txt3″
errormessage=”Age – enter valid value (Between 1 to 120)”
MaximumValue=”120″ MinimumValue=”1″  Type=”Integer” ValidationGroup=”234″ Display=”Static”>*</asp:RangeValidator>
<br /><br />

Name:<br />
<asp:TextBox runat=”server” id=”txt1″ />
<asp:RequiredFieldValidator runat=”server” id=”reqtxt1″ controltovalidate=”txt1″ errormessage=”Name” ValidationGroup=”234″ Display=”Static”>*</asp:RequiredFieldValidator>
<br /><br />

<asp:Button runat=”server” id=”btnSubmit3″ text=”Ok” ValidationGroup=”234″/>
</div>

<div>
<asp:ValidationSummary ID=”valSum” runat=”server”
HeaderText=”You must enter a value in the following fields:”
Font-Names=”verdana”
Font-Size=”12″
DisplayMode=”BulletList”
ValidationGroup=”234″ />
</div>
</form>

References –

http://wiki.asp.net/page.aspx/237/validation-controls/
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/validation/default.aspx