The Paradox that is Agile

If you are following Agile to the letter, you are probably not following agile

So, Agile as a software development methodology has been around for a long time. Long enough for a lot of people in the software industry to know about it, follow it and to eventually abuse the spirit of it.

I’ve been seeing almost every team now-a-days trying to follow Agile in their projects. And I’ve seen people slacking away and not at all being able to follow some of it’s guidelines and I’ve seen a few of them being pretty strict with what agile has to say about software development practices.

So, the teams who actually slack away on agile methodologies and still claim to follow agile are the better ones out of two. Because I believe deep down they know that they are not agile.

The real problem is with teams who “claim” to be following agile by the book. We can call them the Agile Fanatics, but this term itself would be an oxymoron (right?).

The literal meaning of Agile is “being able to move quickly; being able to (respond to) change quickly”.

The Agile manifesto advocates to design your software development practices such that its easier for you to account for change (in requirements, timelines, resources etc.). BUT what if the software practices you have been following in accordance with the Agile manifesto aren’t making you or for that matter your project as “Agile” as you would like it to be. It’s a possibility, that, what works for a lot of other projects just isn’t the right fit for your project.

I believe, that, as much as you should be accepting of changes from the customer, you should also be accepting of the fact that the software practices you are (or have been) following might not be as effective and might need to change from time to time. And that the changes might not be completely in line with the Agile manifesto. And that’s okay, as long as it “works” to make your project Agile.

This isn’t a blog post about re-iterating the agile manifesto. It’s about re-iterating the fact that the guidelines in the agile manifesto are exactly that – “guidelines”.

So the next time you see your scrum master, manager, lead or even your colleague reading out the agile guideline(s) to you as if it were a rule and if you seriously think that it’s counter-productive for your team, please try to explain her/him that :

“If you are following agile to the letter, then you are probably not following agile”.

The thin line between Attention to Detail and OCD (Obsessive Compulsive Disorder)

OCD (wiki)- Obsessive–compulsive disorder is an anxiety disorder characterized by intrusive thoughts that produce uneasiness, apprehension, fear or worry (obsessions), repetitive behaviors aimed at reducing the associated anxiety (compulsions), or a combination of such obsessions and compulsions.

ATD – Attention to Detail is really just a quality in a person, wherein he/she has very keen eye for details (physical as well as abstract). OK, I know its a made up acronym, but I had to have something which stands up to the mighty OCD (and sounds cool 😎 )

 

Disclaimer: I realize OCD is a very serious condition in probably a lot of cases, But recently I have seen a lot of instances of the word OCD used in a very casual sense. It bothers me so much that it has made me write this post.

I have been alleged to suffer from OCD every now and then, esp. from my Wife. I know she means it in a casual sense (or else she would have got me tested by now 😉 )

Believe me I’ve watched House M.D. long enough to know that I don’t have any, BUT people cannot always be convinced, right 🙄 !!

So, my argument is that most of the time people who appear to have obsessive compulsive tendencies, actually have a great attention to detail. Of course their attention to details might be limited to certain objects or situations. For e.g. I am a programmer and over the years I have developed a keen eye for bugs when I read through a code block.

Also, when it comes to objects of interest like electronic items and their design I am very particular to differentiate between similar looking products. Ranging from design intricacies like the angle of curve of a tablet or even trivial things like the cuts on my apple earphone cable keep me interested (they’re fragile indeed and I need to know if I can patch them before its too late.)

Apart from electronics, everyday things like a detergent mark on the utensils I use are the things I look out for. I am a strong believer of human error and carelessness. I don’t trust anyone, including myself to have cleaned the utensils perfectly all the time. That’s the reason I look out for them. You may call me paranoid, but definitely not OC.

There are cases when people are very particular in the way a thing is done or it is arranged w.r.t. other things. They are hell-bent following a process. They keep on thinking about it, all the time. They don’t rest until they get it perfect. They are wired like that. You may call them bull-headed or even perfectionists, BUT definitely not OC.

A classis symptom of OCD is people washing their hands often. This symptom can also be argued as the people might have a very keen eye for dirt on their hands; even between the palm lines (which many a people would miss). I know it’s an argument I will lose, but there might be some cases when causes of this event are not psychological.

Well, now you may be thinking that all of my obsession with differentiating OCD and ATD seems a little too far-fetched right. Some of you might even think that this could be a symptom of OCD as well. 🙂

It could be… 🙁 it could be not… 😈

Probably I have greater “attention to details” to be able to distinguish OC from normal behavior.

Until or unless this behavior starts to seriously interfere with my work and relationships, I would definitely not get worked up on this (and neither should You) 🙂

Patterns patterns on the Wall, which is the Coolest of them All

The Observer Pattern.

Its easily the coolest and most practical pattern I have ever used and since I am big fan of DRY (Don’t Repeat Yourself), I will redirect you to an article which I recently wrote on CodeProject about the Observer pattern.

Implement Observer Pattern in .NET (3 techniques)

The above link has different techniques (along with source code) of implementing Observer pattern in .NET using C#.

It explains the various libraries provided by Microsoft in successive versions of .NET framework in order to implement the Observer Pattern.

The Observer pattern a.k.a Publisher-Subscriber pattern is the one to which you can actually relate in the real world.

Hope its an interesting read.

Uploading/Downloading a file using WCF REST service in .NET 3.5

Last week I blogged about how to create a RESTful service using WCF and how it was to actually not learn anything in order to make your existing WCF service RESTful.

Converting a normal WCF service to being RESTful might be an easy task, but when it comes to streaming files over a REST call using WCF, it might get a little tricky.

Here we are going to cover just that part of our service. This article is in continuation of the last one. So, I would advice you to go through it to get some context.

So, to start of with the implementation, we’ll write the service contract code first as shown below :

[ServiceContract]
   public interface IFileUploadServ
   {
       [OperationContract]
       [WebGet(UriTemplate = "File/{fileName}/{fileExtension}")]
       Stream DownloadFile(string fileName, string fileExtension);

       [OperationContract]
       [WebInvoke(Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
       void UploadCustomFile(string fileName, Stream stream);
   }
public class FileUploadServ : IFileUploadServ
{
    public Stream DownloadFile(string fileName, string fileExtension)
    {
        string downloadFilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Extracts"), fileName + "." + fileExtension);

        //Write logic to create the file
        File.Create(downloadFilePath);

        String headerInfo = "attachment; filename=" + fileName + "." + fileExtension;
        WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;

        WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";

        return File.OpenRead(downloadFilePath);
    }

    public void UploadFile(string fileName, Stream stream)
    {
        string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), fileName);

        int length = 0;
        using (FileStream writer = new FileStream(FilePath, FileMode.Create))
        {
            int readCount;
            var buffer = new byte[8192];
            while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                writer.Write(buffer, 0, readCount);
                length += readCount;
            }
        }
    }

A few things to note from the above piece of code :

  1. For File download scenarios, we need are using the WebGet attribute, indicating that it is indeed a get Call for a file on the server.
  2. Also, in file download, we need to add some header info like Content-disposition and Content-Type to the outgoing response in order for the consuming client to understand the file.
  3. For File upload scenarios, we are using WebInvoke with POST method
  4. We need to make sure that the location in which we are writing the file to (“FilServer/Uploads”), is write enabled for the IIS app pool process.

Apart from the above piece of code, the web.config entries need to be as below (we need to specify reader quotas and message sizes in order to allow for larger files to stream over):

<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="MyWcfRestService.WebHttp" maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647"
                 transferMode="Streamed"
                 sendTimeout="00:05:00">
          <readerQuotas  maxDepth="2147483647"
                         maxStringContentLength="2147483647"
                         maxArrayLength="2147483647"
                         maxBytesPerRead="2147483647"
                         maxNameTableCharCount="2147483647"/>
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
        <service behaviorConfiguration="MyWcfRestService.FileUploadServBehavior" name="MyWcfRestService.FileUploadServ">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="MyWcfRestService.WebHttp" contract="MyWcfRestService.IFileUploadServ">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="MyWcfRestService.FileUploadServBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Now, there is one small problem (gotcha), when we try to write the same code in .NET 3.5

The problem happens when we try to debug our WCF code (i.e. press F5) and open up the FileUploadServ.svc URL in our browser. We are greeted with the below page :

The error on the page says :

For request in operation UploadFile to be a stream the operation must have a single parameter whose type is Stream.

The above message occurs only when we create the service in .NET 3.5. For .NET 4.0 its not a problem.

The good news is that its just a Red-herring and could be thought of as false warning. This I say because if we hit our service from a consuming client, it would run just fine. Its just that when we activate our service, it does not work.

The bottom line is that we can easily ignore this error.

Now, onto writing the JavaScript code to consume the service. Its pretty straightforward if you ask me.

 <div>
            <input type="file" id="fileUpload" value="" />
            <br />
            <br />
            <button id="btnUpload" onclick="UploadFile()">
                Upload</button>
        </div>
        <button id="btnDownload" onclick="DownloadFile()">
            Download</button>
function UploadFile() {
            // grab your file object from a file input

            fileData = document.getElementById("fileUpload").files[0];
            var data = new FormData();

            $.ajax({
                url: 'http://localhost:15849/FileUploadServ.svc/UploadFile?fileName=' + fileData.name,
                type: 'POST',
                data: fileData,
                cache: false,
                dataType: 'json',
                processData: false, // Don't process the files
                contentType: "application/octet-stream", // Set content type to false as jQuery will tell the server its a query string request
                success: function (data) {
                    alert('successful..');
                },
                error: function (data) {
                    alert('Some error Occurred!');
                }
            });

        }

        function DownloadFile() {

            window.location("http://localhost:15849/FileUploadServ.svc/File/Custom/xls");

        }

That’s it. You’re Done. We have successfully implemented a WCF RESTful File Upload/Download service in .NET 3.5 (and higher)

Also, I’ve attached by complete project demonstrating WCF RESTful service here.

 

Please do provide your valuable feedback in the comments below and let me know if you face any issues while implementing the service/.

Creating and consuming a RESTful service using WCF and JavaScript

REST !! REST !! REST !!

It’s the buzz word recently with the advent of mobile revolution. You know what’s more worse than not having heard about a Buzz word!! Its having heard about it, but having no idea of its implications or practical implementation.

Sometime back I blogged about how easy Microsoft has made it to create a RESTful web service using ASP.NET WebApi.

But what about people who are stuck with .NET 3.5 or just are unwilling to skill up from what they have learned in WCF due to sheer inertia. Well, I have discovered recently that it has always been possible to create RESTful web service using WCF. I stumbled upon the need to create a RESTful service in WCF because I had to use .Net 3.5, so I wasn’t possible to use ASP.NET WebApi. And I’m glad that I did. J

I discovered that creating a RESTful service in WCF is not that different from creating a normal WCF service. Of course the only problem I have with WCF is that its just too much abstracted from the inner workings of a RESTful service or how the Web works in general. This can actually cause quite a bit of a discomfort in the event that we get stuck at a technical challenge and we are unable to figure out what it happening because we have no idea what is happening underneath the layers of WCF.

So, if we want to make a WCF service RESTful, these are the below things which need to be addressed:

  1. Decorate our operation contracts with a WebInvoke or a WebGet attribute.
  2. Use webHttpBinding in our config file (since it has to respond to Http verbs)

That’s it. Voila!! So let’s get started :

Consider the below Service Contract Interface of a service which we are creating:

[ServiceContract]
public interface IRestServ
{

[OperationContract]

[WebInvoke(Method = “GET”, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = “json/names”)]

List<string> GetNames();

 

[OperationContract]

[WebInvoke(Method = “GET”, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = “json/names/{lastname}”)]
List<string> GetNamesByLastName(string lastname);


[OperationContract]

[WebInvoke(Method = “POST”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = “json/save”)]
bool SaveNames(List<string> lstRecords);

}

A few thing to notice in the above piece of code:

  1. WebInvoke attribute is actually something which indicates that the service can be invoked from a client side script such as JavaScript
  2. The Method parameter indicates which Http verb will the operation respond to
  3. The Response format defines the format of the response which the operation will return (It could be Json as well as Xml)
  4. The BodyStyle indicates whether the parameters sent to and from the client side will be wrapped in the request or written directly to the body (Wrapped or Bare). There a couple of more options which you could try out here.
  5. The Uril template actually defines the format of URL string which needs to be invoked from client side

The corresponding service code would be as below :

public class RestServ : IRestServ

{
public List<string> GetNames()

{
List<string> lst = new
List<string>() { “Ram Kumar”, “Shyam Kumar”, “Laxman Prasad”, “Ram Prasad” };

return lst;

}


public List<string> GetNamesByLastName(string lastname)

{
List<string> lst = new
List<string>() { “Ram Kumar”, “Shyam Kumar”, “Laxman Prasad”, “Ram Prasad” };

return lst.Where(n=>n.Contains(lastname)).ToList();

}


public bool SaveNames(List<string> lstRecords)

{
//Save the list of names somewhere

return true;

}

}

 

Now, we just need to make a few changes to our web.config in terms of defining the binding for our WCF service.

<system.serviceModel>

<bindings>

<webHttpBinding>

<binding
name=MyWcfRestService.WebHttp
maxBufferSize=2147483647

maxBufferPoolSize=2147483647

maxReceivedMessageSize=2147483647

transferMode=Streamed

sendTimeout=00:05:00>

<readerQuotas
maxDepth=2147483647

maxStringContentLength=2147483647

maxArrayLength=2147483647

maxBytesPerRead=2147483647

maxNameTableCharCount=2147483647/>

<security
mode=None />

</binding>

</webHttpBinding>

</bindings>

<services>

<service
behaviorConfiguration=MyWcfRestService.RestServBehavior
name=MyWcfRestService.RestServ>

<endpoint
address=“”
behaviorConfiguration=web
binding=webHttpBinding
bindingConfiguration=MyWcfRestService.WebHttp
contract=MyWcfRestService.IRestServ>

<identity>

<dns
value=localhost />

</identity>

</endpoint>

<endpoint
address=mex
binding=mexHttpBinding
contract=IMetadataExchange />

</service>

</services>

<behaviors>

<endpointBehaviors>

<behavior
name=web>

<webHttp />

</behavior>

</endpointBehaviors>

<serviceBehaviors>

<behavior
name=MyWcfRestService.RestServBehavior>

<serviceMetadata
httpGetEnabled=true />

<serviceDebug
includeExceptionDetailInFaults=true />

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

 

A few things to note from the above:

  1. We are using the webHttpBinding and have defined some message sizes (optional)
  2. We have specified an endpoint behaviour which use webHttp for communication

Rest all should be self-explanatory I hope.

 

Now, onto the second part of the post. Consuming the service from JavaScript. Its pretty straightforward actually.

<script
type=”text/javascript”>

var AllPeople;

function GetNames() {

$.getJSON(“http://localhost:15849/RestServ.svc/json/names”)

.done(function (data) {

// On success, ‘data’ contains a list of names.

AllPeople = data;
for (var i = 0; i < AllPeople.length; i++) {

};

});

}

 


function GetNamesByLastName(lastName) {

$.getJSON(“http://localhost:15849/RestServ.svc/json/names?lastname=” + lastName)

.done(function (data) {
// On success, ‘data’ contains a list of names.

AllPeople = data;
for (var i = 0; i < AllPeople.length; i++) {

};

});

}

 


function SaveNames() {

var names = new Array();

names[0] = “Chinmoy”;

names[1] = “Chandan”;

$.ajax({

url: “http://localhost:15849/RestServ.svc/json/save”,

type: ‘POST’,

dataType: ‘json’,

data: JSON.stringify(names),

contentType: “application/json;charset=utf-8”,

success: function (data) {

alert(‘Data Succesfully saved in DB’);

},

error: function () {

alert(‘Data could not be saved in DB. Please Try again.’);

}

});

}

</script>

 

The code above should be self-explanatory. What it is doing is simply making REST calls to our WCF services operations.

And that’s all we need to do to make it work. You can download the project from here.

There are few other things which become a challenge when we implement them in WCF Rest service (like uploading and downloading a file). I’ll be covering this as well as a few gotchas (.net 3.5 specific) in a future post.

Hope the explanation has been simple enough. If you happen to find any issues while implementing the same, shout out in the comments below.

There’s no use sitting on Bench if you are not ready to PLAY

There’s no use sitting on Bench if you are NOT ready to play, Right!!

I’m not sure who originally said that BUT I remember it from the movie Constantine (Remember, Chas Kramer – John Constantine’s sidekick)

I’m sure many of you might have heard this quote in one form or the other, BUT very few might have actually thought about how it could change the way we feel about our work, career or Life.

This line of thought holds good for a lot of scenarios in life.
Be it education, profession, sports. Just about anything and everything.

You know how back in school there were kids who used to pull up their socks just before exams (I was one of those kids. 🙂 :()
Kids like ME then slogged all night to get done with the syllabus.
And there were kids who used to study all year round, and not just during exams. It might have not made much a difference back then (I have years of anecdotal proof that I used to KILL it with my 11th hour preps ;)), but in the real world it does make a difference if you are not “Match Fit” or “Ready to PLAY” at all times.

Take for instance sports. Not all of the players keep on playing all the time. Also, new players who get an opportunity to play usually don’t get much time to prove their worth now-a-days. You have to be match fit at all times.
If all you do is wait for your chance to play and seldom practice, are you really gonna perform as good as you would have if you’d have diligently practiced all along. NO.

The idea is not to start working only when you see an opportunity coming along, but instead, work in a way that you create that opportunity for yourself.

Its quite similar to the Law Of Attraction. If you really want something and you channel all your energies towards it, it’ll eventually come to you.

You need not work directly towards achieving it but instead try to find and perfect the means and tools required to reach that goal.

Like famously quoted by Baba Ranchhoddas chhanchad in 3 Idiots (subtitled in English) :

Do not strive to be successful. Strive to achieve excellence instead, success WILL come looking for you. (Success ke peeche matt bhago, Excellence ka peecha karo, success jhakk marr ke peeche aayegi)

I could come up with numerous analogies to emphasize the importance of practicing and perfecting one’s skill so that you are ready when your Day/moment of reckoning cometh. But I would like to put out my views in the context of the software industry (after all I am a Software Developer)

I believe most of the readers of this blog (I know there aren’t many, lets just humour me. ;)) would be salaried employees.
Not all of us are lucky enough to be working on projects all year round. Also, not always are the projects we work on engaging enough in terms of learning or career progression.

Just remember one thing always, at the end of the day you are working only and only for yourself and not for your employer.

What you deliver and learn while you are working on a project helps your employer indeed. BUT what it really does is that it adds up to your Skillset and that’s what will help you in achieving what you want (success, money, better job, you name it).

So why should it be any different when you are not working on a project? Why should it be any different if you are on “Bench”?
It should NOT be. Remember how you should be “match fit” at all times if you wanna perform when opportunity knocks.
Moreover if you keep on enhancing your skills all along, you’ll be able to achieve that one target (success, fame, money) YOU have set out for (not the targets set for you by your employer).

It may sound a lot to do for some LazzyAss people (me included), BUT if you really know what you want to do or what you like to do, you should dive into it and start getting involved.

Just to get you guys started, I’ll suggest some ideas when you have time to spare(don’t panic.. :P)

  1. Try to really understand what you have learnt till now. The best way to put your understanding of a subject to test is by teaching it to someone else.
  2. Think up “problem statements” yourself and try implemeting them in code.
  3. Get up to speed with the latest in programming. It pushes you to learn at a accelerated pace, since the pace at which programming is evolving is mind-blowing.
  4. Create pet projects in your organization which help you or your team in getting more productive
  5. Most importantly follow the rule (Read/Learn)->Practice->(Teach/Discuss/Blog).
  6. Energize and engage people around to do the same (Discuss & share)

There are times when you aspire to be like someone (role model), but there are times when you need to inspire people around you.

<Aspire to Inspire>
Aspire to be someone who can inspire people to be like yourself.
</Aspire to Inspire>

I hope I got the point through to all my friends and readers of this blog.
The idea is simple.

If you really like to play, then PRACTICE.

Programmatically make(fake ;)) HTTP Requests using WebRequest, WebResponse and WebClient

Its without a doubt that Microsoft .NET provides us with wonderful APIs to interact with a variety of interfaces/entities.
One such API/library exists in the System.Net namespace. WebRequest and WebResponse are two such libraries which help us in programatically making HTTP Requests and analyse the Responses in the code itself.

Its actually pretty straightforweard making GET and POST Requests and analysing the corresponding responses from C# code.

I’ll try to discuss the most common methods to accomplish the same.

HTTP GET Request

An HTTP Get Request is simple to make using WebRequest class. An example of one of the requests is as under :

public static string HttpGet(string URI)

{

System.Net.WebRequest req = System.Net.WebRequest.Create(URI);

//req.Proxy = new System.Net.WebProxy(ProxyString, true); //true means no proxy

System.Net.WebResponse resp = req.GetResponse();

System.IO.StreamReadersr = new System.IO.StreamReader(resp.GetResponseStream());

return sr.ReadToEnd().Trim();

}

Just passing the URL for the HTTP Request returns the response in string format. Ok, that was simple; now lets make an HTTP Post call from c#.

HTTP POST Request

Making and HTTPPost request is pretty straight forward, if you know what an “HTTP Post” is. An HTTP Post is basically any request which posts some form data (aggregated from User input).

Usually this form data is sent as a concatenated string of name=value& pairs.

Apart from the Form Data which is sent as part of the HTTP request body, there are other parameters as well which make up a POST request, such as cookies and HTTP header data.

The components which make an HTTP request can be easily identified using tools such as Fiddler. In case you don’t know, fiddler is a web debugging software which can be used to intercept and analyze HTTP traffic originating from our system.

I’ll cover a few details on how to use Fiddler in the last section of this Post. But I guess the below function would hold you in good stead to get you started.

public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
  //req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we’re doing a POST

req.ContentType = “application/x-www-form-urlencoded”;
req.Method = “POST“;
//req.Timeout = 200000;

/*This is optional*/

(req as HttpWebRequest).Referer = @”https://someURL/”;
(req as HttpWebRequest).UserAgent = @”Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36″;
(req as HttpWebRequest).Headers.Add(“Origin”, @”https://someURL/”);

/*This is optional*/

//We need to count how many bytes we’re sending. Post’ed Faked Forms should be name=value&
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
System.Net.WebResponse resp;
resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}

Download File Request

Sometimes we might just want to download a file from a URL. This usually a simple GET request and involves use of another function of the library System.Net. Below is a simple implementation of the same.

WebClientclient = new WebClient();

client.DownloadFile(URL, Path.Combine(“<directory Path>”, “FileName.<extension>”));

The above is a very simple implementation of a file download scenario. We can also make an asynchronous file download request using the above method, which might be a more practical scenario.

HTTP Response Analysis

Fiddler is an excellent utility for analysis HTTP traffic originating from your system. As I have always been saying, its always a good idea to get under the layer of abstraction MS has blinded us with and actually be able to see how the “web” works. You’ll be able to fully exploit the libraries provided by MS in System,Net only if you have a clear understanding of the HTTP traffic.

I’ll try to introduce (strictly for newbies :P) you to a very handy tool (fiddler) for accomplishing the same. (I know it may sound like Hand-holding to some, BUT hey, who doesn’t need it every now and then.)

First, download and install Fiddler from the link Fiddler

Open up Fiddler. You’ll be presented with a screen as below :

B1

The Left pane is where you’ll be able to see the overview all the HTTP Traffic. The Right pane shows the details.

Lets, open up http://chinmoymohanty.com on our browser. On inspecting in Fiddler, you’ll find the below output.

B2

The Left pane shows all the HTTP Requests which might have been made when we hit the website URL. Clicking on one of the rows brings out the Request (top-right pane) and Response (bottom-right pane). Clicking on the “Raw” tab would show the actual HTTP Request/Response (You might need to decode the response if it was encoded; don’t worry fiddler will alert you about that).

B3

As is quite easy to understand here, using data from the Fiddler analysis, you could easily construct/fake and HTTP Post/Get call.Beware, in some cases the server might be expecting encoded data, so it might not work in some rare scenarios.

Hope, this post was informative enough and would provide the needed kick for beginner programmers to code/automate HTP calls.

Please shout your views in the comments section.

Strongly Typed JavaScript (TypeScript)–No excuse now for not diving deep into JavaScript!!

The mainstay of .NET or for that matter, C# has been its strong type checking which we get at compile time. Its so much a part of C#, that we somewhat take it for granted. If we remove Type checking in C#/VS, we’ll be severely handicapped for sure. Type checking and Intellisense  are the 2 most loved features in .NET/Visual Studio without which we (.NET developers) cannot live without.

JavaScript has been around for ages, but only in the past 3-4 years has it gained real traction as an application programming language to reckon with. Before this JavaScript was just considered a scripting language to do minor UI stuff in HTML. Many of you might know that JavaScript is actually an (almost) Object Oriented Language, BUT coding in JavaScript has always been difficult for people who are accustomed to write server code in C# or even Java. Reason being the syntax for doing even simple things like creating classes and interfaces are way different from what we have learnt in C#. It has a steep learning curve. Also, another undoing for JavaScript has been that there weren’t many Dev tools around which could bring in comprehensive Type checking to JavaScript.

This is where TypeScript comes in. I know how I keep on complaining that MS is making life easy for developers by abstracting the intricacies of technology and how at the same time it is making beginner programmers oblivious to the “real” way things work in the WEB. And TypeScript is another shot at the same thing by MS. TypeScript may abstract developers from the actual JavaScript syntax, but it’ll encourage developers to code more in JavaScript, which will in turn result in more beautiful and responsive designs.

TypeScript is an MS open source project. I know to some people it may sound like an Oxymoron (MS and Open source !! Surprised smile), BUT that’s how the Ship is being steered recently at MS.

There have been a lot of open source projects MS has published (like Entity Framework, ASP.NET MVC etc) recently, so it is something people should get used to.

So, what is TypeScript?

TypeScript is a Superset of JavaScript actually, which eventually compiles to JavaScript, BUT the syntax for TypeScript is more along the lines of other OO Launguages like C#. Moreover, any JavaScript code is a valid TypeScript code. Also TypeScript brings along with it Intellisense and (good enough) type checking during Development time.

How do I use TypeScript?

You could just download and install the TypeScript Plugin for VS 2012 from Microsoft and you can straight away start using TypeScript. TypeScript files are files with extension .ts, and they can be compiled to JavaScript (.js) files simply by calling the TypeScript compiler(tsc.exe) from command prompt.

Enough of Gyan, its time for some quick examples to showcase why every JavaScript application developer should use TypeScript. I’ll demonstrate this with a very simple example. Say we need to declare and use a class in JavaScript.

The code we’ll need to right in JavaScript would look like this :

var Person = (function () {
function Person(Name, Age) {
this.Name = Name;
this.Age = Age;
}
Person.prototype.SayHi = function () {
returnHello, ” + this.Name;
};
return Person;
})();

var person = new Person(“Sam”, 28);

console.log(person.SayHi());

As can be seen from the above code, its not exactly how a C# programmer would go about creating and using classes.

If we right the same code in TypeScript, it would look some thing like below:

class Person {
Name: string;
Age : number;
constructor(Name: string, Age:number) {
this.Name = Name;
this.Age = Age;
}

SayHi() {
returnHello, ” + this.Name;
}
}

var person = new Person(“Sam“,28)

console.log(person.SayHi())

The above code when compiled using tsc.exe produces a JS file which has the exact code written previously.

Moreover, you also get Intellisense as well as Type Checking(familiar territory Smile) in Visual Studio while using TypeScript :

image

Where can I quickly learn TypeScript?

http://www.typescriptlang.org/ is your GOTO site for anything related to TypeScript. It features some quick demos and a nice video tutorial for you to get started with TypeScript. It also has a detailed Language Specifications which is surprisingly very user friendly.

Also the website has a very cool Playground where you can try out some examples using TypeScript and it’ll generate the JavaScript side-by-side.

I would say no programming language(like JavaScript) is difficult to learn if the tools provided are good enough. Of course, you’ll have to be aware of the tools (like TypeScript) available at hand to accomplish the same.

If you have any further queries regarding using TypeScript, please give me a shout in the comments section.

JavaScript does NOT support Method Overloading–Thats true!!

A few weeks back I blogged about how “surprisingly” WCF Operation Contracts do not support Method overloading, due to the way the Web is designed.

It may come as a surprise to a lot of folks that even JavaScript does NOT support method overloading in the strictest sense.

For people from C# and Java background, who have just started coding in JavaScript, and are getting a hang of it, they may run into one particular issue while coding in JavaScript.

Problem –> A common error/mistake almost everyone does (i.e. if the developer is keen enough to dive deep into JavaScript) is explained below.

The example has 2 JavaScript functions defined in a JS file as below. They have the same name, BUT different no. of arguments(your typical method overloading)

function funcA(a,b) {
return a + b;
}

function funcA(c) {
return c;
}

Now, if we make the calls below, the outputs are as shown below:

funcA(2); –> Output is ‘2’

funcA(3,4); –> Output is ‘3’ (and NOT ‘7’ !!)

So, WTH did just happen!!

The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.

In our case the only function available is funcA(c). So even if we think we are making a call to funcA(a,b), its actually calling funcA(c).

So, even when we make a call as funcA(3,4), Why doesn’t it throw an exception if there are mismatching number of arguments??

This is where there is another JavaScript feature, which a lot beginners miss out on. In any JavaScript method, the arguments passed into the method are accessible via an Object array with the name args[].

So in our case even if we define a JavaScript method as funcA(), we can still make a call to it as :

funcA(2)

funcA(2,3)

funcA(2, “hello”, 4, 5)

All of the above are valid and the parameters can be accessed by Index in the args[] array, available inside the method.

This is the reason JavaScript does not throw an exception; if you pass 2 parameters in a JavaScript function accepting only 1, it’ll just consider the first of the 2 parameters.

Solution –> The easiest solution that can be applied here is that we have a parent function with the same name accepting any number of arguments. Inside this function we inspect the incoming arguments (type, number, order etc) and call the appropriate child methods based on that (see below for a very simple and trivial example).

function funcA() {
if (arguments.length==1) {

return funcOne(arguments[0]);

}else if (arguments.length==2){

return funcTwo(arguments[0],  arguments[1]);

}}

function funcTwo(a,b) {
return a + b;
}

function funcOne(c) {
return c;
}

The solution suggested above may sound easy to implement, if you are dealing with basic types(integer, string,array) and are planning on overloading only a handful of functions. BUT, if your overloading requirements are complicated, you may have to put in a lot of effort and code.

There are a few efficient ways to overload in JavaScript out there, which I may discuss in a future post.

We may be used to comprehensive & extensive method overloading in common Object Oriented Languages like C# and Java, BUT JavaScript is different.

Although JavaScript can be said to be an Object Oriented language, BUT its not a class based language as C# and Java. What it means is that apart from common types like Number, String and Arrays, every other Type in JavaScript is simply of type Object.

So, even if we intend to somehow implement and use method overloading in JavaScript, it’ll be limited as compared to other OO languages.

If any of you people have any suggestions on an ideal and reliable Overloading solution in JavaScript, you are welcome to provide them in the comments.

Consuming and Deploying ASP.NET WebApi Services – Gotchas!!

Last week I posted about how every web programmer should know about the RESTful nature of Web and start using Asp.NET MVC 4 Web Api to accomplish the same. The post was accompanied by a sample HTTP GET resource call to an ASP.NET Web Api controller action.

So, I believe you people have already started using WebApi; If not then this post may still help you as and when you start.

This post focuses on some of the issues I have encountered while developing using ASP.NET WebApi and the solutions to get around those issues.

Gotcha 1 –> PUT and DELETE request won’t work on IE10

This one caused quite a pain when I started using WebApi and discovered that PUT and DELETE request don’t work in IE10 (specifically in Windows 8 64-bit). I am not sure why it doesn’t work in the latest and greatest version of Internet Explorer, BUT that’s how it is. There is a workaround for this issue. We can add this tag inside the <head> tag of our Web page to make IE10 work like IE9.

<meta http-equiv=”X-UA-Compatiblecontent=”IE=EmulateIE9” >

You could add it to all your pages or on just the pages which make PUT or DELETE requests, your call. BUT it is something to keep in mind while developing with ASP.NET WebApi until MS comes up with a fix for this.

Gotcha 2 –> PUT and DELETE requests do NOT work once the application is deployed in IIS

When you start working with WebApi you’ll realize its awesome, very easy and all his honky dory as long as you are developing in VS and debugging your solution. BUT, once you deploy your WebApi application in IIS you run into problems and some if your WebApi calls do not work. Don’t be surprised as this is quite a common issue as IIS is by default not configured to serve PUT/DELETE requests.

    • Configuring IIS 7.5 for WebApi

         Sometimes the WebDav module installed in IIS 7/7.5 causes issues when a WebApi application is deployed in IIS. Not sure what the reason is, BUT the solution that worked for me was removing the WebDav module for my application. This is made possible by adding the below tag in your web.config file, which instructs IIS to not register the WebDav module for our application. The below tags have to be included inside the <system.webServer> tag in the application’s web.config.

<modules runAllManagedModulesForAllRequests=”true“>
<remove name=”WebDAVModule” />
</modules>
<handlers>
<remove name=”WebDAV” />
</handlers>

    • Configuring IIS 6 for WebApi

This one is a little tricky and has no proper explanation as to why it works. BUT we need to configure IIS6 for WebApi for our application to work consistently. The workaround has been sourced from Phil Haack’s post about using ASP.NET MVC on IIS 6. The post itself is very informative, BUT the part which we are interested in is at the bottom. So, I’m gonna put it out here for you guys :

  • Right click on your deployed application and select properties
  • In the properties windows, click Configuration to open the “Application Configuration” window.

application mappings

  • Get the path to the aspnet_isapi dll using the below method.

One easy way to find out is to find the .aspx extension in the list and double click it to bring up the mapping dialog.

extension mapping

Now you can copy the path in the Executable text box to your clipboard.

  • Now, onto the previous “Application Configuration” window. In the Wildcard application maps section, click the Insert… button.
  • This brings up the wildcard application mapping dialog. Enter the path to the aspnet_isapi.dll copied in the previous step.

wildcard extension mapping

Don’t forget to uncheck the Verify that file exists checkbox! This is one of the most common mistakes people make and can cause a headache if not done. It may cause the application to stop working completely.

So, that’s it. You should be good to go. Remember, everybody might not face these issues as their IISs might be configured correctly or they might be using the correct version of the correct browser already. BUT having knowledge about these Gotchas should come in handy.

If you have any questions or view regarding these, give me a shout in the comments section.