WHAT'S NEW?

Tiny talk :: LINQ Funda :1

IEnumerable 


  • Is for LINQ to Objects
  • Objects that are in memory on Heap


IQueryable 


  • Is for working on LINQ to SQL
  • Inside it, it using Expressions to frame and execute sql queries.


Func<T>

  • Can return a value. The last value in the definition is the return.
Ex: 

Func<int,int> PrintNumber = x => (x);
            Console.WriteLine(PrintNumber(50));


Action<T>

  • Cannot return any value. It is only to feed and use directly

Ex:
Action PrintEmpty = () => Console.WriteLine("Hi");
            PrintEmpty();

            Action<int> PrintOneNumber = x => Console.WriteLine(x);
            PrintOneNumber(5);

Expression:

  • To be used to help the developer better understand the code.
  • It is slightly different from Func<T> and Action<T>.
  • Expression takes Func<T> as input and is to be used as a variable and not as a method that is the case with Func or Action

Ex:
Expression<Func<intintint>> PrintMulti = (x, y) => (x * y);

            Func<intintint> Mutli = PrintMulti.Compile();
            var zExp = Mutli(5, 10);
            Console.WriteLine(z);



ASP.NET :: MVC :: Layout file

Master pages in MVC are a little different from that of ASP.NET. 

PlaceHolder is the one that holds a page's content inside the master page. In the same way, RequestBody() is the place where the view's data/content is placed and then rendered to the user.

RequestBody() is in the _Layout.cshtml page.

But how is it that MVC knows that it has to start _Layout.cshtml first before anything else is loaded??
That is in a file called _ViewStart.cshtml

This is the code inside it:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";

}

If we want to override a specific page that we can have a page with the same name in the folder of your views.

Say you have a folder Home and it has Index.cshtml and it should use a Layout called Layout2.cshtml file then create _Layout2.cshtml in the same folder.

You can even do this within the view as well like this:

@{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout2.cshtml";

}



git Config --global :: set your accounts default identity


I was working on to puch my node application to heroku last week. Before we can push the code to Heroku, we need to have Git (not GitHub) installed on our machines with a valid SSH token. Git, to reiterate, is a version control tool.
So, when i said >git commit, this was the msg that was shown.
Q) What did i do?
A) inplace of the user.email and user.name, give a value that you think you can remember day in and day out!!!


$ git commit

*** Please tell me who you are.

Run

git config --global user.email "you@example.com"

git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.


fatal: unable to auto-detect email address (got 'Obby@ObbyWorkstation.(none)')





MongoDB issues : Recover Data after an Unexpected Shutdown

Today while working on MongoDb, i had a power interruption and the system has restarted. when i tried to start mongod.exe with the command

>mongod.exe --dbpath E:\MyFolder\bin

it threw me an error stating there was an issue with the close connections of Mongod. This means that data sync has some issues and so mongod cannot start smoothly
The solution for this is:

check if there is a file named mongod.lock in the bin folder. If yes, check if its size is greater than 0kB.
If yes, then delete this file, because this is the one that is intimating mongod that there was an abrupt closure of the database the previous time.
now go back to the command line and say

>mongod.exe --journal (in case journal is not set for your db)
>mongod.exe --repair

this should set the database back in line and up and running.
if you get another error like
initandlisten] exception in initAndListen: 10296 dbpath (/data/db) does not exist, terminating

then exit the cmd line and rerun the repair command and then say

>mongod.exe --dbpath E:\MyFolder\bin

to set everything back in line.

Post json is empty in nodejs when used with postman

Using postman app for chrome, i was trying to post to my node js application listening to port 3001.
however, all the body of the data is sent as empty.
Because of this, the only data that is getting saved in mongodb using the mongoose connection was as below:

{
    "_id": "542e4ea1480f9abc13239976",
    "__v": 0
}

The issue with the code was that the body parser was placed at the end after the mongo connection was created and just above the app.listen(3001) line

When i changed the code to the top of the file just after the line

var app = express();
it worked for me.

now my complete code looks like this


var express = require('express');
mongoose = require('mongoose');
fs = require('fs');

var app = express();

app.configure(function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
});


var mongoUri =  'mongodb://localhost/MyTestDatabase';
mongoose.connect(mongoUri);

var db = mongoose.connection;

db.on('error',function(){
throw new Error('unable to connect to db');
});



require('./models/MyTestModle');
require('./routes')(app);

//moved from here to the yellow highlighted section

app.listen(3002);
console.log('Listening on port 3002...');

Android Studio :: upgrading to 0.8 and above from previous versions?

if you are upgrading from a previous version of Android Studio to 0.8 and above then with in your project, make sure
you change the following things:

In build.gradle, check if apply plugin reads as follows:
apply plugin: 'com.android.application'

at the bottom of the file, the dependencies should read like this

compile 'com.android.support:appcompat-v7:20.0.0'

DATEPART and DATENAME usage

Had this requirement of reading the name and month value for one of our requirement today.
We used the easiest once -

DATEPART(month, Customer_joining_date)

this outputs the numeric month value. So if its January its 1, Feb then its 2.

DATENAME(month, Customer_joining_date)

this outputs the month name from the date time value. So if its in mm-dd-yyyy (08-26-1987 18:52:03:00) then it is will output's AUGUST.

SYSDATETIME() vs  GETDATE()

both of them will return the same current system date time but SYSDATETIME() will return that in DATETIME2 format with precision upto 7 digits.



vachar vs nvachar in SQL Server

Do you know- 


  • VARCHAR takes less amount of disk space to store than NVACHAR for the same string.
  • VARCHAR does not support unicode data. So, if I try to save a string that is in any other language than English, it fails to display it as is.
  • Thus NVARCHAR comes to our rescue in case we want to save unicode string variables/ literals.
  • If we run the execution plan for select statements that have VARCHAR and NVARCHAR, we will notice that NVARCHAR takes more time to than VARCHAR.


remember these simple things and design your database variables next time to save disk and save execution to be faster.
Happy coding.

4 points for better productivity and for a better product.

Recently, I have completed 6 years in IT industry. On this occasion, when I pulled my friends for a evening coffee,I have been asked by few of my friends to put down a few points that I think are worth noting from my 6 years of IT industry experience.
Though my complete career has been with IT so far, yet I believe that the points that I would write will stand valid for all the other fields where effort and output has a great importance. Hence, I published my article in LinkedIn yesterday with just 4 and yet most important according to me.


As a child, I was taught that I must have some self-guidelines and self-discipline. However, it is a surprising thing that the so called “self” are taught to me when I was a kid, and I was made to keep up to the mark and if there is any chance, make it a habit for lifetime.
The common point from one of the many “self” things that were taught at home and school was being able to do and complete my activities in time and within the schedule of either my parents (mostly my mom in this case) or by my teachers.  All of them believed that doing so will take us to a better tomorrow and a better way of leading life.
Here are my 4 most important learning’s that I had in my last 6 years as a professional in an IT industry that is mostly dominated with the single phrase – “productivity”.

[Read the complete article here: Read It Now!!!]

pic credits: xlntele

Manage your tasks and not your time

I prefer saying manage one’s tasks over managing one’s time. Managing one’s activities is more important than managing time. Doesn’t it sound funny when someone says – “You will have to learn to manage your time”? [Read more].

Understand the key concepts/ business scenario.

No matter what field you are in, it is more important to understand the true business scenario to which you are working. This means, think what is it that the end user (customer) is expecting when she comes across your product. Does your design appeal the end user? Does your approach have all the ingredients that will keep up to the expectations of the end user? [Read more].

Get involved and get going.

Don’t stop after you know what the end user has asked you for. Be proactive. Talk to your manager. Get involved in all those meetings and interactions that have the client representation. [Read more]!

Communicate and communicate directly.

I am sure that majority of the sessions that you were forced into might just have been on communication skills and email communication. I am confident that they have definitely helped you better the way you talk to your colleagues and the way you write your emails.
However, what I mean here is completely different from the rest of them [Read more].

The To-do list.

That's the biggest thing that anyone has to manage more than anything else these days. Someone who manages his/her todo list is more a manger symbol in today's fast moving world.
How are you managing your todo list then?
Some use cellphone alerts some use calender ans some use the system pop ups.



In the good olden days, people maintained a diary fir their tasks and activities.  With increasing use of technology,  people don't even remember their wife' phone number.

In this situation the old practices come to our rescue. Try carrying a pen and a small paper that fits in your pocket.  Write the most important ones with a star in front of them and number for the others.

This is the best way to get the most important of your work done with almost no hindrances

LinkedIn new look and feel for premium users.

We know how important it is to be internet social these days. A new communication trend that came into, has made everyone get in for some or the other reason.
Facebook has been leading the internet social scene from the days it got popular. the FB team picked up the tastes of its users and their love and what they want in their social sites quickly. With Agile all over, they are fast in releasing so many new features every now and then.
Twitter, another social networking site, has recently made changes to their user profiles that look very similar to FB. Now, LinkedIn has fallen in this line with change to their premium users profiles.

Have a look here.

SPINNER control for Android UI

These days, as part of my side project, I have started working with Android. There was a requirement to show type of travel (business, economy, tourist, etc.,) basis for the customer who is awaiting to check-in into our clients hotel.

Android gives us a simple spinner item that can be quickly built and used. Below is the sample. For the sake of the sample, i have hard coded the location names, instead of picking up from SQLlite.


for my MainActivity.xml, i have made it implement  AdapterView.OnItemSelectedListener .

Then, defined the spinner and its dataset
        //to read the spinner element
        Spinner spinner =(Spinner) findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(this);
        // Spinner Drop down elements
        List<String> categories = new ArrayList<String>();
        categories.add("Business");
        categories.add("Family trip");
        categories.add("back packing tourist");
        categories.add("delegation visitor");
        categories.add("Other Tourism ");


Then, i have set the Adaptor details for the ArrayList and the spinner to bind together.

// Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                                    (this, android.R.layout.simple_spinner_item, categories);

       // Drop down layout style
       dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

   // attaching data adapter to spinner
       spinner.setAdapter(dataAdapter);



Override the methods for onItemSelected

 @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        // On selecting a spinner item
        String item = adapterView.getItemAtPosition(position).toString();

        // Showing selected spinner item
        Toast.makeText(adapterView.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
here is the out come of the code in the emulator.



Making a logged In customer :: Few more ways

In this new world of technology, where eCommerce is making the established shop sellers sweat, one of the ways where you show growth is by the number of people registered with your site. 
But is it good to have a forced signup page as the landing page? 
Many people from famous sites like Smashing Magazine, Design Moto etc., say that let the customer experience the site first and make her love your way and then let her decide when to become a logged in customer. Sure, she will become when she wants to end up buying an item from you.


(note: This is not to critisize any website owners and handlers, they are purely opinion and debate based. Feel free to contact me if any of the content is objectionable for you)

Random Code snippets 1

Was trying few things in random and came across this.
How to call a non-static method inside a static method which belong to the same class. Here is the sample.
question framed myself.


Small Talk :: WCF :: RESTful service basics


I came across one question too many times on multiple websites and from multiple persons -
"What is REST and RESTful service?" or "Please tell me how to define RESTful service?" or "What is the significance of RESTful service?"

So, I have decided to write this post and believe this will clear the air about the basic understanding of RESTful service.

Here we go:

  • REST stands for Representational State Transfer.
  • RESTful service says that any service should be treated as a RESOURCE and it should be available and be accessible using simple HTTP binding.
  • It says that any operations that we perform on database are resource operations. So, RESTful service should also be able operate in the same manner.
  • Thus, all the CRUD operations, called the VERBS- that is actions should be performed using the REST.
  • So they are – GET(), POST(), PUT(), DELETE().



What next? Think about ODATA services? .... sure, will take this up too for the benefit of all of us here, in the next post. Happy Coding!!! 

Instant Calculator using Google

Need an instant calculator in your web browser. Here it is from Google. Few of you might already know this yet sharing it for the benefit of larger audience.

Converting a normal ILINQ query to parallel linq query


A simple example for converting the normal linq query to a Parallel Linq query in dotnet.


public void NormalLinqQuery()
        {
            IEnumerable<int> localRange = Enumerable.Range(1, 100000000);
            Stopwatch watch = Stopwatch.StartNew();
            var output = localRange
                .Where(getNum => getNum % 1234567 == 0)
                .Select(rangeNum => rangeNum);
            foreach (var num in output)
                Console.WriteLine(num);
            Console.WriteLine("Normal Query in millisec: {0}",watch.ElapsedMilliseconds);
        }

        public void ParallelLinqQueryExample()
        {
            IEnumerable<int> localRange = Enumerable.Range(1, 100000000);
            Stopwatch watch = Stopwatch.StartNew();
            var output = localRange
                .AsParallel()
                .Where(getNum => getNum % 1234567 == 0)
                .Select(rangeNum => rangeNum);
            foreach (var num in output)
                Console.WriteLine(num);
            Console.WriteLine("Parallel Query in millisec: {0}", watch.ElapsedMilliseconds);
        }

Django +Python coming up


Its over 2 weeks, that I have not posted anything here. Wondering what I am up to? 
The pic below describes all. So, stay tuned for a tiny sample code in our Github soon. Happy coding.

My first game with Python

In the last 3 days, I have started learning and exploring Python. Many of the webpages said that it is easy to code in Python and the code talks back to the developer when he/she visits it even after a long time in way where the gist is understood within no time.



Below is the link to my git-hub code where i wrote a program that holds an arrays of 4 words and the user has to guess the randomly generated word using the banked-spaces clue. The code is in Python 3.3.4

https://github.com/eshwaryaddanapudi/Python-WordGuess

Angular Dart : Flight School : GDG Hyderabad

I have attended the Angular Dart session called the FLIGHT SCHOOL in the Google Hyderabad over the weekend on 22/2/2014 organized by Google Developer Group - Hyderabad (#GDGHyd). Dart is a programming language from Google that's built on Object Oriented Programming and is an open source. 
So what? We have a post on it's way that teaches the basics of DART. 
Below are the few snaps from the event.
-
-







Redis NO SQL database: some hands on

Over the last ten days, I was busy with a family get together. Hence, not posts and I cannot blog anything than technology and related here.

What I did in the last three days is working on a simple application that gets and sets data and perform CRUD operations on Redis: Key-Value pair NO SQL database technology.

Will upload the code in github sometime this week. see you.


Agile Methodologies ::Building Blocks: Episode 5

During few Coffee time breaks in the last 2 weeks, we a group of 4-5 people have been discussing about Agile and one of my friend asked me -

what is that ONE THING, that is SO GOOD with AGILE that can made this methodology happen and work for so many.
 As always it was, we did have one of our friend supporting waterfall model.
 
image belongs to the respective owner


Here is (are?) my answer(s) :


 ü  Agile is all about developing a part of the application in iterative cycles (sprints). 
ü  At the end of the sprint, a minimal deliverable product that is part of the actual application is delivered. This means, a team or an individual is not dealing with too many things at a time.

ü  When it comes to the manager’s point of view, it means that he or she can see what is going good or what's going bad with the development strategy is. 

ü  When it comes to the owners of the product i.e., the  higher management, it gives them an opportunity to look at how the current application is, assess against the odds on how it’s going to fare.

ü  Show it to the stakeholders or potential customers and get the feedback from them and work again on the application to do what matters the most to the end user.

In contrast, Waterfall is all about collecting all the requirements and executing them over a long period of time and then delivering them. You never know, when the priority of the consumers is going to change.

MagicTodo -using HTML5,CSS3, JQuery, MediaQueries

Hi All,
As promised yesterday, i have uploaded the code to the git hub and it can be found here.
This is mobile first application designed using media queries + css3. I will let you know, once i convert this file to a mobile app. I am thinking to use PhoneGap for this. I have to get hands on and then do this. so will take some time. I have used the localstorage of the web browser to store the data as a json. See you tomorrow with Agile.

link for source code: https://github.com/eshwaryaddanapudi/MagicTodoList.git

(img: all rights to the owner) 

 (mobile phone screenshot)
(desktop -web browser screenshot)


HTML5, CSS3, $JQuery & localstorage

In the last 2 days, I have got my hands dirty on how to use HTML5, CSS3 and JQuery to do a simple, i mean it, very simple TODO-List using the LocalStorage of the browser.

here is what i have achieved after 2+4 hours of effort in the last 2 days. I will upload the code to Github and share the same with you folks.

trust me, JQuery is awesome with HTML5.


Reinventing the Wheel.

Before we start talking about Agile, I had an interesting talk with my friend about the posts of my blog here. He says that a lot has been talked about code, clean code, best practices, C#, Agile and what not there are too many people with an experience more than my age!!! So he concludes that i was trying to re-invent the wheel.

My answer was simple and straight forward - I understand and I know there are many of them here. Yet, probably I have the ability to put things very simple. I believe that my posts can reach to those who are looking for things that are told in a little easy way.

If we do things which are for a better than the existing one, its always good and its always new. This only means telling the story more cleanly and clearly with a new additions.

See you next week with Agile Methodology :: Episode 5

Agile Methodology series :: episode 4

As part of the agile practice assessment, we group of friends, the other day they had a talk about how we feel and what we feel are good and bad about agile. what we feel are okay and what we feel are awesome about agile in comparison with waterfall model which we practiced previosuly.


So, lets get into the topic.

What I like with agile:

1. As a team, we can pick and choose which tasks to complete first.
2. I have the freedom of talking and sharing with my teammates more.
3. With more talking, we felt it was the ideas of the complete team than just a two or three that counted.
4. We have the best oppurtunity of 2-3 brains thinking on a problem, if we are stuck than a single head hitting on the wall for a solution.
5. Estimation is done based on ME and MY TEAM members abilities and skill sets than just picking up few use cases.
6. Minimum documentation to the level of making the new entrants understand the project.

What I hate/dislike/disagree about Agile:

1. Too much freedom or too much of work as tasks are divided for everyday core working hours.
2. Sometimes, it so happens that everyone is busy with the sprint work that I don't get a dedicated helping team member to solve my problem.
3. Too lengthy retrospective and sprint planning meetings.
4. Continuous work allocated. So taking a leave might turn my next day a nightmare.

Points of conflict.

1. Less scope and more scope for INNOVATION
2. Less documetation is a down side and at the same time an advantage
3. Team talk an advantage as well as a disadvantage.
4. Product owner giving tasks based on sprint length makes us lag on the complete knowledge of the project and the work to be done.


We will talk on some points in depth and touch upon few more in the next episode.
Stay tuned! Stay curious!! Stay Healthy!!!

All great ideas were shared listening : The Art of Listening

I think it’s not just right to talk about code and the software practices alone. There is more to this what makes the earlier two things go on and succeed. They are skills of different kind. I know that you guys would have guessed it by now – the behavior skills.

Behavior skills in its own is a very vast subject and more importantly it cannot be taught with a chapter in the book for every situation. However, we can make ourselves go through few leanings and stitch them with our previous experience and make ourselves ready for the best and the worst. And every time, it’s the act as per the situation that makes us more convenient and others in the situation more comfortable. So, let’s jump in, but where shall we start? I have the answer!!! Trust me and follow me here.


The first and the foremost of the Behavior skills (BS) is conversing. I somehow don’t want to take the word communication right away and right here, because it’s again a big topic on its own. When we are at a comfortable place, we will start using the word communication. Conversing is between two or more people and in general on a specific topic. So as far as the subject is concerned it’s easy for everyone in the group. However, for the subject to take a route where it realizes (I dislike the word ends-up, because it’s like a narrow mind thought)to become a fruitful discussion is when everyone puts in their thoughts on the subject matter.

But what it takes to make everyone their thought? It’s all about a simple practice of listening to the one who is talking/speaking and the rest giving the full levels of dedication to the one talking. This makes the complete circle of conversing. Yes, A complete life cycle of conversation (sounds pretty similar to SDLC?).

So, we shall put a full stop for this point here and come back with a new line in the next post. Thus, it’s very important that we listen to someone who is talking in the group while we are in discussing, because you might never know that a person who hasn’t spoke at all has a better idea than the rest of the team. See you soon!

Agile Methodologies : Tips : Tip1

  1. Make sure stand up meetings don't go beyond 15 min of time.
  2. Never discuss a topic too deep. Say a person is facing issue in establishing an ADO.NET connection to the DB. It should remain as a hindrance issue and not a topic to discuss on.
  3. Carry a piece of object like an identifier, that indicates who is speaking.
  4. More importantly, don't leave the issue reported in step(2) in the stand-up but discuss it and help resolve the person his/her issue at their desk.

Stay tuned, stay healthy, keep coding!!!

Agile Methodologies : Series 2 : Scrum Methodology


Parker and John are two champs working with a renowned IT product and services company. These days, they are keeping themselves busy for few hours and free for few hours at the office. When peeped in, you can notice that they are spending their time at Pool table, a smiling chat over a cup of coffee.

We grew curious and wondered how not just these two folks but rest all from their project are seen around the office at the same time. So, we decided to walk to them and ask what made them have good free time at office and at the same time deliver better quality product during the project meetings and demos. The answer was straight and clear  - "We are into Scrum under the Agile Methodology"

So, what is Scrum Methodology


When we talk about agile, most of the teams that practice agile are using scrum methodology. That's because its the most easiest and the simplest of all. The simple steps that make Scrum the simplest of all are.
  • Its team has 4 different roles 1. Product Owner. 2. Scrum Master 3. Team members.
           However, Scrum master is not a new person in the team, but a role given to one from the team.
           A good output from a team can be obtained if the team has 2 developers and 1 QA.
  • The project requirements are executed in what is called SPRINTS which last for 2 weeks and in some cases 3 weeks. 

  •   At the end of the sprint, all the team members/ stake holders get into a meeting and review the work done. In general, this has what items of the product have been promised, what are delivered, what have changed and followed by a DEMO of the potentially shippable application.

Backlog:

This has all the requirements to be developed so as to produce a completed product.
Each backlog item has few steps that take the team's efforts closer to finish line.

Sprint Planning:

Few items together executed over a sprint makes a potentially shippable product.

Daily stand-up.

Also called as daily scrum, all the team members share with each other
  • what an individual has done yesterday
  • what  is in for them for today
  • are there any obstacles/ impediments/blockages that can hinder the sprint work
This meeting is presided over by the scrum master.

Sprint review:

At the end of the sprint, team has a meeting with the product owner where the developed part of the application is either accepted or rejected.

Sprint retrospective:

This is the last step of finishing the current running sprint before the next one is taken. Here the scrum master discusses what went well, what went wrong, what were the unexpected that came to the team during the sprint. This helps in better planning for the upcoming sprints.

See you with another series on agile coming up!!! stay healthy, stay tuned, happy coding.



Agile development Methodology : A series : Introduction

Being a software doesn't mean that you always, all time stick to writing code based on the requirements.

Writing code is a job that makes a software engineer stick around. S/E is the one who makes requirements turn into applications. But, how is it that he/she make this change that helps the client's life turn around?

Everything in life is bound to follow step-by-step procedure. Say for example, reaching destination B from A. The step-by-step procedure is get to the nearest transportation mode at place-A. Get into the transport mode and reach-B. But this doesn't merely solve our requirement.

What else will we do? Find what is the best route and the fastest mode of transport available at place-A that makes us reach place-B faster.

Alright, say if this is the requirement for few hundreds of people out there at place-A at the same time. Assume that everyone takes road, hire a car and reach place-B. This leads to blockage of roads at a junction. How do we control the flow? put in a traffic signal and control the traffic. This is called management by laying down few rules.

Thus everything in life has a step-by-step procedure which has some rules that manage the software life cycle so that the life of S/E moves easy and helps him/her develop a better quality product with high quality coding standards.

To achieve this, there are many methodologies/ methods like waterfall, iterative, Agile etc.

Off late the one that gained importance in the recent times in Agile. Though Agile existed for over 2 decades now. management and developers have started believing that releasing little chucks of working code every now and then which shows some result is more important than a disaster that can possibly occur after all the development is done at one stretch.

So in the coming few posts, just to relax ourselves from hardcore programming we shall focus and understand what makes our life easy being a software engineer.

Lets make our code talk - episode 3

Hi guys,
Wish you and your dear one's a wonderful new year- 2014 ahead.

Continuing our abilities in trying to bring the best of us using our code, we are in the 3rd episode of this. This time around, we will discuss how we can make our code get rid of the red lines.
Red lines? Yes, the hard coded text in C# is in general in red color and so we call it the Red-Color-Phobia.

Red-Color-Phobia.

Many developers have this tendency of hard coding few values, during the process of assigning things, comparing things or while retrieving things.

Example 1:
Say, there is a requirement for an online shopping portal where in, based on the current location of the active customer, a surprise discount percentage has to be offered during the Thanks Giving time.

The developer/ programmer has written this to achieve the requirement.

Var cutomerSurpriseDiscountPercentage=0;
Var customerLocation = string.Empty;
If(customerLocation == “New York”)
{
       cutomerSurpriseDiscountPercentage = 10;
}


How can we better this code?

Define an ENUM that holds the names of the locations to which the surprise discount s available

enum ValidSurpriseDiscountLocations{
NewYork = “New York”,
Detroit,
NewJersy = “New Jersy”
}

Thus, our code is little modified for a better quality


Var cutomerSurpriseDiscountPercentage=0;
Var customerLocation = string.Empty;
If(customerLocation == ValidSurpriseDiscountLocations. NewYork)
{
       cutomerSurpriseDiscountPercentage = 10;
}


See you again.