Saturday, November 22, 2008

Python love my C#

I worked on dynamic languages like Ruby, python for fun and liked python a lot. When IronPyhon was introduced as DLR (Dynamic language runtime) i was particularly interested in where the things were heading.

Inclusion of DLR into silverlight 2.0 is awesome buts what more interesting is how C# is adopting (morphing) into  Pyhton.
Wondering this i did some research and found this article which exactly states what i always thought.

This is cool stuff!!! I am in love with my C# again!!! ::D
Blogged with the Flock Browser

Python love my C#

I worked on dynamic languages like Ruby, python for fun and liked python a lot. When IronPyhon was introduced as DLR (Dynamic language runtime) i was particularly interested in where the things were heading.

Inclusion of DLR into silverlight 2.0 is awesome buts what more interesting is how C# is adopting (morphing) into  Pyhton.
Wondering this i did some research and found this article which exactly states what i always thought.

This is cool stuff!!! I am in love with my C# again!!! ::D
Blogged with the Flock Browser

Why C# doe not have Checked Exceptions like JAVA ?

I was wondering that fact and decided to search on it not found this.
An excellent write Iinterview on Checked Exceptions.

Blogged with the Flock Browser

Sunday, October 19, 2008

Chorme error!!

I recently found the solution for the error : "Application failed to initialize properly (0xc0000005)" when you run Google Chrome after installation.

For Symantec EP users, Change the following registry entry and restart the machine.

In Regedit:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SysPlant

change  Value of Start REG_WORD to 4. Refresh / restart machine.

Chrome should work fine now.

OR Use Flock instead. :D
Blogged with the Flock Browser

Friday, October 17, 2008

Who moved my chiron?

I am working with silverlight since WPF/E days and after the Silverlight 2 RTW release was wondering to my wonder tool Chiron.exe. A bit of searching took me to the blog which says:

Chiron is still available for you if you want it.  It is a part of the Silverlight Dynamic Languages SDK


which is available on Codeplex.  So if you need/want it, there you go. 
Some people were using Chiron for their automated build scenarios to
create the XAP package during the builds.  A lot of the packaging stuff
for XAPs is now a part of some of the MSBuild tasks, so you can still
automate your builds using MSBuild.


That explains the stuff; i presume. I am personally missing Chiron. Silverlight DLR, ironPython is something i love and like really, however, i do not have any great ideas where i can implemnet them. So most of times its just feel good POC on SL 2 DLR.

Bottonline: I will miss you, Chiron.


Blogged with the Flock Browser

Wednesday, October 01, 2008

Installing Chrome on Vista

I was really upset as Chrome was not getting installed on my vista machine and was scratching my head. The error was

(If you get the error message “Send request returned 0×80042197. Http status code 407." , After a while, i figured that it may be because my proxy requires a password (ie authenticate).
I did a research on google and found below comment. (No pun intended from my end)

The Chrome installer is trying to download itself, but the geniuses (yes, really) at google forgot to put in a password input box. Until Google releases an updated installer, you can download the full Chrome installer here:

http://dl.google.com/chrome/install/149.29/chrome_installer.exe

But my favorite remains FLOCK, Its the best!!!. I eveb blogged this using flock!!!

Blogged with the Flock Browser

Tuesday, September 30, 2008

NET Connection strings

 .NET SqlConnection object. 

Trusted Authentication

Data Source=ServerName; Initial Catalog=DatabaseName; Integrated Security=SSPI;

Trusted authentication uses the security credentials of the current user to make the connection to SQL Server.  SQL Server uses Windows (or Active Directory) to validate the current user.  ServerName can be the name of a server or the name of a SQL Server instance such as Server1\Instance2.  ServerName can also be expressed as an IP address.  SSPI stands for Security Support Provider Interface . 

SQL Server Security Authentication

Data Source=ServerName; Initial Catalog=DatabaseName; User Id=UserName; Password=UserPassword;

In SQL Server authentication SQL Server stores the username and password.  ServerName can be the name of a server or the name of a SQL Server instance such as Server1\Instance2.  ServerName can also be expressed as an IP address.

Setting the Application Name

Data Source=ServerName; Initial Catalog=DatabaseName; Integrated Security=SSPI; Application Name=MyAppName;

I often set the Application Name in connections strings.  Whatever text you assign to Application Name will appear in a couple of different places:

  • It will be displayed in Profiler under the Application Name column.
  • It will be shown in the output of sp_who2 in the Program Name column.
  • It will be shown in the Activity Monitor in the Application column.  You can get to the Activity Monitor in SQL Server Management Studio by Management -> Activity Monitor.
  • It will appear in the program_name column if you select from master.dbo.sysprocesses (for SQL Server 2000)
  • It will appear int he program_name column if you select from sys.dm_exec_sessions (for SQL Server 2005 and later).

Setting the application name makes it very easy to find out what applications are issuing particular SQL statements against my database.  Setting the application name can also lead to an increase in the number of connections to your SQL Server.  Each client that uses connection pooling will create one pool inside each application per unique connection string.  If you use multiple application names you have the possibility to increase the number of pools and thus the number of connections to SQL Server.  I've always found it more beneficial to have the application name than to have a few less connections to my database servers.

Using MARS (Multiple Active Result Sets)

Data Source=ServerName; Initial Catalog=DatabaseName; Integrated Security=SSPI; MultipleActiveResultSets=True;

If you want to use MARS you'll need to enable it in the connection string.


Blogged with the Flock Browser

Tuesday, September 16, 2008

Explaining SAAS to my wife.

This weekend i was engaged with a rather uninteresting conversation with my wife. My wife is computer savvy but still is catching up on new technologies. Below is a brief snippet. I am hopeful that this will give you some idea on SAAS.

Me: ok...
Wife: What? you said something?
me: Nothing. I was just talking aloud... its about SAAS.
Wife: SAAS??? (for the less informed.. SAAS means mother-in-law in hindi !!!).  Are you watching those hindi serials lately?
me: Well, SAAS is a Acronym for Software As A Service.
Wife: You must be kidding. The other day you were talking about RUBY (Its another computer language, and a different story, however) and RIA(Rich Interactive Application). But SAAS?? Tell me more..
Me: Well as i said. SAAS is a new delivery model for software. Actually its NOT new at all... The concept is quite old. In older times, each industry have to generate its own electricity to operate. Later on as the scale of economies grew, electricity was provided by third parties and the industries just knew how to consume that electricity service. The technical know-how to how to produce electricity for mass consumption was taken care by these third parties.

Wife: Ok... its the same "PUSH" and "PULL" technologies on web everyone is talking about? We have Service Oriented Architecture since ages now!!!
ME: SAAS is achieved via SOA but it is a much bigger concept than the SOA itself. SAAS is a delivery model which provides many benefits over the traditional model. Its about catching the long tail.

Wife: The Long tail? ...
ME: Actually, there is a concept coined by Chris Anderson, who is the author of the book "the long tail". It talks about the fact that the future of the business is selling LESS of MORE. What is essentially means that if the distribution channel is large enough, products that have a low sales volume can collectively make up a market share which exceeds the relatively few bestsellers. So the sales drive is from small number of BIG customers to massive number of small customers. So you see ... its about tapping the business opportunity created by this long tail of small customers.
To serve the above, the costs should be significantly less and thats where the new Software delivery model of SAAS comes into picture.
Here is the WIKI definition
http://en.wikipedia.org/wiki/Software_as_a_Service

Software as a service (SaaS, typically pronounced 'sass') is a model of software deployment where an application is hosted as a service provided to customers across the Internet. By eliminating the need to install and run the application on the customer's own computer, SaaS alleviates the customer's burden of software maintenance, ongoing operation, and support. Conversely, customers relinquish control over software versions or changing requirements; moreover, costs to use the service become a continuous expense, rather than a single expense at time of purchase. Using SaaS also can conceivably reduce the up-front expense of software purchases, through less costly, on-demand pricing. From the software vendor's standpoint, SaaS has the attraction of providing stronger protection of its intellectual property and establishing an ongoing revenue stream. The SaaS software vendor may host the application on its own web server, or this function may be handled by a third-party application service provider (ASP). This way, end users may reduce their investment on server hardware too.


Key characteristics

The key characteristics of SaaS software, according to IDC, include:[3][dead link]

  • network-based access to, and management of, commercially available software
  • activities that are managed from central locations rather than at each customer's site, enabling customers to access applications remotely via the Web
  • application delivery that typically is closer to a one-to-many model (single instance, multi-tenant architecture) than to a one-to-one model, including architecture, pricing, partnering, and management characteristics
  • centralized feature updating, which obviates the need for downloadable patches and upgrades.

SaaS applications are generally priced on a per-user basis, sometimes with a relatively small minimum number of users and often with additional fees for extra bandwidth and storage. SaaS revenue streams to the vendor are therefore lower initially than traditional software license fees, but are also recurring, and therefore viewed as more predictable, much like maintenance fees for licensed software.

Wife: What the deal about multi tenancy:
Me:
    Multitenancy refers to the architectural principle, where a single instance of the software runs on a software-as-a-service (SaaS) vendor’s servers, serving multiple client organizations (tenants). Multitenancy is contrasted with a multi-instance architecture where separate software instances (or hardware systems) are set up for different client organizations. With a multi-tenant architecture, a software application is designed to virtually partition its data and configuration so that each client organization works with a customized virtual application instance.

Maturity levels of SAAS

SaaS architectures generally can be classified as belonging to one of below Maturity levels. whose key attributes are configurability, multi-tenant efficiency, and scalability. Each level is distinguished from the previous one by the addition of one of those three attributes:

  • Level 1 - Ad-Hoc/Custom: At the first level of maturity, each customer has its own customized version of the hosted application and runs its own instance of the application on the host's servers. Migrating a traditional non-networked or client-server application to this level of SaaS typically requires the least development effort and reduces operating costs by consolidating server hardware and administration.
    • Level 1 (Chaos); Every time you add a new customer, you add a new instance of the software.
    • At its level, nothing is done for allowing multiple tenants running on the same instance. The only way to support multiple customers is to serve them with different copies of the software. Furthermore, because little is done to allow customization through configuration, each copy includes specific customer customizations, in the forms of custom extension code, custom processes, custom data extensions. Needless to say that although “technically” the software is delivered as a service (i.e. the software does not run on premise) economy of scale cannot be achieved as each customer runs a different instance of the software. Although this could be a starting point to validate the business model, one has to move quickly up. Managing 1000s of customer at this level is very difficult.
  • Level 2 - Configurable: The second maturity level provides greater program flexibility through configurable metadata, so that many customers can use separate instances of the same application code. This allows the vendor to meet the different needs of each customer through detailed configuration options, while simplifying maintenance and updating of a common code base.
    • Level 2 (Managed Chaos): Every customer runs on the same version of the software and any customizations are done via configuration. But, you still have different instances for each customer (their own website, their own virtual server, their own physical server, etc.).
    • the software can be tailored  for each tenant via configurations (no custom code), all the tenants use the same code. However at level 1, the architecture is still not multi-tenant, each customer runs its own copy (albeit the same). The separation can be either virtual (virtual machines on a same server) or physical (running on separate machines). Although much better than previous level, the architecture allows customization through configuration (code base is the same), the computing power is not shared among the instances and therefore the provider cannot achieve economy of scale, putting it at a competitive disadvantage vs. a multi-tenant solution.
  • Level 3 - Configurable, Multi-Tenant-Efficient: The third maturity level adds multi-tenancy to the second level, so that a single program instance serves all customers. This approach enables more efficient use of server resources without any apparent difference to the end user, but ultimately is limited in its scalability.
    • level 3 (Multi-Tenant, Highrise): You've got all customers running on a single version of the software, and they're all running essentially on one "instance".The good news is that you're getting the benefits of multi-tenant (sharing resources across customers). Even better is that you're not writing custom code for each customer -- everyone essentially runs on the same version. The big challenge is that as you add more floors to your building (to stretch the analogy a bit), it gets more and more expensive. And, there are limits to how high you can build to accomodate a large number of tenants.
    • At this level. the application architecture includes the multi tenancy concepts. Akin to level 1, the UI can be customizable per tenant, so can the business rules and the data model. The customization per tenant is fully performed through configuration and is performed through a self-service tool, getting around the need of provider intervention. It is almost the SaaS "perfect case"; the only big piece missing at Level 2 is the capacity to scale out; the data partitioning is such at this level that growth can only be achieved by scaling up.
  • Level 4 - Scalable, Configurable, Multi-Tenant-Efficient: At the fourth and final SaaS maturity level, scalability is added through a multitier architecture supporting a load-balanced farm of identical application instances, running on a variable number of servers. The system's capacity can be increased or decreased to match demand by adding or removing servers, without the need for any further alteration of application software architecture.
    • Level 4 (Multi-Tenant, Build-Out): This is when you've got multi-tenant, single version of the software model. But, you can scale-out (add buildings at will). This is optimal because instead of letting the architecture decide how many tenants you put into a building, you can let the economics decide. And yes, there is an optimal number of tenants per instance and this number varies on your situation.
    • At this level, the architecture allows all the capabilities of level 3 (multi-tenancy, configuration) plus the scale out of the application. New instances of the software can transparently be added onto the instance pool to dynamically support the increasing load. Appropriate data partitioning, stateless component design, shared metadata access are part of the design. In this model a Tenant Load Balancer (round robin, rule based…) is introduced, maximizing the utilization of hosting resources (CPU, storage etc.); the total load is adequately distributed over the entire infrastructure. The data is also periodically moved to average the data load per instance. The architecture is scalable, multi-tenant and customizable via configuration.
  • Level 5 (Utopia): This is like Level 3, except you've figured out an efficient way to run different versions of the software on different "instances". You're doing this not because you're writing custom code for a customer, but because you want to run different code for different customers -- to try things out. The best example is having an "early adopter" instance where customers that want to use your latest and greatest features can do so. Helps them. Helps you. Helps everyone. As long as you're efficient about release management.

Virtualization also may be used in SaaS architectures, either in addition to multi-tenancy, or in place of it. One of the principal benefits of virtualization is that it can increase the system's capacity without additional programming. On the other hand, a considerable amount of programming may be required to construct a more efficient, multi-tenant application. Combining multi-tenancy and virtualization provides still greater flexibility to tune the system for optimal performance.[6] In addition to full operating system-level virtualization, other virtualization techniques applied to SaaS include application virtualization and virtual appliances.



Benefits of Saas

    * Cost: the inherent economy of scale found in SaaS gives SaaS providers the ability to deliver services very cost-effectively.

    * Risk mitigation: in theory, SaaS providers assume the risks of developing, maintaining, and delivering an application.

    * Accessibility: as long as one has access to a web browser and an Internet connection, users in different states, countries or even continents can access the same information in real time without the delay of synchronizing off-network changes. This is a key advantage of SaaS.

    * Frequent upgrades: updates are made frequently and, for the customer, effortlessly. Because the software is delivered over the Internet, hosted providers have greater flexibility in upgrading the applications and rolling out changes to customers. Traditional software vendors, by contrast, might upgrade software once a year, if that, but the customers bear the burden of reconfiguring it and paying for the newer version. Using the hosted model means customers can do more to shape the application.

    * Lower total cost of ownership (TCO): traditional software, regardless of business size, can cost thousands to tens of thousands of dollars in implementation fees, hardware, maintenance, services, and support. SaaS gives companies the opportunity to enjoy a “zero touch” software application – this means zero maintenance, end user support, and administration costs. Add to this comparatively low implementation and customization costs, SaaS offers a much better TCO than on-premises offerings.

    * Flexible contracts: when compared to outsourcing, this is one of the biggest advantages of SaaS. Many SaaS providers offer short-term and, in some cases, month-to-month contracts. This is the ultimate “try-before-you-buy” flexibility that can help businesses make a strategic decision with little or no liability.

    * Predictability: while this may not be a pro that some businesses realize at the onset, cost, service levels, and staffing requirements all become more predictable.

    * Scalability: SaaS offerings are easily able to develop with the growth of a company, maintaining performance levels and uptime.

    * Business-focused IT services: While traditional IT organizations have been responsible for delivering technology, today’s businesses look to IT for thought leadership and business-enablement as well. Offloading aspects of technology delivery can free up IT executives and technicians alike to pursue high-impact projects that add value to the business.

Simply put, SaaS can save a company the headaches of ongoing maintenance, time and money in IT support and equipment costs. Additionally, the key factors that can influence and organizations choice of adopting a SaaS solution are scalability, accessibility, flexibility, and dependability, as well as massive advantage of speed to market.

Pitfalls in SAAS

    * Standard product for all customers: with enterprise resource planning (ERP) and customer relationship management (CRM) products, there has traditionally been a greater deployment investment with customizing the software to fit the business. Some SaaS products offer limited customization options. These possible limitations may require adopters to change their internal operations to fit the application.

    * Outages: the presence or absence of a guarantee on uptime should be an element considered when selecting an on-demand provider. Why so? Because there is always a possibility that an outage may occur, no matter how remote the possibility. Many SaaS providers will build “uptime guarantees” into their service level agreements (SLAs). That’s not to say that reliability won’t keep improving—such guarantees, as well as mounting competition, all but insures that outages will become increasingly rare.

    * Single tenant: some SaaS offerings are built on what is referred to as “single-tenant” architecture. This means that these offerings were built to a single company’s specifications and make available as a SaaS. Single tenant offerings are likely to encounter the same customization and cost problems as traditional software. Recent advancements in SaaS have given rise to a “multi-tenant” architecture, allowing the vendor the ability to maximize the efficiencies of scale using a shared application and shared hardware.

    * Accessibility: Just as much as it’s an argument for, accessibility can also be an argument against if one does not have access to a web browser.

    * Cookie cutter: an early criticism of SaaS is that the offerings were too generalized. They also couldn’t be customized like traditional software applications and even certain shrink-wrap applications. In the early days, extensibility and integration was clumsy. It’s important to note that many SaaS providers now offer customization platforms that are extremely robust and make integration and extensibility as easy as point-and-click.

    * Scale: the majority SaaS providers are aiming for the small-to-medium-business (SMB) market. Those SaaS applications may not scale to tens of thousands of concurrent users. As SaaS and business continue to evolve, this is likely to change.

After all this there was no reply from my wife.. She was already into deep sleep!!!! :D

Note: The above conversation have adapted definitions, references and other well know articles on SaaS. I presume to present due credit to them wherever required, whether mentioned in article or not.




Blogged with the Flock Browser

Monday, September 01, 2008

Bubbling exception

When bubbling some exception up to some interface handlers, what is most recommandable:
try
{ // Do something }
 catch ( Exception )  // notice no variable ex
 {// Do something throw; }


 or:

try
    { // Do something }
catch ( Exception ex )
    { // Do something throw ex; }

if you catch an exception and then rethrow that exception using "throw ex;", the effect is actually that a new Exception will be created in the current scope, and the stack trace will be erased. When the exception is finally handled, the stack trace will start at the point where you rethrew it, instead of starting at the exception's origin.

If you catch an exception and the rethrow that exception using "throw;", you re-throw the exact same Exception, and the stack trace is preserved. Your Exception doesn't suffer amnesia, it remembers where it comes from.

Of course, another better known option is to wrap the caught exception in another one, using the Exception.InnerException property.


Blogged with the Flock Browser

Saturday, July 26, 2008

Uncommon C# keywords

stackalloc
    stackalloc allocates memory dynamically from the stack. Its very fast and the memory is reclaimed after the enclosing function exits. But it, of course, has some limitations. It only works with blittable types. It's good for arrays that will never be anything more than a few hundred kilobytes. By default, the maximum stack size is one megabyte. In practive, function call depth is very very small, unless you do something like a recursive function scanning a deep tree. Offsetting the risk that a stackalloc can generate the StackOverflowException is the infrequency of multiple dynamic stack allocations in use at the same time.

    Even for moderately large arrays, stack-based allocation can be preferable to heap allocations, especially if these allocations are very frequent or very temporary. The worst type of allocation for the garbage collector are large arrays, especially temporary ones. Large objects (over 85K) are placed separately in the large heap and are only release during a full garbage collection. (In other words, the more frequent Gen 0 or Gen 1 partial collections do not release large memory allocations). Large objects are never compacted, resulting in potential fragmentation and wasted memory.

yield
    yield is a common term used when referring to Iterators. The keyword can only be used in the context of an Iterator actually. Furthermore, the definition of an iterator holds the usage of yeild. Here are some definitions via MSDN.
t

  • An iterator is a section of code that returns an ordered sequence of values.
  • An iterator can be used as the body of a method, an operator, or a get accessor.
  • The interator code uses the yield return statement to return each element in turn.
  • Using iterators, it is no longer necessary to implement the interfaces System.Collections.IEnumerable and System.Collections.IEnumerator when creating a collection class that supports foreach. The compiler does this work for you.
  • The return type of an iterator must be System.Collections.IEnumerable, System.Collections.IEnumerator or one of the generic iterator interfaces.
volatile
    The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

    The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. See How to: Create and Terminate Threads (C# Programming Guide) for an example of volatile in a multi-threaded scenario.

default
    Generally seen in generic code, the default keyword can be used to obtain the default value to a parameterized type (such as T) when you don't know some of the following:

  • Is the type: Value-Type or Reference Type.
  • If it is a value-type, is it numeric or a struct.
The easiest way to get the initialized value is by calling the default keyword. This will avoid any code that may initialize a generic type to null or a numeric value. We can add a little more polish to our generic types and utilize the type constraints feature of C# 2.0.

Type Constraints
    Aside from the usual keywords, there are also other concepts that may be uncommonly used. One really neat trick to generics in C# .NET 2.0 is type constraints. This is where you can take a generic type like T, and apply constraints such as the types polymorphisms and inheritance factors. We can take a simple type T, and actually require that it implements a given interface or inherits from a particular class. Even still, we can require that it has a default constructor created.

In this case I am writing type constraints on the generic type Products to implement the IBuilder interface and contain a default constructor (indicated by the new() constraint). This can be handy when dealing with generic types and you can ensure that not just any type is being used for a particular class.
Blogged with the Flock Browser

Sunday, July 06, 2008

Learn to teach!!! Are u participating?

   
Subodh Pushpak

Delhi
Volunteer - Class of 2008
 
Blogged with the Flock Browser

Monday, April 14, 2008

REST - Representational State Transfer

REST

REST strictly refers to a collection of network architecture principles which outline how resources are defined and addressed. The term is often used in a looser sense to describe any simple interface which transmits domain-specific data over HTTP without an additional messaging layer such as SOAP or session tracking via HTTP cookies.

REST Principles:
  • Application state and functionality are divided into resources
  • Every resource is uniquely addressable using a universal syntax for use in hypermedia links
  • All resources share a uniform interface for the transfer of state between client and resource, consisting of
    • A constrained set of well-defined operations
    • A constrained set of content types, optionally supporting code on demand
  • A protocol which is:
    • Client-server
    • Stateless
    • Cacheable
    • Layered
REST:
  • Provides improved response times and server loading characteristics due to support for caching
  • Improves server scalability by reducing the need to maintain communication state. This means that different servers can be used to handle initial and subsequent requests
  • Requires less client-side software to be written than other approaches, because a single browser can access any application and any resource
  • Depends less on vendor software than mechanisms which layer additional messaging frameworks on top of HTTP
  • Provides equivalent functionality when compared to alternative approaches to communication
  • Does not require a separate resource discovery mechanism, due to the use of hyperlinks in content
  • Provides better long-term compatibility and evolvability characteristics than RPC. This is due to:
    • The capability of document types such as HTML to evolve without breaking backwards- or forwards-compatibility, and
    • The ability of resources to add support for new content types as they are defined without dropping or reducing support for older content types.

    Various websites and web applications offer REST-like developer interfaces to data (e.g. Flickr or Amazon S3).
Difference between POX/HTTP, SOAP, and REST....
  • REST is an architectural style that is independent, but compatible, with XML. It’s about identifiable resources, resource representations, a fixed (uniform) interface, and linking. HTTP is REST’s most popular instantiation.

  • POX/HTTP means exchanging plain old XML documents over HTTP. RESTful POX, i.e. using XML in a RESTful manner, would mean POX is a subset of REST. Many, if not most POX applications don’t care about REST very much, though — they’d thus be part of a distinct set of applications.

  • SOAP is a standard document format for building high-level protocols. Anything that uses SOAP is (by definition) not just using plain old XML, and thus not POX; it may be RESTful, unless it violates REST principles.

For best explanations visit http://tomayko.com/writings/rest-to-my-wife.
Blogged with the Flock Browser

YaHoo messenger smilies. :)

:-??       confused
%-(        not listening
:o3        dog
~:>        Chiken
:(|)         Monkey
>:/        bring it on
;))          giggle
[-o<     pray
3:-o     cow
:-@      chatter
Blogged with the Flock Browser

Silverlight HTTP Pipeline

In Silverlight 2, by default, only able to talk back to the site of origin server is allowed.
To acheive that the HTTP request is going back to site of origin look at the deployment URI of the XAP and the request URI.
Comparing these two URIs, 3 things must match:
  1. Same domain. http://foo.com  is different than http://bar.foo.com or http://www.foo.com
  2. Same protocol. http://foo.com is different than https://foo.com
  3. Same port. http://foo.com is different than http://foo.com:8080

HTTP requests themselves are:

  • Asynchronous only
  • Can only be initiated on the UI thread
There are two APIs in Silverlight for HTTP communication.  The first is WebClient and the second is HttpWebRequest.

WebClient

WebClient is a great API with a simple, events-based paradigm.  Used to easily download a string or a Stream.

WebClient, behind the scenes, does a GET request and then gives back the result in the form required.  It also automatically resolves relative URIs against the deployment URI of the XAP.


   1: private void DownloadString()
   2: {
   3:     WebClient webClient = new WebClient();
   4:  
   5:     // Hook up events
   6:     webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
   7:     webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
   8:  
   9:     // Initiate download
  10:     webClient.DownloadStringAsync(new Uri("myfeed.xml", UriKind.Relative));
  11: }
  12:  
  13: void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
  14: {
  15:     // Update progress UI
  16:     progressTextBox.Text = e.ProgressPercentage;
  17: }
  18:  
  19: void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
  20: {
  21:     if (e.Error == null)
  22:     {
  23:         // Clear progress UI and show downloaded string
  24:         progressTextBox.Text = "";
  25:         feedTextBox.Text = e.Result;
  26:     }
  27: }
  28:  


HttpWebRequest & HttpWebResponse

HttpWebRequest and HttpWebResponse are the standard .NET HTTP apis.  They are much more powerful than WebClient but also more complex to use. Used to set headers or to issue a POST request.


   1: private void SendPostRequest()
   2: {
   3:     HttpWebRequest request = WebRequest.Create(new Uri("http://foo.com/upload")) as HttpWebRequest;
   4:     request.Method = "POST";
   5:  
   6:     //  Set ContentType through property 
   7:     request.ContentType = "application/xml";
   8:  
   9:     //  Set other headers through Headers property
  10:     request.Headers["x-custom-header"] = "value";
  11:  
  12:     //  Initiate getting request stream
  13:     IAsyncResult asyncResult =
  14:     request.BeginGetRequestStream(new AsyncCallback(RequestStreamCallback), request);
  15: }
  16:  
  17: private void RequestStreamCallback(IAsyncResult ar)
  18: {
  19:     HttpWebRequest request = ar.AsyncState as HttpWebRequest;
  20:  
  21:     // populate request stream
  22:     request.ContentType = "text/xml";
  23:     Stream requestStream = request.EndGetRequestStream(ar);
  24:     StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.UTF8);
  25:     streamWriter.Write("<?xml version="1.0"?>"
  26:                        + "<entry xmlns="http://www.w3.org/2005/Atom">"
  27:                        + "<author>"
  28:                        + "<name>Elizabeth Bennet</name>"
  29:                        + "<email>liz@gmail.com</email>"
  30:                        + "</author>"
  31:                        + "<title type="text">Entry 1</title>"
  32:                        + "<content type="text">This is my entry</content>"
  33:                        + "</entry>");
  34:     streamWriter.Close();
  35:  
  36:     // Make async call for response
  37:     request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
  38: }
  39:  
  40: private void ResponseCallback(IAsyncResult ar)
  41: {
  42:     HttpWebRequest request = ar.AsyncState as HttpWebRequest;
  43:     WebResponse response = request.EndGetResponse(ar);
  44:  
  45:     // use response.  
  46: }

Thanks to Scorbs for such a in depth explanation, for more please visit http://scorbs.com/.



Blogged with the Flock Browser

The 23 Gang of Four Design Patterns .. Revisited

The Gang of Four (GoF)(from Design Patterns: Elements of  Reusable Object-Oriented Software, Addison-Wesley Professional Computing Series, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides).

These 23 GoF patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral.

Creational Patterns
  1. Abstract Factory:  Creates an instance of several families of classes. Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  2. Builder: Separates object construction from its representation. Separate the construction of a complex object from its representation so that the same construction processes can create different representations.
  3. Factory Method: Creates an instance of several derived classes. Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  4. Prototype: A fully initialized instance to be copied or cloned. Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  5. Singleton: A class of which only a single instance can exist. Ensure a class only has one instance, and provide a global point of access to it.

Structural Patterns
  1. Adapter: Match interfaces of different classes.Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
  2. Bridge: Separates an object’s interface from its implementation. Decouple an abstraction from its implementation so that the two can vary independently.
  3. Composite: A tree structure of simple and composite objects. Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  4. Decorator: Add responsibilities to objects dynamically.  Attach additional responsibilities to an object dynamically. Decorators provide a             flexible alternative to subclassing for extending functionality.
  5. Facade: A single class that represents an entire subsystem. Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use.
  6. Flyweight: A fine-grained instance used for efficient sharing. Use sharing to support large numbers of fine-grained objects efficiently. A flyweight is a shared object that can be used in multiple contexts simultaneously. The flyweight acts as an independent object in each context — it’s indistinguishable from an instance of the object that’s not shared.
  7. Proxy: An object representing another object. Provide a surrogate or placeholder for another object to control access to it.
Behavioral Patterns
  1. Chain of Resp. : A way of passing a request between a chain of objects. Avoid coupling the sender of a request to its receiver by giving more than one object a  chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
  2. Command: Encapsulate a command request as an object. Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
  3. Interpreter: A way to include language elements in a program. Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
  4. Iterator: Sequentially access the elements of a collection. Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  5. Mediator: Defines simplified communication between classes. Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
  6. Memento: Capture and restore an object's internal state. Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later.
  7. Observer: A way of notifying change to a number of classes. Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  8. State: Alter an object's behavior when its state changes. Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
  9. Strategy: Encapsulates an algorithm inside a class. Define a family of algorithms, encapsulate each one, and make them interchangeable.            Strategy lets the algorithm vary independently from clients that use it.
  10. Template: Defer the exact steps of an algorithm to a subclass. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
  11. Visitor: Defines a new operation to a class without change. Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
I must also mention and credit goes to http://www.dofactory.com/Patterns/Patterns.aspx for the most of the above information.



Blogged with the Flock Browser

Saturday, March 22, 2008

Destiny

After playing with the idea for long, today i went ahead with it. Actually, i always thought i do not have ample time for such silly things, but i realized i actually do have. I can certainly have some time for creativity!!!

So, here it is. But first the preface... Like so many people i like reading news (minus yellow journalism) and the debates on them. Each person will look at the news from hie own perspective.

Then there is virtualization. the what ifs... the food for thought for the legendary writers.

The idea is to create a component which will read daily news and then somehow(i have an idea though!!) link the stories together to cook up a fictional story.

What good it will do? i dont know.. may be that way we can find out how we react to stories or is there a pattern in this otherwise seemingly chaotic world around us...

May be it can whip out a story good enough for a hollywood potboiler!! May be a non sensical black humour.. who knows?

Just cant wait to see what a number cruching machine (read computer) can do when it can relate one MS Doni being the hottest person on sale to a non descriptive Indian soldier (they call him spy!) Sabarjit waiting to hanged in pakistan after spending entire life time in jail.

May be it can actually give us data on how a budget is related to increasing number of farmers commiting suicides or how rain is actually responsible for giving millions of unprivilged indians like me to own a lakhtakia(Rs 1 lakh) car sans Mr. Tata. :) 

And when it does, It recreates destiny.

The idea is simple enough, but to make it really work i will have to spend some midnight oil. I am ready. A crash course in Artificial intelligence would be handy. :)


below is the mind map of the idea. If it all sounds very foolish and stupid to you.... You are the person i would be needing.



    News Feed1,
    News Feed2 -- > Component. (Definately not a news aggeregater) ---- > AI stuff --- > Our fictional story.
        


PS: There is no commercial value attahced to the project, Just plain challenge. As a famous MNC hotshot was once commented at "Arent you fed up with selling boltteled carbonated water?" and rest is history. (No pun intended, but my organization just gave up keeping free carbonated cold drinks!)


If anyone of you are game for it, do just post your comments here or shoot me an email.

The name of the project... well you guessed it... :) its DESTINY.

Blogged with the Flock Browser

Monday, March 10, 2008

GlobalLogic WCF training ppt slides

The ppt is shared @ this Location.
Your suggestions/ comments are welcome, as always :)

I would be posting the demos as well soon..

Blogged with Flock

Monday, February 18, 2008

HTTP PipeLine and Application / Page Events


See the below three figures...









1. The ASP.NET HTTP pipeline relies on IIS to receive the request.

2. When IIS receives an HTTP request, it examines the extension of the file.

3. If the file extension is associated with executable code, IIS invokes that code, in order to process the request.

4. Mappings from file extensions to pieces of executable code (.exe) are recorded in the IIS metabase.

5. When ASP.NET is installed, it adds entries to the metabase (associating various standard file extensions, including .aspx and .asmx), with a library called aspnet_isapi.dll.

6. When IIS receives an HTTP request for one of these files, it invokes the code in aspnet_isapi.dll, which in turn funnels the request into the HTTP pipeline.

7. Aspnet_isapi.dll uses a named pipe to forward the request from the IIS to an instance of the ASP.NET worker process, aspnet_wp.exe.

8. The aspnet_wp.exe worker process uses an instance of the HttpRuntime class to process the request.



Below the diagrammatic representation of mixing Page-Events with Application-Events.








This life cycle of the ASP.NET page starts with a call to the ProcessRequest() method. This method begins by initializing the page's control hierarchy.

The life cycle of Page ends by handing off the Web page's HTML markup to the Web server, which sends it back to the client that requested the page.

1

Application_Start

2

Application_BeginRequest

3

Application_AuthenticateRequest

4

Application_AuthorizeRequest

5

Application_ResolveRequestCache

6

Session_Start

7

Application_AcquireRequestState

8

Application_PreRequestHandlerExecute

 

Page Life Cycle occurs, and at the end generated HTML is sent to the server. This HTML is then rendered by the client/browser.

This is the place where the Page events mentioned at the right side of figure 2 occurs.

9

Application_PostRequestHandlerExecute

10

Application_ReleaseRequestState

11

Application_UpdateRequestCache

12

Application_EndRequest

13

Application_PreSendRequestHeaders

14

Application_PreSendRequestContent

 

Form Displays



Blogged with Flock