Thursday, April 23, 2015

Understanding the language in it's own way.

It's been a while since i posted here, I got a little free time on my hands courtesy of waiting on comments on a pull request.
A few days ago i really wanted to develop a very quick rest application. I have been writing a lot of java services of late which are consumed by rest applications. Despite my tests around it on the java level I wanted to ensure if there was a quick fire way to test it from the rest layer without going into the hassle of building a whole array of projects to test what i want.
I was evaluating a couple of options given my laziness. One was to use sinatra, second was to use the dropwizard-core library. I have been reading about the waves its generating recently also instilled further into my curiosity. I tried setting up a demo project and it seemed seamless but still decided to use Sinatra given my earlier familiarity with it.
A little intro about Sinatra its a DSL for developing web applications in Ruby with minimal effort. It's a direct quote from their github repo and my stress will be on the minimal effort. It really is that minimal if you're developing a rest application you will have to mash up the get,post, put or delete logic in one spot in a ruby file and import sinatra as dependency and when you run the ruby file you will have it running your endpoint locally. It really is that simple.
I did run into a little snag which costed me a good hour to troubleshoot though. It was my mistake combined with the super dynamic aspect of Ruby which made it harder for me to catch it which was really the point of this post.
The gist of the mistake i did was I had a collection of Strings in a constructor and then I had a collection of Objects but when i initialized the constructor in one of my workflows I was passing in a collection of Objects in place of collection of strings it was supposed to take. In Java the beauty is it would've shown me a compile error then and there but not in Ruby though where most of the conversions in my understanding happens on the runtime which is where it was freaking out saying incorrect number of arguments received.
Another major part of the problem when i thought a lot about it stemmed from the concept of me writing Ruby code like a java programmer, thats because I am still not a seasoned ruby coder. It was a really icky mistake which could've been avoided in the compile time itself but then again given the awesomeness of sinatra i was able to write an application which i used to test my workflow very very quickly.
I am also not trying to compare Ruby or Java in this post they are both awesome in their own unique way. As much as how I love java it would've taken at-least triple the time it took for me to set this project in Sinatra. This post is on the concept of trying to give me the idea of trying to understand the language in its own way rather than trying to simulate one language in terms of another.
oh well my pull request comments demand more attention now. Until next time!!

Sunday, June 23, 2013

Groovy and its awesomeness on integration tests.

I know its been really a while like a year and half long since i posted something out on this side. I finally decided to stretch my thoughts out a little.

It's been close to 2 years since i came to Kansas city and I have to say I am loving the work i am doing here everyday because the scope of picking a new stuff everyday is fantastic. The biggest hurdle i faced was migrating from Visual studio to Eclipse but everything after that was smooth. I have been messing with Groovy, Ruby, dipping my feet into clojure of late. I actually wanted to start writing about clojure today but still i think i don't have enough experience with it to post a blog on it. So i will stick to Groovy for now.

Alright so what's groovy before i delve into more finer details. let me start off with a comparison here and as to what we're comparing. I am going to compare a method in java to a method in groovy.

public static long add(final long a, final long b) {
  return a+b;
}
Simple enough to add any explanation for this method, lets look at its groovy equivalent.
def add(a,b) {
 a+b;
}
First thing which stands out is the missing return type, second there is no types for the arguments passed and third there is no return statement inside the function, Groovy is a dynamic language and supports lazy evaluation where the compiler doesn't care about the types of the arguments until the runtime also the groovy by default returns the last statement it executes on the method eliminating the need to specify a return type. Let me show some more nifty features. say if i want to create a list and set in java.

List list = new ArrayList();
list.add("A");
list.add("B");
Set set = new HashSet();
set.add("A");
set.add("B");
Well with guava this can be reduced to simply these.
List list = Lists.newArrayList();
list.add("A");
list.add("B");
Set set = Sets.newHashSet();
set.add("A");
set.add("B");
With Groovy it's this simple
def list = ["A","B"]
def set = ["A","B"] as Set
I felt this was much more lucid and simple and in my integration test which is usually a lot of logic for initializing variables, helper classes, wrappers around making the calls the groovy notation reduced the number of lines of code by more than 30%. The best part was the improving the readability of the code because of the advanced workflows covering multiple scenarios. for example lets take this scenario for a method signature in both java and groovy.

public static BigInteger computeAreaOfTriangle(final long side1, 
final long side2, final long side3) {
//TODO logic to compute area using side1, side2, side3
return BigInteger.valueOf(area);
}
when this method is actually called it looks like this.
final BigInteger area = computeAreaOfTriangle(10,20,30);
Although Groovy it supports the concept of named arguments which makes it look like this.
def area = computeAreaOfTriangle(side1:10,side2:20,side3:30);
Although it looks like there is more space to represent in this notation than in the Java way but the readability it provides is much elegant and more easy to troubleshoot as well because we clearly know which argument is mapped to which parameter. That being said Groovy also did have its own pitfalls, one of them being the aspect Groovy gobbled up all the exceptions and it was very difficult to get the stacktrace of an issue as to why its actually failing. I will list this incident which actually drove me a little crazy for 20 minutes to get to the bottom of actually quite a simple issue.

//Once again blogger choking on tags for a map of Strings 
//keyed by longs.
ImmutableMap.of(1,"A",2,"B",3,"C",4,"D",5,"E",6,"F");
I used guava to create an ImmutableMap which is map of strings keyed by long values. If you were to do the step above in java, compiler would mark an Red X and complain that you can't use pass more than 5 arguments (keys and values) to the method of() it will says its an invalid argument and ask you to use the ImmutableMap.Builder for more than 5 arguments. 

 If I were to tell you on maven goals perspective. If you do maven clean verify on that code i have it will give you a compilation error immediately but with Groovy since its dynamic it was compiling the code but when it was doing the test phase it was throwing that error in the runtime and marked the test as failed on the unit test phase which confused the hell out of me until i looked at the guava javadocs for that method. 

On the overall aspect i love using Groovy and i am using that in favor of jBehave frameworks i used for integration testing previously and its making the test more sleeker in my perspective. I am also playing around a lot with Ruby and clojure as well. Hopefully by the next time i post i can make some strides onto that. (It won't be a year and half)

 Until Next time!!

Friday, February 10, 2012

Finally Awake

It's been a long time since i made a posting out here, Well it was the winter and I was hibernating you might say. Well I actually was transitioning a whole lot in these past 6 months or so. I can't believe how quickly time flies. To my surprise in my LinkedIn profile I found that I am in my new job for about 6 months now. 

I have been busy though finally I have mustered enough courage to say I can write unit tests pretty well and most important of all I made the choice to transition from C# to Java. As surprising its for people who might read it here and it was something which i thought about carefully before i chose the move. It really came at a time when i was LINQing my way to glory. 

One of the prime reasons being the team i wanted to be part of when I took the offer. (Also more on the effect of interviewers who interviewed me on that very day). When i got the offer my recruiter told me clearly I would be working on services development for iPad and Android. Oh Yes! So you know the reason of my big switch from all these years of C#. I don't miss it though for I am stackoverflow just about everyday and I keep my tabs on those two. Ironically the options I had to choose from were very difficult and other offer which I gave up was services development on .Net 4.0. Both shared the traits of being major healthcare providers here in US. Well I have a more sense of fulfillment right now that my work would impact a whole lot of people directly. 

So that's the story of how I became a Java developer. Transition from Visual studio to Eclipse wasn't that hard because of grad school experience with Java. But Eclipse is not Visual studio because of its glitches but serves the purpose of being an IDE very clearly. I certainly picked up a bunch of key attributes in this hibernation phase to write nifty little unit tests. I didn't realize how much powerful they were primarily because in all my previous companies they had an extensive testing team to backup the developers for testing but in here every developer has to be their own tester which includes unit tests initially followed by Integration tests which are black box tests.

I have written a demo restful web service (which I would post here next time definitely. I promise :D) which I thought could be very useful for anyone to pick it up easily. For I was writing a bit of those when i started out now I am working on a rather different but exciting story for the moment right now. I finally have sometime on my hands to update my blog which seemed to be getting some attention recently. 

Plus next time would be my recent exploits on Kindle Fire and as fate would've it I ended up with 2 iPads as well. One was given to me at my work for testing out the services. Any takers for my old iPad?

Until Next time!!

PS: Yawns... Finally out of slumber well and truly


Wednesday, October 5, 2011

Duh...iPhone 4s


After the amazing set of releases by Amazon over the course of last week where in I was keeping my fingers crossed for Apple to make its next move. In a way felt let down after the much hyped iPhone 4s announcement despite the fact I knew that there won't be much to expect in that announcement.

It's more than a matter of choice for me currently I am going to jump into the Bandwagon eventually will be ruing this decision here when iPhone 5 is going to come out. As of now I am twitching to order the iPhone 4s because of my lack of a smart device for that matter.

Amazon is the big winner in the week of announcements by throwing in a bunch of marvelous items during the last week press release. Gadget of the month will be iPhone 4s for me.

It's less than 2 weeks for the release of Arkham city and finally D day is heading closer

Wednesday, September 28, 2011

Rubbing the salt

This one is going to stand on a sad note rather than a tech note. First up is the Mango update which started rolling out when my phone broke couple of days before and it's weighing heavily on my mind.

Second one is the announcement by Jeff Bezos. Everyone kinda knew about Kindle Fire the tablet they were about to release but the surprise factor happened to be the new kindle. Oh boy they took me by surprise. I was looking in depth with the functionalities which each of them are having. So as I could get guess from the names. Anyone interested would find the detailed specs when you visit Amazon's home page today. I like the Kindle touch by the looks of it I am waiting to see the hands on video to see how it looks from Engadget.

 From first impressions and an avid fan of Amazon products I am blown by the new kindle more than Fire. Touch based kindle by the price range would be a huge seller in my perspective and a big money making strategy of Amazon because I paid close to 200 bucks on my old Kindle along with the Smart cover and stuff now that I reflect on it I could get 2 Kindle Touch's right now.

 Well now you know what rubbing a salt feels like. I am looking for any takers for my Veronica. Another smart move I admire is their placement before Apple's big announcement. Ball is your court apple let's see what you come up with. Until next week or I until I find more info on Kindle touch. Cheers!

Monday, September 26, 2011

RIIP Macho Phone!

Yesterday was one of the really worst days which I faced in these past 2 months. Just when i was waiting so eagerly to get hooked up to a Mango update. My Windows Phone died on me, apparently due to the failure of the LCD screen. I didn't think I needed the insurance with that phone primarily because of the fact that I never had a problem with any of the phones I had in a long time. I did realize that with ATT it's much better to have an insurance policy even though if the cost of the product is very cheap.

I loved my Windows Phone. These are the contingency plans I came up with, Order a Samsung Focus from Amazon.com and weather the storm. Something cool crossed my mind which would work out perfectly if it goes well. I wanted to get an iPhone 4 yesterday because I didn't want to be deprived off a smart phone but i realized I could get something better which would be the iPhone 5 which is due to come out soon. Well that would definitely make my phone rather distinctive. I consider this as the heavenly sign primarily because my love for apple products has increased exponentially after the usage of my iPad.

I hope to repair my Windows Phone and solely use it as my crash device for testing my applications. All in all I was able to avert the major damage which I would've faced yesterday.

On a side note. After all the travel in the past 2 months I have finally settled down and I am really raring to start with my new team in my company. Apparently I will be getting to play with a lot of smart devices. I simply can't wait. 

I got a request via email to reveal about the naming conventions I used for my gadgets. Well I have this obsession of naming my device after a girl (based on literary references and some of my favorite names) . My iPods were Megan & Cilla. My Kindle is Veronica. My 360 is an Agnes. I still haven't christened my iPad cause I am finding to choose between 2 very beautiful names. By the looks of it I should create a list of new names.  I should probably post it on my Personal blog too but I think this blog makes it a suitable avenue to divulge it.

As for things I am looking forward too, Arkham city is hardly 3 weeks away i can't wait to get my hands on the Collector's Edition

More next time...


Wednesday, August 3, 2011

Food for thought

I had this question on an interview where I was asked to solve this problem on C#. Reverse a string :) well my eyes were gleaming when i heard the question, best part being asking me to do it in all possible ways I could think off to answer it immediately. I was happy with the number of answers I could do it in that short tenure of time but  I realized how knowing a framework in detail could streamline the thought process very quickly. I am going to list my answer in this post so that someone might bump on it on the rare instance and find it useful.
class Reverse
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Input String:");
            string stringToBeReversed = Console.ReadLine();
            string reversedString = ReverseTheString(stringToBeReversed);
            Console.WriteLine("Reversed String is: " + reversedString);
            Console.ReadLine();
        }
 
        private static string ReverseTheString(string stringToBeReversed)
        {
            //Nifty one ain't it?
   char[] chArray= stringToBeReversed.ToCharArray();
   Array.Reverse(chArray);
   return new String(chArray);
  
        }
   
   private static string ReverseTheString1(string stringToBeReversed)
        {
            // interviewers love one liners don't they?? :)
   
   return(new String(stringToBeReversed.Reverse().ToArray()));
  
        }
   
   private static string ReverseTheString2(string stringToBeReversed)
   {
            //Old fashioned way how could i ever miss the one with good'ol for loop
   string sOutput = String.Empty;
   char[] chArray = stringToBeReversed.ToCharArray();
   
   for (int i = chArray.Length - 1; i > -1; i--)
   {
   sOutput += chArray[i];
   } 
   return sOutput;
   }
  
  private static string ReverseTheString3(string stringToBeReversed)
        {
            //Old fashioned way with string Builder upgrade
            StringBuilder sOutput = new StringBuilder();
            char[] chArray = stringToBeReversed.ToCharArray();

            for (int i = chArray.Length - 1; i > -1; i--)
            {
                sOutput.Append(chArray[i]);
            }
            return sOutput.ToString(); ;

        }

  
  private static string ReverseTheString4(string stringToBeReversed)
   {
         //one with recursion
   if (stringToBeReversed.Length == 1)
   return stringToBeReversed;
   else
   return stringToBeReversed[stringToBeReversed.Length - 1] + ReverseTheString4(stringToBeReversed.Substring(0, stringToBeReversed.Length - 1));
  }
  
  private static string ReverseTheString5(string stringToBeReversed)
        {
            //one with LINQ :)
            var reversedValue = stringToBeReversed.ToCharArray()
                         .Select(ch => ch.ToString())
                         .Aggregate<string>((xs, x) => x + xs);

            return reversedValue.ToString();
        }
  
   
    }

It's a real simple piece of code I posted it here since I felt the urge to write something since it's been a while I posted something on here. I am currently working on a top secret venture currently and once I form a working prototype I would definitely post it here. Hope someone finds my little post amusing.

Until Next time!!

Sunday, July 17, 2011

Epic Fail

I wanted to install Mango Tools SDK onto my laptop to start tweaking a new app I had been prototyping for quite some time now on Windows Phone 7, alas there was one major hindrance. My laptop was running Windows Vista Home Premium and for mango be installed needed a SP1. I let my windows update to download the SP1 and tried installing it which happened to be the beginning of the end.

SP1 corrupted my HDD with an error message and I was lucky to note it in the middle of the night when I saw the light on my laptop persisting than normal. I force reset it and boom windows wouldn't started. it was of no concern to me since I had the same situation umpteen times. I used safe mode now I got the prompts for the drivers being loaded and I was watching the sequence eagerly when i got the message CRC DLLs cannot be loaded then I realized what the service pack installation had gotten me into.

I realized I had no way to boot again into my current windows version and finally decided to reset my lappie to factory settings. I had my external HDD handy and manually copied all files to my Backup using DOS copy  commands. Huh took me the entire Saturday night to make a backup and I regret missing my Dev Environment currently. 

Moral of the Story: Its better to upgrade to Windows 7 rather than installing Windows Vista SP1


Friday, June 17, 2011

Halotopia

I have three posts on drafts which needs my approval, Life has been a little hard for the past few weeks needless to say! I have been following E3 Expo with some curiosity because of the rumor mills which were grinding some info about upcoming Halo 4. Rumor hills had been churning that for quite sometime at-least for the past  2 years. I was full of skepticism filled with a glimmer of slight hope.

Alas heaven gates opened this was the result.


It almost knocked me out of my chair when i saw Master Chief coming out of cryogenic sleep, I know it's going to be just one year long of wait left ahead of me. The wait has been made worth it because of another video preview which made my jaws drop in awe.



Halo Combat Evolved Anniversary Edition, Like its mentioned in the video "Campaign of the Decade" remastered so i can try it on my new Xbox :) so looking forward to playing the "Attack on the Control Tower" level when it comes out on legendary mode!

I can only pity PS3 fans who won't be getting this bonanza :) :)

Counting down for the holidays !!!


Thursday, May 19, 2011

Me Myself and Veronica :)

I took quite a long break from here after writing my last post out here, I do love writing but I had a handful to deal with in the last 2 months. Thought of making this post here today after bumping into an interesting article at Engadget. Well i was pretty amused reading about it since I am a kindle user for the past 2 months it made feel a quite elated I should say :) Oh yes Veronica is my kindle !!

If iPods were a revelation of the past decade, Kindle has ought to be the biggest revelation of this one (at least i think so)primarily in the age of tablets its good to see a dedicated reading device.(I really had a hard time when people tried to use my kindle screen as touch screen when they first used it and It's not a tablet) holding its own and this remarkable feat by amazon of taking charge of the 3G for the device shows how much the company tries to advocate the concept of reading to its customers.

It's not a review on Veronica, its just a reflection of how well thought-out concept she is. The display is astoundingly brilliant and the E-Ink display gives the feel which LCD screens can't even dream about conjuring giving the interface which perfectly emulates the perfect reading experience. Most people would complain on the fact of comparing the experience of reading from the book, Yes I do agree with them nothing like the smell of fresh paper while you're deeply engrossed into the story, but you got to look at the bigger picture say you're traveling and you feel compelled to read this particular story you cant carry your collection wherever you go.

This is where Kindle kicks in you get to store the entire library wherever you go. Anything you buy on wireless comes via 3g directly to the device. shopping for books is just a breeze. Of course people might argue I covered an inch of an argument in my previous paragraph. I don't want to start a feud primarily I am suggesting anyone who solely loves reading would love Kindle and trust me Veronica has been of awesome company to me. I love playing scrabble on Kindle when I am not reading.
Anyone who is thinking about Kindle I think they should get it without getting second thoughts cause I think its going to be one of the quintessential devices very soon :)

Love ya Veronica!!

Wednesday, April 20, 2011

Gameutopia!

Mortal Kombat & Portal 2 quite possibly one of the good combo games to play concurrently :)

Going to take my time playing these two unlike crysis 2 which i beat it in 2 days and got bored out of my mind since then.

One eye for Fatality and One eye for Science!!

PS: Next post is on my first application on Windows Phone 7...

Friday, April 1, 2011

LINQing - The Basics

Been a while since I made my promise, nevertheless despite me wanting to post something interesting. I would very much like to stick to my promise, so here it goes.

LINQ stands for Language Integrated Query is a set of features listed from Visual Studio 2008 (.Net 3.5 and above) it extends query capabilities to Language Syntax of C#. I tried explaining the architecture of LINQ to people I know at work they seemed least bit interested and judging from their experience they wanted to see it in action directly rather than wanting to know about the entire architecture so I thought of adapting the same format for this post. It will be direct hands on and anyone interested in learning the architecture can find more accurate information here

The gist of this post is to explain the concept of LINQ to XML and this will be accomplished firstly by the creation of a XML Document using LINQ to XML features followed by a simple, update and delete query. (I wanted to go into more complex Lambda expressions but most people don't like reading for a long time so another time may be ;))

First I shall start with the creation of a XML Document. The code below is written in C# (.Net 3.5) and it's Visual Studio 2008 compilable.

//Creating XML USing LINQ Statement

 XElement xelem = new XElement("GameIcons",
                      new XElement("Icon1",
                          new XElement("Name", "Gordon Freeman"),
                          new XElement("Game", "Half Life"),
                          new XElement("PrimaryWeapon", "Crowbar"),
                          new XElement("SecondaryWeapon", "GravityGun")),
                      new XElement("Icon2",
                          new XElement("Name", "Master Chief"),
                          new XElement("Game", "Halo"),
                          new XElement("PrimaryWeapon", "Assault Rifle"),
                          new XElement("SecondaryWeapon", "Melee")),
                      new XElement("Icon3",
                          new XElement("Name", "Ezio"),
                          new XElement("Game", "Assassin's creed"),
                          new XElement("PrimaryWeapon", "Hidden Blade"),
                          new XElement("SecondaryWeapon", "Sword"),
                          new XElement("Misc","Throwing Knives")));

             xelem.Save(@"C:\LINQTutorial\LINQTutorial.xml");

Can it get any simpler than this, The document is created using XElement (equivalent to the old XmlNode) and the biggest factor is the simplicity and readability it adds to the language and the same hierarchical structure you realize with the XML file structure can be realized here. Anyone having difficulty in following the steps can be clarified easily once they see the file which has been created.


  
    Gordon Freeman
    Half Life
    Crowbar
    GravityGun
  
  
    Master Chief
    Halo
    Assault Rifle
    Melee
  
  
    Ezio
    Assassin's creed
    Hidden Blade
    Sword
    Throwing Knives
  

XML with customer names and phone numbers are so boring don't you think? I Wonder if anyone ever came up with a XML file like this before, seems like Gordon Freeman (MIT Graduate as he  is) is wiling to be the first test subject. I would like to show case a simple select query to show the basics.(this should be very easy test to him than the teleportation test he takes in Half Life 2)

String sXmlValue = File.ReadAllText(@"C:\LINQTutorial\LINQTutorial.xml");
XDocument xdoc = XDocument.Parse(sXmlValue);
//Sample Select Statement
            
var nameList = from obj in xdoc.Descendants("Icon1")
               select new
               {
                name=(string) obj.Element("Name"),
                game=(string) obj.Element("Game"),
                primaryWeapon=(string) obj.Element("PrimaryWeapon"),

                };

            foreach (var varName in nameList)
            MessageBox.Show(varName.name + "\t" + varName.game + "\t" + varName.primaryWeapon);
      
The functionality is very simple, I read the contents of the XML file created previously and using the XDocument to parse the contents of the string (XDocument is equivalent to XmlDocument in terms of functionality). Now onto the query component which is the backbone the query returns the list of variable elements for the XML file with child node as Icon1 and from those I pick the individual child name elements directly based on their String value. This will display the contents of the Icon1 that is details about Gordon Freeman as formatted by MessageBox Contents(Yes including the gravity gun). I am sure the readability aspect is very lucid for this task.

Seems Master Chief wants to go next for the Update Trial. He isn't satisfied with Melee as his Secondary Weapon and he needs a Rocket Launcher. So the next LINQ Statement will fix that aspect for him.

//Simple Update Statement

IEnumerable xval = (from obj in xdoc.Descendants("Icon2")
                                         select obj).ToList();

//Giving Rocket Launcher as Secondary Weapon to Master chief
foreach (XElement xe in xval)
    xe.Element("SecondaryWeapon").SetValue("RocketLauncher");


Cool. Huh? Master Chief is very happy with his Rocket Launcher and finally Ezio seems to wonder why he has the Misc child node when Freeman and Chief doesn't have it, so I will comply to the wish of Ezio and will remove the node for him. Delete statement is even more straightforward than the update statement.

//Delete Statement
IEnumerable xval1 = (from obj in xdoc.Descendants("Icon3")
                                          select obj).ToList();

foreach (XElement xe in xval1)
      xe.Element("Misc").Remove();

Ezio takes the leap of faith gladly now that his wish is granted. It's very hard to cover the abstraction and underlying concepts of LINQ in a single post. I did my post to uncover the most basic elements and once the basic concepts strike home more complex lambda expressions are very easy to learn. Always the best place to start would the MSDN Documentation.

Once the Intricacies are uncovered. LINQ is in fact Child's play! (now you know the allusion to the gaming references)

I really enjoyed writing this post. Until Next time!


Friday, February 18, 2011

Julian Date

I was a little busy over the past week with lots of traveling, It's been a productive week for me personally and my next post would be on my experiences with LINQ to XML definitely. I got fascinated with LINQ for a long time finally my project requirements have necessitated the need to use LINQ but current post is about a nifty little feature which i made use of yesterday and i figured someone would make use of this feature in case if they were searching for it.

I am a lazy guy, laziness has always been my trademark niche and i tend to spend more time exploring the framework functionality to get the job done real quick and it's not that i am against development of custom methodologies, I am an ardent lover of custom applications. I personally like accomplishing things this way rather. :)

The requirement i faced was a minor part of my module which needed the Current time object to be Converted to the Julian date format [YYDDD] for instance today February 18 2011 can be represented as 11049 in string notation. 

11- Last 2 digits of year 2011
049 - Represents the Current Number of this day in the calendar year from 0-365 (31 days in January + 18 days currently)

It's a straightforward simple routine and It's in C#

public string RetJulianDate(DateTime dt)
        {
            DateTime dObj = dt;
            String sYear = dObj.Year.ToString();
            int month = dObj.Month;
            int day = dObj.Day;
            //Current Month difference
            int current = day;
            
            int sum = 0;
            int final = 0;
            if (month > 1)
            {
                for (int i = 1; i < month; i++)
                {
                    sum += DateTime.DaysInMonth(dObj.Year, i);
                }

                final = sum + current;

            }
            else
                final = current;
            return (sYear.Substring(1, 2) + final.ToString("000"));
        } 
 
 
 
Until Next time! 

Friday, February 4, 2011

Logging - Oh ya Log4Net

One of the most important aspects to a good application in fact one of the most pivotal components happens to be logging. If not for logging it would be very nasty to troubleshoot an issue when the application goes live onto production. Where do you start looking for problems??

There are some really awesome logging frameworks out there but I am going to focus on an Open Source logging framework which i use it with .Net viz Log4Net. It's very easy to incorporate this feature onto your application and the best part it's free. Log4net is part of Apache Logging Services project which was intended to provide cross language logging services primarily for debugging.

I think I've given enough funda for now and i am going to jump into the essentials which one needs to do to incorporate Log4net as part of their application in this post. I was actually brooding over setting up this for my application 3 months ago and when i looked up i found most of the articles i read about setting this up were not properly documented. I decided to make a post about this properly so it might help someone in the future when they read this.

Before i start developing the sample application. Log4net can be downloaded from here, You can get the latest Log4net build from this site. It contains the Log4net dll which will be referencing for the sample application i develop.

I will explain this with a simple Forms application in Visual Studio. Create a Forms application on Visual Studio and once the application is created, Add a new config file to the application namely App.config and i think the abstraction would be the scenario that application would have a config file and in case it has many modules all the modules in turn would have their App.config files seperately. Before you use log4net you need to create a configuration setting for it in App.config file. I've listed the App.config setting below


  
    

The main thing to note is the param tag by name File. This contains the destination where the log file will be created for instance in this scenario it will be created under the folder MyLogFolder with the log file name as customlog.txt. Now i will focus onto the Sample Application part and how to go about accessing the log4net from the application side. The application like i mentioned is a simple forms application with a button click event as shown in the snippet below.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using log4net.Config;

namespace Log4Net
{
    public partial class Form1 : Form
    {

        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  
        public Form1()
        {
            InitializeComponent();
            log4net.Config.XmlConfigurator.Configure();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            log.Warn("Custom Warning Message");
            log.Debug("Custom Debug Message");
            log.Info("Custom Info Message");
            log.Error("Custom Error Message");
        }


    }
}


The code snippet is very elementary. It shows the way to incorporate the log4net after adding the reference to the DLL via the application. The main thing to note would be lines 17 & 21 which are both self explanatory in nature and on the click of the button the log file would've have the following contents as shown below.

WARN 2011-02-04 12:03:07 – Custom Warning Message
DEBUG2011-02-04 12:03:07 – Custom Debug Message
INFO 2011-02-04 12:03:07 – Custom Info Message
ERROR2011-02-04 12:03:07 – Custom Error Message


Like i said it's just a skeleton and it's a very simple framework with very strong functionality embedded in it. Logging made easy!!

Jet Set Go

I had this blog created for a long time ago, the primary reason i wanted it to be the avenue to share my nerdy thought processes sometimes (Don't worry it wont be that nerdy i try to keep it really simple enough). i had this posts in drafts for over 2 months and now that I've finally decided to curb my procrastination and wanted to nail it down today.

I've been in the blogging circle for a while ever since the completion of my masters i had this fascination to start my own tech venture where i could share my new eureka moments which i get at work but deep down if i look at it intuitively the complex issues are the ones which can be solved easily but most of the time is spend on some trivial issues which we tend to overlook and most of the ventures out here would be to focus on the trivial issues and how to go about solving it :)

My normal blog would be this always but i will move some of the aspect to this part. This would be the avenue for the bigger things i plan to venture into this year hopefully. In case you were wondering about the part why i used GlumLicense as the blog post name well i started this blog as soon as i got my new 360 and Glumlicense was my Xbox Gamertag then (Just to let you know how lazy i really had been or may be it's my Xbox) right now you can always connect to me easily via my Gamertag which is machovenki.


The Stage is set. Let the Game begin!!!