Sunday, September 19, 2010

Debugging Blogspot+Silverlight+Dropbox issue

I traced my browser calls when it loaded the demo silverlight app and I got the following:



Request URL:http://dl.dropbox.com/u/4186718/Nitin.Spike.XAPHosting.xap
Request Method:GET
Status Code:200 OK
Response Headers
Content-Type:application/octet-stream
Date:Sun, 19 Sep 2010 06:12:06 GMT
Server:dbws
accept-ranges:bytes
cache-control:no-cache
content-length:4379
etag:10n
pragma:no-cache
x-robots-tag:noindex,nofollow




The problem is that the Content-Type is application/octet-stream, it should have been application/x-silverlight-app. Okay so we know the problem, how do we fix it? I am using dropbox, are they suppose to push with correct content-type or do i need to configure it somewhere... I have asked this question in their forums...

Thursday, September 02, 2010

Testing Silverlight

Get Microsoft Silverlight




Okay it doesnt work, but i see a lot of people displaying silverlight content on blogspot. I wonder whats going wrong. I guess i am done using these free blog hosting sites... its time to move to my own blog - its expensive but i will get to control a lot of stuff.
Update: I have finally hosted my silverlight XAP on a paid host and it works. :)

Saturday, August 28, 2010

Enum extensions

Sharing these Enum extension methods I wrote yesterday.
using System;
using System.ComponentModel;

namespace Nitin.Spike.EnumExtensions
{
    class Program
    {
        static void Main()
        {
            const Colors someColor = Colors.Red;
            string description = someColor.Description();
            if (someColor.HasDescription())
            {
                if (someColor.HasDescription("indicates stop", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Works");
                }
            }
        }
    }
    public enum Colors
    {
        [Description("Indicates Stop")]
        Red,
        [Description("Indicates Nothing")]
        Blue,
        [Description("Indicates Go")]
        Green
    }
    public static class EnumExtensions
    {
        public static string Description(this Enum someEnum)
        {
            var memInfo = someEnum.GetType().GetMember(someEnum.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);

                if (attrs != null && attrs.Length > 0)
                    return ((DescriptionAttribute)attrs[0]).Description;
            }
            return someEnum.ToString();
        }
        public static bool HasDescription(this Enum someEnum)
        {
            return !string.IsNullOrWhiteSpace(someEnum.Description());
        }
        public static bool HasDescription(this Enum someEnum, string expectedDescription)
        {
            return someEnum.Description().Equals(expectedDescription);
        }
        public static bool HasDescription(this Enum someEnum, string expectedDescription, StringComparison comparisionType)
        {
            return someEnum.Description().Equals(expectedDescription, comparisionType);
        }
    }
}

Saturday, July 31, 2010

High Speed Internet


The first time I connected to internet was some 9 years back, I got my own internet connection around 8 years back, and at that point of time I used to get 56 Kbps speed, and today I have a 512 Kbps line.

Is this speed enough for me? Hell no.. why not? because even today I can’t watch my videos directly off the web. Although I can watch low quality videos online, but now I want HD quality. I wonder if I will ever be satisfied with my connection.

Sunday, July 18, 2010

WPF Converter values


I posted this at stackoverflow : http://stackoverflow.com/questions/3204422/wpf-corelating-multibindings-and-converters-values

The problem was how do you handle indexes when your converter value array is of large size. I thought over it and come up with this:

https://www.assembla.com/code/TechnologyAndMe/subversion/nodes/ConverterValues
(Download complete source using a SVN client from http://subversion.assembla.com/svn/TechnologyAndMe/ConverterValues/)

So now all you have to do is :









Here Prop1,Prop2,Prop3 are the actual values that you want to pass to the converter, Value1, Value2, Value3 are just ids for Properties below them. Now in the converter, just use my BoundValues class and accessing the properties become as easy as saying :

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var boundValues = new BoundValues(values);

return string.Format("{0} {1} {2}",
boundValues["Value1"], boundValues["Value2"], boundValues["Value3"]);
}

Where BoundValues["Value1"] returns value of Prop1, so now I no longer have to worry about managing the sequence of bindings in my XAML.

Thursday, May 27, 2010

Generic Singleton

****

What was I thinking, if I use any regular class here, it will not be singleton as you could always new() up an instance.

****
Once and for all, I am going to settle with this implementation of singleton.

https://www.assembla.com/code/TechnologyAndMe/subversion/nodes/Singleton
(Download complete source using a SVN client from http://subversion.assembla.com/svn/TechnologyAndMe/Singleton )

Singleton is now as easy as:
var instance = Singleton<SomeOtherClass>.Instance;

Tuesday, May 18, 2010

Agile Estimation

I have created this document describing how to estimate for agile projects :
http://docs.google.com/View?id=dm24bwn_37hkjw97ff

Please provide your feedback and you are more than welcome to contribute your ideas/experiences.

Sunday, May 16, 2010

Downside of LINQ

 

  1. Operators like Orderby are greedy, when used execution is no longer lazy.
  2. You have to pay more attention to LINQ queries for remote data
  3. If you use Count on LINQ query and also use the same query in foreach, then you end up iterating over the dataset twice.
  4. no edit and continue support

Wednesday, May 05, 2010

Why should you use LINQ


What are the benefits of using LINQ?

  • Lazy evaluation
  • Parallel execution using PLINQ
  • Abstraction – declarative – only tells what is required, not how to get it
  • Because of extension methods – you can apply LINQ on anything
  • Works with any LINQ provider

Saturday, May 01, 2010

REST vs SOAP

 

REST

SOAP

Simple HTTP next DCOM
not transport neutral transport neutral
  message based security
only CRUD operations CRUD + more
can scale ?
broader reach and interoperability ?
std format using GET,PUT,POST,DELETE format is SOAP envelope,header,body
no need for WSDL  
data format can be JSON or XML  
easy to version and evolve ?
bookmarking and caching can be done cannot be done
Cloud computing people are using REST ?

SOAP is typically used in enterprise scenarios as middleware and most of the operations are pretty much CRUD operations.

Why REST :

  • if you only do HTTP
  • if you don’t need WS* and web Security(SSL) is good enough
  • Simpler than SOAP , uniform, comparable

Why SOAP :

  • if you need message based security – banks
  • your services are middle ware rather than public web services(web facing)
  • your services are local to enterprise

My post here tells you what REST is, however that is the most common understanding of REST, the definition goes beyond it, ex.

  • that resources be self-describing
  • complete object should be provided to POST/PUT instead of key value pairs of updates
  • collection of resources should be resource that represents a collection of other resources

World wide web is a RESTful system. Does your browser (the client) know whether it’s displaying a banking website or a casual game? Nope, it just utilizes standard media types (HTML, CSS, Javascript) to compose and represent the data. You don’t have to know the specific URL you’re looking for on a website so long as you know the “starting place” (usually the domain name) and can navigate there.

So REST is an ingenious and flexible way to allow for the consumption and traversal of network-available information. What it’s not, however, is a very good roadmap toward building APIs for web applications.

webHttpBinding - REST in WCF (Part 3)


Now we know that using [WebGet] we can get a resource based on URI. This is just the GET verb of HTTP, we also have other Verbs – PUT,POST,DELETE. To use these verbs WCF has the [WebInvoke] attribute.

However we cannot allow anyone to PUT,POST,DELETE our resources, so we will typically have some authentication process before we can allow this. This is achieved by reading and writing to the HTTP context. It can also be used to control caching, set content type, etc.

Taking the .svc Out of REST
WCF Services hosted in IIS use the .svc extension. This does not follow common REST URI naming practices. For example, the service in Part 1 and 2 is accessed using the following URI:
http://localhost/TimeService.svc/Now?GMT=1
You can remove the .svc extension by using an ASP.NET HttpModule (with IIS 7.0 only) to call HttpContext.RewritePath to modify the URI. This would allow the URI to take the following form: http://localhost/TimeService/Now?GMT=1


Technorati Tags: ,

webHttpBinding – REST in WCF (Part 2)


In Part 1, the service was exposed as /Now?GMT=5, now the solution is updated to handle request such as /GMT/5

Download the complete solution using an SVN client from here

[OperationContract]
[WebGet(UriTemplate = "/GMT/{GMT}")]
string GMT(string GMT);

Sunday, April 18, 2010

webHttpBinding – REST in WCF (Part 1)


REST stands for Representational State Transfer

It basically means exposing services

  • based on URI
  • encode message without the overhead of SOAP
  • pass parameter using HTTP
  • format data using JSON or POX

Service Contract

Get the complete code solution from this SVN url : http://subversion.assembla.com/svn/TechnologyAndMe/RestTimeService

using System.ServiceModel;
using System.ServiceModel.Web;

[ServiceContract]
public interface ITimeService
{
[OperationContract]
[WebGet]
string Now(string GMT);
}


Web.Config





behaviorConfiguration="webBehavior">

















Now to access the service hit the service with this url

http://localhost:3048/TimeService.svc/Now?GMT=1


The output is as follows


GMT 14/18/2010 23:23:58

Friday, April 09, 2010

Whitespace – Cleanest programming language


http://compsoc.dur.ac.uk/whitespace/

From their homepage -
“Most modern programming languages do not consider white space characters (spaces, tabs and newlines) syntax, ignoring them, as if they weren't there. We consider this to be a gross injustice to these perfectly friendly members of the character set. Should they be ignored, just because they are invisible? Whitespace is a language that seeks to redress the balance. Any non whitespace characters are ignored; only spaces, tabs and newlines are considered syntax.”

WTF. Now talk about dirty code.

User story formats

 

Now, usually the user stories that we write are of the format :
As A Bank Teller, I Want a name search field, So That I can quickly look up customers.

But like someone pointed out, it makes much more sense to construct the story as follows:
So That I can quickly look up customers, As A Bank Teller, I Want a name search field.

Further more, now we can relate the So That to actual business values and we also got rid of explicit implementation details from I Want, as follows:
So That I can serve customers faster, As A Bank Teller, I Want an efficient way to look up customers.

Sunday, April 04, 2010

WPF window phases

 

1. Constructor is called.
2. Window.Initialized event is raised.
3. Window.Activated event is raised.
4. Window.Loaded event is raised.
5. Window.ContentRendered event is raised.
6. User interacts with the window.
7. Window.Closing event is raised.
8. Window.Unloaded event is raised.
9. Window.Closed event is raised.

Wednesday, March 31, 2010

WCF Binding Features

 

Supported features for each binding

WCF Communication Bindings

 

Binding Name Description .NET

basicHttpBinding

Binding for WS-I Basic Profile 1.1 Web Services including ASMX Web Services

3.0/3.5

wsHttpBinding

Binding for advanced WS-* based Web Services such as WS-Security, WS-Transactions, and the like

3.0/3.5

wsDualHttpBinding

Binding to support bidirectional communication using duplex contracts.

3.0/3.5

webHttpBinding

Binding that supports REST/POX-based services using XML and JSON Serialization.

3.0/3.5

netTcpBinding

Binding for communication between two .NET-based systems.

3.0/3.5

netNamedPipeBinding

Binding for on-machine communication between one or more .NET-based systems.

3.0/3.5

netMsmqBinding

Binding for asynchronous communication using Microsoft Message Queue (MSMQ).

3.0/3.5

msmqIntegrationBinding

Binding for sending and receiving messages to applications through the use of queues using MSMQ.

3.0/3.5

wsFederationHttpBinding

Binding for advanced WS-* based Web services using federated identity.

3.0/3.5

ws2007HttpBinding

Binding derived from the wsHttpBinding with additional support for the latest WS-* specifications based on standards available in 2007.

3.5

ws2007FederationHttpBinding

Binding derived from the wsFederationHttpBinding with additional support for the latest WS-* specifications based on standards available in 2007.

3.5

Sunday, March 28, 2010

SOA != Web services


A lot of folks think a service oriented architecture is “Web services on steroids.”

In order for business to free itself from technology, the business logic must be separated from the plumbing, Web services technology is what allows us to make this separation, creating business service components from business applications. The business logic sits above
the plumbing in the business services layer. These business service components bring to the business the same efficiencies of reuse, ease of change, and consistency of results as Web services do on the programming level.

The creation of a SOA involves identifying the key business services and working top-down, versus bottom-up. Making key business services into black boxes means that business can reorganize itself as needed. Once you have several key business services, you string business services together to create a business process. In an insurance company, “claims handling” is a business process. In a hospital, “admitting a patient” is a business process.

Note that a business process is not by definition automated. It may indeed require manual participation or intervention. Great gains in efficiency come when a process is automated “from end to end,” but this is not always possible.

Saturday, March 27, 2010

What is SOA?


When business increases and becomes complicated, we need IT to sort out things. It enables us to create custom solutions which increases our productivity. Now with IT in place, when the business needs to change/do M&A/etc. the applications developed by IT dept is a roadblock, as it cannot magically start working as per new requirements, and changing the applications takes long time and of course lots of money. Thus, IT becomes a constraint for business to grow.

SOA (Service Oriented Architecture) is a new approach to building IT systems, It uses existing assets and enables change. SOA is suppose to liberate business from the constrains of technology. It lets the business focus more on business and less on technology.

Current IT systems suffer from the following complications:

  1. Business logic and plumbing
    One of the biggest problems in programming is that it is very difficult to keep the business logic separate from the plumbing because you need to control both at the same time. Though the tasks are related, they can be separated. It’s work, and it requires both the use of appropriate software tools and programmer discipline to ensure that the business logic is kept separate from the technology that makes it happen.
    For example, if you want to change the order in which particular business functions happen, and you’ve kept your business logic separate from your plumbing, making these changes is no big deal in a SOA. But if your business logic and your plumbing are one giant application, changes are costly and complicated, take time, require extensive testing, and are a very big deal indeed.
  2. Legacy Systems
    Business in many cases will depend on legacy systems which are in place and operational, and business does not have time or budget to start from scratch.
    With SOA, you can use almost all your existing business applications. True, you may need to change them a little in order to include them in a SOA, but it is possible, and it is not all that hard. For example, you can treat an entire application as a service, or you can take some code out of an application and make just that code into a service.
    A SOA uses very specific, industry-agreed upon standards to create interfaces that make it possible for various components of the SOA to talk to each other.
  3. Application archaeology
    It may not be possible to separate out business logic and plumbing as many of
    the business layer components come from existing applications, and existing business applications were likely built in very different ways, at different times, by different people, and for different reasons, maybe even using different computers. Unlike hardware, software hangs around for decades.
    Intelligent black-boxing is an important aspect of SOA. With a SOA, you can build a whole new computing environment by using all the resources that you already have by treating many components as black boxes. Particularly, you need to treat existing application components as black boxes, making them accessible by adding adapters. For example, you should use a black box to include older plumbing components that still work. The black box prevents you from spending money to replace something that works just fine. Or, as the sages say, “If it ain’t broke, don’t fix it.
  4. Who’s in charge
    If the plumbing for one component doesn’t work with the plumbing for several other components, how will an end-to-end process work? If it fails, how will you know?
    Any and all problems associated with the end-to-end processing of components are dealt with by a little something called the SOA supervisor. So, no need to worry, because the SOA supervisor will take care of things. The SOA supervisor acts something like a traffic cop and helps prevent SOA accidents.

So, technically, a service oriented architecture is an architecture for building business applications as a set of loosely coupled black-box components orchestrated to deliver a well-defined level of service by linking together business processes.

Monday, March 01, 2010

Extension methods on Interfaces

 

class Program
{
[STAThread]
public static void Main()
{
IFoo myFoo = new Foo();
myFoo.DoFoo(); //Class Foo does DoFoo()
myFoo.DoBar(); //Class FooExtensions does DoBar()
}
}
internal interface IFoo
{
void DoFoo();
}
internal class Foo : IFoo
{
public void DoFoo()
{
Console.WriteLine("Class Foo does DoFoo()");
}
}
internal static class FooExtensions
{
public static void DoBar(this IFoo obj)
{
Console.WriteLine("Class FooExtensions does DoBar()");
}
}

Sunday, February 28, 2010

Exception Handling Best Practices

 

  • Serialize exceptions, so that they are available across app domains.
  • As far as possible, let the exception be in the same assembly that throws it.
  • Use at least the 3 common constructors that Exception class provides.
  • Use pre-defined exceptions if possible instead of custom exceptions.
  • Return null instead of exception for common errors
  • Categorize exceptions in a hierarchy based on modules.
  • Include localized description string for exception.
  • Provide Exception properties for programmatic access.
  • Do not catch generic exceptions when specific exceptions can be caught.
  • Check for ErrorCode property in COMException for HResult value.
  • Make COM objects implement IErrorInfo, so that they can be access in .NET

Tuesday, February 23, 2010

Race condition and Deadlock

 

A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.

The typical solution to a race condition is to ensure that your program has exclusive rights to something while it's manipulating it, such as a file, device, object, or variable. The process of gaining an exclusive right to something is called locking.

A deadlock occurs when two threads each lock a different variable at the same time and then try to lock the variable that the other thread already locked. As a result, each thread stops executing and waits for the other thread to release the variable. Because each thread is holding the variable that the other thread wants, nothing occurs, and the threads remain deadlocked.

Deadlock Prevention

1. Remove mutual exclusion – no process should have exclusive access to a resource
2. Process should acquire all required resources before starting
3. By releasing resources after a certain amount of time
4. By assigning precedence to resources, so process an only try to acquire lower precedence resource

Managed Threading Best Practices

 

We use threading to increase responsiveness of our application and to do multiple tasks simultaneously(typically IO and CPU bound tasks).

  • Don't use Thread.Abort
    to terminate other threads. Calling Abort on another thread is akin to throwing an exception on that thread, without knowing what point that thread has reached in its processing.
  • Don't use Thread.Suspend and Thread.Resume
    to synchronize the activities of multiple threads. Do use Mutex, ManualResetEvent, AutoResetEvent, and Monitor.
  • Don't control the execution of worker threads from your main program (using events, for example).
    Instead, design your program so that worker threads are responsible for waiting until work is available, executing it, and notifying other parts of your program when finished. If your worker threads do not block, consider using thread pool threads. Monitor..::.PulseAll is useful in situations where worker threads block.
  • Don't use types as lock objects.
    That is, avoid code such as lock(typeof(X)), or the use of Monitor..::.Enter with Type objects. For a given type, there is only one instance of System..::.Type per application domain. If the type you take a lock on is public, code other than your own can take locks on it, leading to deadlocks.
  • Use caution when locking on instances, for example lock(this) in C#. If other code in your application, external to the type, takes a lock on the object, deadlocks could occur.
  • Do ensure that a thread that has entered a monitor always leaves that monitor, even if an exception occurs while the thread is in the monitor. The C# lock statement provide this behavior automatically, employing a finally block to ensure that Monitor..::.Exit is called. If you cannot ensure that Exit will be called, consider changing your design to use Mutex. A mutex is automatically released when the thread that currently owns it terminates.
  • Do use multiple threads for tasks that require different resources, and avoid assigning multiple threads to a single resource. For example, any task involving I/O benefits from having its own thread, because that thread will block during I/O operations and thus allow other threads to execute. User input is another resource that benefits from a dedicated thread. On a single-processor computer, a task that involves intensive computation coexists with user input and with tasks that involve I/O, but multiple computation-intensive tasks contend with each other.
  • Consider using methods of the Interlocked class for simple state changes,
    instead of using the lock statement. The lock statement is a good general-purpose tool, but the Interlocked class provides better performance for updates that must be atomic. Internally, it executes a single lock prefix if there is no contention. In code reviews, watch for code like that shown in the following examples.
  • Avoid the need for synchronization, if possible.
    This is especially true for heavily used code. For example, an algorithm might be adjusted to tolerate a race condition rather than eliminate it. Unnecessary synchronization decreases performance and creates the possibility of deadlocks and race conditions.
  • Make static data thread safe by default.
  • Do not make instance data thread safe by default.
    Adding locks to create thread-safe code decreases performance, increases lock contention, and creates the possibility for deadlocks to occur. In common application models, only one thread at a time executes user code, which minimizes the need for thread safety. For this reason, the .NET Framework class libraries are not thread safe by default.
  • Avoid providing static methods that alter static state.
    In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time. This opens up the possibility of threading bugs. Consider using a design pattern that encapsulates data into instances that are not shared across requests. Furthermore, if static data are synchronized, calls between static methods that alter state can result in deadlocks or redundant synchronization, adversely affecting performance.