Tuesday, November 27, 2012

Always check in schema.rb

I was unsure whether schema.rb should be checkin or it is something which is created automatically while running project. But find out that it should be check in to your repository.

More Information always-check-in-schema-rb

Saturday, November 24, 2012

master branch and 'origin/master' have diverged, GitHub

Struggling with above error while getting latest everytime?

use this command to get latest from the master branch: git reset --hard origin/master

The following untracked working tree files would be overwritten by checkout, github

In case you're struggling with this error while getting latest (push) from the repo or trying to merge existing changes then use following command:

git clean  -d  -fx ""

it will delete untracked files. Also the following link has good explanation of couple of useful git commands.

Source: Stackoverflow: error-the-following-untracked-working-tree-files

Wednesday, November 21, 2012

Various database management systems

Like this guy over stackoverflow (Stackoverflow question) even I was trying to understand the difference among various database available across industry.

As suggested, wikipedia has done nice job in explaining it clearly Comparison of relational database management systems.

Friday, October 19, 2012

Rename a database column in Rails using migration

There are times when you need to rename a database table's column name in Rails which was originally created by using scaffold/generate command. To do so first create a new empty migration and then add following statement in self.up
rename_column :table, :old_column, :new_column
Visit this question for detail description (with complete code) Rename a database column in a migration

Sunday, October 14, 2012

Installing and running MySQL service on windows

It may occur that while installing a fresh copy of MySQL server, the mysql service does not start automatically. In-fact, service is not added/installed to windows by default. In that case follow the following steps:
I'm assuming that MySQL server is installed. If not then go to MySQL download link and download Windows (x86, 32-bit), MSI Installer

a) First of all change User Account Control (UAC) settings to allow installation of new service to windows. Go to control panel > User Account, then open 'Change User Account Control settings'. Change settings from default to lowest i.e. Never Notify. Hit OK and restart system to apply changes.

b) After restart, open command prompt and navigate to bin directory of MySQL. It might be in ProgramFiles or ProgramFiles(x86). Here is the path of this on my machine: C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin.
$ cd C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin
 then install mysql service using:
$ mysqld --install
Careful - there is 'd' in service name. After installation, you can verify whether service is properly installed or not in services list. (Run services.msc command in run prompt not cmd).

Now just start the service by using (in cmd):
$ net start mysql
That's all. Your MySQL service is up.

Monday, October 8, 2012

Maintaining multiple ruby and ruby gems version in windows

I've two different gem repository 1.8.7 and 1.9.1. However ruby gem environment uses only one gem repository for all uninstall and update commands (which can be retrieved using GEM ENV) command. But because of this I was somewhat helpless for uninstalling/modifying the gems in repository different from the default one. Use the following steps to control the same:

Maintaining multiple ruby version: PiK is a very helpful gem to maintain multiple ruby versions on your machine. You can add references of all ruby versions available in system and select which one to use by default i.e. updating Gem environment.
a) Install Pik gem: Open command prompt with ruby and rails (type ruby in search box on windows)
gem install pik
b)  Then add the bin path of all ruby versions available like:
pik add C:\RailsInstallerNew\Ruby1.9.3\bin
 c) Now run "$ pik list" command to verify all ruby versions added to pik. Also notice there will be a unique number in the starting of each ruby instance like 187, 193 (which references the ruby versions).

d) To select a particular ruby version use "pik <unique number mentioned in point c>" like
pik 187
After this command if you fire pik list command then you'll see a * in front of ruby 187 version. Also "$ gem env" command will show ruby version 1.8.7 as the default version selected.

Maintaining multiple gem set with multiple ruby versions (not sure): In case of multiple gem directory and uninstalling a particular gem version (from the gemset different from the default gem repository) first go to the gem bin directory of that particular ruby version (from the cmd) and then fire run "gem uninstall <gemname>".

Sunday, October 7, 2012

Invalid date format specification in gemspec

If someone is facing issue with gems version conflict or have an error like "Error running test: units and test: functional" while running bundle exec rake command then following steps might fix all gems version conflict related issues like "Invalid date format specification in gemspec"

Go to your project directory in CMD and run following commands:
1. "gem install rubygems-update",
2. "update_rubygems",
3. then "gem pristine --all"

This combination solved the problem for me.

The program can't start because LibMySQL.dll is missing from your computer.

Follow these steps to fix this issue:
Step -1 copy the libmySQL.dll from this link LibMySQL.dll download link (Assuming you're using ruby 1.8 not 1.9, in case if you are using the latest version then take the latest dll version not this one which you can retrieve by installing the latest mysql exe on your machine and this dll can be found at: C:\Program Files (x86)\MySQL\MySQL Server 5.5\lib)
Step -2 Paste it in C:\Ruby\bin of yours


Friday, September 28, 2012

General ruby on rails installation and integrating issues

Error integrating mysql withRuby on rails

Invalid date format specification error :
"gem install rubygems-update", "update_rubygems", then "gem pristine --all" is the combination that solved the problem for me http://stackoverflow.com/questions/7290575/invalid-date-format-specification-in-gemspec

Deactivate a Gem - you have already activated rake 0.9.3.beta.1, but my Gemfile requires rake 0.9.2
run command: "gem uninstall rake" then command prompt will ask you which version to uninstall and selet 0.9.3 there after you will be left with the desired rake version.

Saturday, September 22, 2012

Semi Join and AntiSemiJoin, SQL

Joins explained : http://blogs.msdn.com/b/craigfr/archive/2006/07/19/671712.aspx

Monday, September 17, 2012

missing :controller ( ArgumentError), Ruby

C:\work\BackChannel>rails destroy Category
/routing/mapper.rb:179:in `default_controller_and_action': missing :controller (
        from C:/work/BackChannel/builder/ruby/1.9.1/gems/actionpack-3.2.1/lib/ac
tion_dispatch/routing/mapper.rb:76:in `normalize_options!'
        from C:/work/BackChannel/builder/ruby/1.9.1/gems/actionpack-3.2.1/lib/ac
tion_dispatch/routing/mapper.rb:59:in `initialize'
        from C:/work/BackChannel/builder/ruby/1.9.1/gems/actionpack-3.2.1/lib/ac
tion_dispatch/routing/mapper.rb:1302:in `new'

I was having this error while running either a destroy command or scaffold to create new category. Later I realized it was because of some existing routes present in routes for Category model. After removing them command worked successfully. In order to debug such error track the stacktrace of error and find any file which is part of your project. I mean not the ruby code base file.

Delete controller, view, models automatically from Rails Application

In Ruby on Rails, it is quite easy to create a new model view and controller using the scaffold command. Apart from the mentioned MVC this command also creates many other files like migration which proves quite helpful for creating a new ruby application.

However there are times when you want to delete a controller / view / model from the application along with files that are automatically created with the scaffold / generate command like fixture, spec etc and the simple command to ease your task is destroy (Rails3). Use it like

rails destroy controller controller_name
e.g. rails destroy controller categories

Here we can replace controller with view or model to delete an appropriate object.

Note that while specifying controller name just specify the name of controller not controller file name like here categories not categories_controller.rb. This command will delete categories controller, model, view and other background stuff. Here is the list of task done by the command fired in example.

Saturday, September 8, 2012

Installing a fresh copy of Latex and editor on windows machine

If you need to create a document with lots of mathematical functions then it is very well suggested to use software like Latex. Basically Latex in itself is not an editor however it provides binaries/libraries which can be used by a text editor for creating highly sophisticated documents full of Greek alphabets.

Follow following simple steps to install the Miktex and TexnicCenter
1. Download MikTex latest version from this page MikTex Setup.
2. Install it and mind it while installing, setup will prompt you when to download additional package which is default to 'AskMe' change it to Yes so that you've all updated and required binaries. It might be possible that if you don't change it you won't get Tex.exe or Latex.exe which are required for an editor.
3. Next, download the text editor for creation of your text document using Latex. I personally prefer TexnicCenter, download its latest installer from this link Texnic Center Setup (In case link is not working use this link instead Texnic Download Page)
4. After download and installation of TexnicCenter, when you run the TexNic Center first time it will ask for several configuration which are very important for proper working of software.

a) Link to Latex.exe or Tex.exe distributables. Supposing you're using a 64 bit machine, provide this link C:\Program Files (x86)\MiKTeX 2.9\miktex\bin and press next.
It might be possible that here dialog will prompt with error: "The application latex has not beed found in the directory of your tex distribution". This error comes because you did not change the automatic libraries download option for MikTex from 'Ask Me' to 'Yes', which I mentioned in step 2. Simple resolution will be to repeat step 2 only. I personally stuck on this step for atleast 2 hours.

b) If you are good with latex link then next setup will ask for post script viewer path which is basically a software where you wish to view your document after compiling through latex. Generally it is Adobe reader so provide the link to adobe reader.exe.
On my machine link is:
C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRD32.exe

If nothing strange come up then you're good to go. Open Texniccenter to create new latex documents. After writing documents you first need to compile your documents (F7) and view output (F5).

This is my personal experience with latex installation. It might be possible that something new come up so please feel free to post your issues and suggestions.

Thursday, August 30, 2012

Ruby Handbook (Frequently Used Concepts)

Frequently used concepts-
1. Difference between 'do..end' block and brackets { }.
Ans: Do End Block vs. Brackets

2. Copying Ruby object.
Ans: All variables in ruby are references to an object. a = b means that a and b points to the same object. To copy an object use a = b.dup . Credit

3. What is Ruby's double-colon (::) ?
Ans. Double color :: in Ruby

4. How to call Class Methods from Instance Methods? Difference between Class Methods and Instance Methods? Also the differences between class instances and method instances.
Ans: Using Modules and mixins. A mixin is a module, but a module isn't necessarily a mixin.
        a. Difference between class variables and instance variables
        b. Difference between class methods and instance methods

5. Ruby is not a statically typed language i.e. it is a dynamic language and there is no such thing called compile time check. That's why even if there is some conflict in accessing a method because of its Access Protection then it will be determined only at runtime without any prior warning.

6. In Ruby, all variable are references to objects not their copies.

7. What is the difference between puts and print method?
Ans: puts method add a new line character after each print however print method does not. So if you have a block to print all elements of  an array, then puts method will list each object of array in new line however puts will place all elements in single line like a string. Other references

8. Name a method which is used to get next int or character from a variable? i.e. to get 3 from a variable whose value is 2 or to get B from a variable A.
Ans: <variable>.succ (Successor)

9. Difference between Single Quote and Double Quotes in Ruby?
Ans: Mostly single quotes are used when we don't need to have string "interplation", where actually we use double quotes. Single Quote Vs Double Quote (Brief)

10. What are Exit codes in Ruby?
Ans: Whenever you run a Ruby script/program, a process is started. When a process is completed or interrupted in middle, it always exits with a exit code within range 0-255 which represents whether process was successful or not. An exit code with 0 means that program was successful. More details: Exit code in ruby

11. What is Database migration and list all methods used for the same
Ans. Migrations are a convenient way for you to alter your database in a structured and organized manner. Complete explanation: Migrations in ruby on rails

12. RubyMine - Could not find gem "jquery-rails". or similar gems
Ans. In such issues, run command gem install jquery-rails from the command line. Stackoverflow Adding a new gem

13. Scope of instance variable in a controller method. How long it will be retained?

Monday, August 27, 2012

Frequently used Adobe Reader keyboard shortcuts

These days I'm using Adobe Reader very frequently and extensively. Here are the couple of shortcuts which will help you in reading better.

1. Go to a particular page number: CTRL + SHIFT + N . So now no useless scrolling if you mistakenly pressed end key.
2. Readmode/ Presentation mode: CTRL + H, L: Personally I use CTRL + L mode for reading.
3. Increase/Decrease Zoom level: CTRL + "+ / - ": Control plus "+" or "-" key. Note that this shortcut also works in Presentation mode so if you want better concentration while reading a book and font of book in presentation mode (full screen mode) is very small then use CTRL + "+" key to increase that. I use it this way only.

Will add more later.

Saturday, August 25, 2012

Configuring RUBY in Eclipse Juno, Windows

Steps to configure Eclipse Juno for RUBY development from scratch on Windows 7:
1. Install Ruby: Download the latest ruby one-click installer and after installation. Run 'ruby -v' command to verify ruby path is properly set up. In case you get an error like- not recognized as an internal or external command. Add a new environment variable (right click my computers, properties, advanced properties, environment variable) with properties as : Name - Path , Value - Ruby bin directory path. Somewhat similar to C:\ruby193\bin
2. Download latest eclipse (preferably - Eclipse IDE for Java developers) from Link to download Eclipse.
3. Extract the zip file to a folder and create shortcut of eclipse.exe to an easily accessible place and run eclipse.
4. Now your eclipse is ready for Ruby installation. Go to Help -> Install New Software.
5. Select 'Juno' for Work with combobox.
6. Then in the textbox below 'Work with' combo, type "Ruby".
7. You will see a checkbox before 'Dynamic Languages Toolkit - Ruby development tools'
8. Select the check box and click next. Proceed to install the same.

There are the major steps you need to set up your development machine.

You might need to configure Interpreters for ruby (which is done by default) In case you face issue with creating new ruby project then go to 'Window -> Preferences -> Ruby -> Interpreters' in eclipse. See if there is a ruby.exe interpreter is selected. In case it is not then add a new interpreter. Click browse and provide ruby.exe path. Most probably it will be C:\ruby193\bin. There after it should run successfully.

Now I've started using RubyMine for ruby development. Though it is paid but a very good environment for ruby development.

Sources: Searched a lot but this was the one which finally helped me in configuring interpreter Setting up your environment

Friday, August 24, 2012

Writing your first RUBY program

So finally I've started learning a language which does not have any main method (starting method). Yes, it's ruby. Though I learned a foundation knowledge about ruby and its syntax and familiarize with couple of programs. Here is what you can do to write and run your first ruby program.
1. Online code compiler and editor: Compilr
2. Writing first ruby program : this finally helped me to write first offline program on my machine.
3. Setting up your machine : Setting Rails Development Environment
Configuring your machine to learn new language is also imp step in learning specially when you've no idea about the subject. Currently I'm exploring the text editor (kind of IDE) for Ruby and will post when found a good one and ofcourse free. :)

Also I find this book quite good for beginners Programming Ruby : The Pragmatic Guide

Thursday, July 12, 2012

Idle blog posts

Friends, Good Morning to all. I just want to share with you that I'm going to pursue masters program and pretty much busy in packing and arranging all stuff for my upcoming endeavor. That's why there will be significant drop in blog post in this month as well as upcoming month.

Catch you soon.

Wednesday, June 27, 2012

Learning Ruby on Rails for beginners

Well it has been a long time since I posted something here. Actually these days I'm pretty much occupied in gearing up for upcoming responsibilities. Soon, probably after a month, I would be back to student life from this hectic corporate job. I will be pursuing Masters in Computer Science with specialization in Programming Languages and Software Engineering. So that explains my inactivity from blog.

Meanwhile I would like to recommend/suggest a website to all fellow beginners who are looking for stuff to get start with learning Ruby , Rails programming languages.

Just go to Learn Ruby online. Even I'm learning the same.

Cheers !!

Wednesday, June 13, 2012

Naming your variables, methods guidelines (CS: Part 1)

We name variables, properties, methods, arguments, classes, namespaces, folders, files. Here are some simple naming guidelines:

1. Use Intention-Revealing names: The name of anything should answer all the big questions. It should reveal why it exists, what it does and how it should be used. If a name requires a comment then the name does not reveal its intent. e.g you should not use something like int a; // users count. instead use something like int currentUserCount; No comment required.
Also it is a good practice to create constant variables whenever you're using constant in methods. Such as instead of using condition like if(currentUserCount == 100) use if(currentUserCount == MAX_USER_COUNT) and create a constant MAX_USER_COUNT with 100 value.

2. Make Meaningful Distinctions: Sometimes you try to give same name to refer to two different things in the same scope but as compiler won't allow you to do it you try to do it by adding number series, noise words, misspelling just to satisfy compiler. But this is not a good practice. If names must be different then they should also mean something different.

3. Use Pronounceable Names: Coding in a team is like a social activity and you need to discuss your issues, approach with your colleagues. You should use pronounceable names in your code just in order to have a healthy discussion. Just imaging telling someone that "slcctrlct is incorrect in this module" instead of "switchlegControllerCount is incorrect in this module". This will surely help you instead of being part of a joke.

4. Use Searchable Names: Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text. One might easily find MAX_USER_COUNT instead of searching 100 everywhere in class. Likewise the name i is a poor choice for any variable for which a programmer might need to search. It is the most common letter and likely to show up in every passage of text.
The length of a name should correspond to the size of the scope
5. Avoid Hungarian Notation: Earlier we used to name our variable in hungarian notation like phoneString : a variable for phone of type string. But suppose we later change its type from string to PhoneNumber (which can be done very easily and quickly by IDE) then variable name would be same. Thus it would be
PhoneNumber phoneString; which has misleading information. So avoid these type of notations.

6. Naming Interfaces and their implementation: Consider you are creating a factory class which will provide you an object of particular type of instance. This factory will be an interface and will be implemented by a concrete class. So what should you name them? IObjectFactory or ObjectFactory. Well, it would be better to leave interfaces unadorned here. The preceding, I , so common in today's legacy wads, is a distraction at best and too much information at worst. We don't need to show users that we are using Interface for our factory class.

7. Class Names: Classes and objects should have noun or noun phrase names like customer, wikipage. Avoid words like Manager, Processor, Data or Info in the name of a class. A class name should not be a verb.

8. Method Names: Methods should have verb or verb phrase names like postUserClick, deletePage.

9. One word per concept: Avoid using the same word for two purposes. If you follow the "one word per concept" rule, you could end up with many classes that have, for example, an add method. As long as the parameter lists and return values of the various add methods are semantically equivalent, all is well.

10 Don't add gratuitous context. Say there is a particular feature developed by a developer named Ram then don't create any class like RamDiscoveringDevice.cs. Shorter names are generally better than longer ones, so long as they are clear. Add no more context to a name than is necessary.

Credits: Clean Code ebook

What is clean code, good code? (Coding skills)

Before starting lets check out why do we need clean code or in fact what is bad code which in turn necessitates clean code.

Bad Code: If you're a programmer then I'm sure you must have seen a piece of code in your application with a huge mess and gradually more and more features are added to that same piece and eventually code got worse and worse until code simply gets unmanageable.  We always try to find our way, hoping for some hint, some clue. of what is going on just to let things work as required but all we see is more and more senseless code. This is what known as bad code. We all feel the relief of seeing our messy program work and deciding that a working mess is better than nothing. At that moment we generally think we will come back to this piece and clean it up but according to LeBlanc's law :Later equals never. :)

Ironically we ourselves are the father of this bad code and we generally try to bemoan this thing to excuse like short deadline, managers, marketers, requirement changes etc. But do consider this:
The managers and marketers look to developers for the information they need to make promises and commitments. The users look to developers to validate the way the requirements will fit into the system. The project managers look to developers to help work out the schedule. The developers are deeply complicit in the planning of the project and share a great deal of the responsibility for any failures; especially if those failures have to do with bad code!! Most managers want good code, even when they are obsessing about the schedule. They may defend the schedule and requirements with passion; but that's their job. It's developer's job to defend the code with equal passion. Thus it is unprofessional for programmers to bend to the will of managers who don't understand the risks of making messes.
Clean Code:
Bjarne Stroustrup - "I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimization. Clean code does one thing well."

Beck's rules of simple code:
1. Runs all the tests.
2. Contains no duplication.
3. Expresses all the design ideas that are in the system.
4. Minimizes the number of entities such as classes, methods, functions.

"You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem."

The Boy Scout Rule: It is not enough to write the code well. The code has to be kept clean over time. We've all seen code rot and degrade as time passes. So we must take an active role in preventing this degradation. There is very simple rule:
Leave the campground cleaner than you found it.
If we all checked-in our code a little cleaner than when we checked it out, the code simply could not rot. The cleanup does not have to be something big. Change one variable name for the better, break up on one function that's a little too large or doing more than one thing, clean up one composite if statement. This practice will be very fruitful for the project over the time and eventually your application would be in very much stable instead of all pieces of crap every where.

In upcoming posts I'll brief about how you can make your code clean i.e. good coding practices. 

Tuesday, June 5, 2012

Good coding practices and guidelines, C#

While working on fixing FxCop errors I came across good code practices and guidelines, some of which I know earlier but would like to sum up here:

1. Do not declare visible instance fields
The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. Accessing a property is as easy as accessing a field and the code in a property's accessors can change as the type's features expand without introducing breaking changes. Properties that just return the value of a private or internal field are optimized to perform on par with accessing a field; there is very little performance gain associated with using externally visible fields over properties.Externally visible refers to public, protected, and protected internal accessibility levels.

2. Mark members as static
Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue

3. Do not decrease inherited member visibility 
You should not change the access modifier for inherited members. Changing an inherited member to private does not prevent callers from accessing the base class implementation of the method. If the member is made private and the type is unsealed, inheriting types can call the last public implementation of the method in the inheritance hierarchy. If you must change the access modifier, either the method should be marked final or its type should be sealed to prevent the method from being overridden.

4. Do not expose generic lists
System.Collections.Generic.List<T> is a generic collection designed for performance not inheritance. System.Collections.Generic.List<T> does not contain virtual members that make it easier to implement new behaviors. The following generic collections are designed for inheritance and should be exposed instead of System.Collections.Generic.List<T>.
  1. System.Collections.ObjectModel.Collection<T>
  2. System.Collections.ObjectModel.ReadOnlyCollection<T>
  3. System.Collections.ObjectModel.KeyedCollection<TKey, TItem>

To fix a violation of this rule, change the System.Collections.Generic.List<T> type to one of the generic collections designed for inheritance.

5. Do not ignore method results
Issues: Either one of following comes under this issue category
1. A new object is created but never used.
2. A method that creates and returns a new string is called and the new string is never used.
3. A COM or P/Invoke method that returns an HRESULT or error code that is never used.

Why these are considered as issues: It makes you aware of circumstances such as:
1. Unnecessary object creation and the associated garbage collection of the unused object degrade performance.
2. Strings are immutable. Methods such as ToUpper return a new instance of a string instead of modifying the instance of the string in the calling method.
3. Ignoring an HRESULT or error code can lead to unexpected behavior in error conditions or to low-resource conditions.

How to fix: (Fixes mentioned in order to issue description)
1. If method A creates a new instance of B object that is never used, pass the instance as an argument to another method or assign the instance to a variable. If the object creation is unnecessary, remove it.
2. Method A calls method B but does not use the new string instance that method B returns. Pass the instance as an argument to another method, assign the instance to a variable, or remove the call if it is unnecessary.
3. Method A calls method B but does not use the HRESULT or error code that the method returns. Use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method.


Monday, June 4, 2012

Do not initialize unnecessarily, C#

The common language runtime initializes all fields to their default values before running the constructor. In most cases, initializing a field to its default value in a constructor is redundant, which degrades performance and adds to maintenance costs. One case where it is not redundant occurs when the constructor calls another constructor of the same class or a base class constructor and that constructor initializes the field to a non-default value. In this case, changing the value of the field back to its default value can be appropriate.

Collection properties should be read-only, C#

It is recommended that your collection property should be read only i.e. they should not contain setter. A writable collection property allows a user to replace the collection with a completely different collection. A read-only property stops the collection from being replaced but still allows the individual members to be modified.

If you actually want to replace the collection then the preferred design pattern is to include a method to remove all the elements from the collection and a method to re-populate the collection. Instead of setter property use Clear and Add methods of collection in order to replace the complete collection.

This error is reported by code validation tools like FxCop.

Sources: MSDN Collection properties should be readonly.

Friday, June 1, 2012

SuppressMessage attribute not working, FxCop

FxCop 1.35+ versions have the ability to suppress messages in code using ‘SuppressMessage’ attribute. This attribute Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.

For example: Suppose you have a class

public class UtilityFunctions
       [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
       public string GetMachineCurrentLocation()
          // logic to fetch location using GetUserGeoID & GetUserDefaultLCID etc
           return machineLocation;
In the above example, we've suppressed the UsePropertiesWhereAppropriate violation for the GetMachineCurrentLocation method so that FxCop no longer will raise it. Some advantages of using this:
1. Other developers in your team can quickly see that an obvious violation has been suppressed.
2. Unlike in-project suppressions, changes to the namespace, type or signature of a member (ie name, return type, etc) do not require the SuppressMessage attribute to be updated.

Issue: Using Suppress Message first time won't work in fxcop. Even after adding suppress message, violation errors are still logged in FxCop.

Fix: While using in-code violation suppression first time, it can be confusing as to why FxCop seems to ignore these attributes. The SuppressMessage attribute is what is called a 'conditional' attribute. A conditional attribute is an attribute that is only included in metadata of your assembly if a certain compilation symbol is defined at compile time. 
The SuppressMessage attribute itself requires the CODE_ANALYSIS symbol to be present and by default, this is not included in non-team system projects. That's why FxCop continues to report errors.

To define this symbol, do the following in Visual Studio:
  1. In Solution Explorer, right-click your project and choose Properties.
  2. In the Properties window, choose the Build tab.
  3. In the Conditional compilation symbols text box, enter CODE_ANALYSIS

Hope this will fix your issue.

Tuesday, May 22, 2012

Stored Procedure vs Inline Query, SQL

A very basic post but still worth mentioning. Here are the major differences between the two:

1. Stored procedures are stored in a pre-complied form.That is once a Stored procedure is executed, the compiled code is used in subsequent calls. This is not possible with inline queries.

2. Stored procedures reduces network traffic.
Since Stored procedures are stored in the server, only the name of Stored procedure is required to pass to the server. But in the case of inline queries, the complete query has to be passed to the server. So inline queries will increase network traffic when the queries are very large.

3. Stored procedures support Deferred Name Resolution.That is we can create stored procedures for objects(eg:- tables) which are not yet created (and will be creating in the near future)

4. Stored procedures prevents SQL Injection Errors.

5. By using Stored procedures we can separate all the queries from the Business logic code. Therefore we can create a separate layer. But while writing inline queries, all the queries have to be written (mixed up) with the business logic code which in turns causes issues while debugging.

6.Developers and database designers can work simultaneously using stored procedures. While a programmer writes business logic, another one can create stored procedures at the same time. :)

Difference between Truncate and Delete statement, SQL

In SQL server there are 2 main keywords for deleting data - Truncate and Delete. Although the end result might be same but both work very differently. We should take into consideration the advantages, limitation and the consequences when using one of them.

Before moving to the details lets first understand the basic SQL statement types:

  1. DML - Data Manipulation Language: It is used to retrieve, store, modify, delete, insert and update data in database. Examples: SELECT, UPDATE, INSERT statements.
  2. DDL - Data Definition Language: It is used to create and modify the structure of database objects in database. Examples: CREATE, ALTER, DROP statements.
  3. DCL - Data Control Language: It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it. Examples: GRANT, REVOKE statements.
  4. TCL - Transactional Control Language: It is used to manage different transactions occurring within a database. Examples: COMMIT, ROLLBACK statments.

Difference - TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is release back to the server. However, DELETE is a DML command and can be rolled back.

When we use this command, SQL server deletes one row at a time. Each row is logged in the transaction LOG. This also means that the server will also maintain the Log Sequence number. This will consume more database resources and the process will  be slow. But this also gives an advantage. The transaction can be rolled back as there are transaction log.

Also you can use the where clause with the delete command but not with the truncate command. With truncate command it's all records or nothing.

Also one more advantage of the truncate command is that it also resets the identity seed of the table. Also the fact that deallocated pages is returned to the system for use in other areas.

Truncate statements cannot be used on the tables involved in log shipping or replication. This is because they both depend on the transaction log to keep the database consistent.

Truncate table cannot be used with table having foreign key references. As the truncate command do not fire any triggers. If you want to use the truncate command with a foreign key, you need to first drop the index and then add it again after using the truncate table command.

Friday, May 18, 2012

Start debugging F5 does not build automatically, Visual Studio

I was facing this issue from a long time and every time I overlook this issue by manually building required projects. I also posted the issue on stack overflow community but did not get any successful answer (Stackoverflow link).

Issue: Many times it happen that while working on application development, you use edit and continue option i.e. you write code while application is in debugging mode (like you hit breakpoint and start writing code from there on). I'm assuming that you've enabled Edit and Continue option from Option -> Debugging -> Edit and Continue dialog box. Now when you stop application and try to run it again using F5 the edited file is no longer compiled automatically and your changes are not reflected. So generally in this scenario we need to manually build the project having edited file from the solution explorer. But this will be a huge bottleneck to your performance if you need to make changes frequently in debugging mode.

Solution: If you're like me i.e. in case visual settings are going out of your bound then simply reset all settings to default one then you must have tried devenv/resetsettings command in order to fix this problem. But this does not solve our problem actual fix is :
1. Open the "Configuration Manager" from the Debug/Release dropdown and verify that Build checkbox is checked for all of the projects you want to build.
2.  Open Visual Studio settings from Debug -> Option & Settings. Then Project and Solutions -> Build and Run . Now in drop-down for "On Run, where projects are out of date:" Select 'Always Build' instead of 'Never Build'.

Hope this will fix your problem. It worked in my case.

Wednesday, May 16, 2012

Is it difficult to switch technology from .NET to Java?

I woke up in the midnight and started to think about how much difficult it is to switch from .NET technologies to Java? I think basics would be same in both technologies so there should not be much hurdles. After all both are based on the concepts of Object-oriented programming. Still I request to my readers for their inputs on this topic. I will update any information that I found.

22 April '12 4:00 AM: I don't know why this question wont let me sleep comfortably. Last time when I was thinking about this resulted into insomniac and today also. There are plenty of things running in parallel related to this. The major factor which is invoking me to shift to Java is the fact that it is being used in almost all major application which are quite large in terms of scalability, responsibility and involving novel cross-platform dependencies. As much I've read, in Java you need to have a better framework and libraries understanding in order to get the stuff done also the big plus factor that it is an open-source language so you have very much bright chances to learn the stuff happening inside assemblies. Also one more factor, all big software giants use Java for their application development. I want to have a hands on such applications after all I love programming so why not go for real challenging tasks :).
But at the same time, I think I've around 3 years professional experience on .NET technologies and have learnt a lot from basics to advanced concepts. In fact gave training sessions to juniors too. So why not carry on learning advanced concepts in .NET itself instead of spending time in learning the basics of Java and then intermediate level learning? I believe being good in one is better than OK in two. Now here comes the confusion, both seems good to me. Also one more thing which I believe is get comfortable with uncomfortable. So again pushing me to learn Java. It would be difficult to switch technologies on the professional level as there will be great expectations from a 3 years experienced profession. But that's the challenge and I should happily accept it.

Stopping it here only as this is not something which can be decided in 5-10 mins. Perhaps I'll start learning Java from the advanced topics on the side track. 

Friday, May 11, 2012

Code references completed its 1K views (:

I would like to share a good news :) . Code references has completed its 1000 views today and am glad to know that this happen in a very short time-span. Started from 0 views/week, code references has 15-30 views/day traffic these days. Started from sharing the information that I collect from various website to explaining the tweaks with my own code, I will try to more and more new stuff on this blog in order to make code-references more better. Thanks to all readers, for your suggestions and regular views which motivated me to write more.Hope you perceive more knowledge in upcoming posts.

As I'm a newbie in blogging as well as in programming I used to share knowledge already present over the internet but collating all useful information is also necessary. So I'll try my best to share all new things that come across my learning pathway.

Update 8th September 2012: Code references has now crossed 3000 page views. Cheers

Happy Reading - Rohit Kandhal

Extension Methods ( IfNotNull methods), C#

As per MSDN, Extension methods enables you to "add" methods to existing types without creating a new derived type. They are a special kind of static method, but they are called as if they were instance methods e.g. <objectName>.<extensionMethod>( ).
Usage: Many times it happens that you want to check an object whether it is null or not before calling any of its instance method. e.g. if(parent != null) { parent.XYZ ( ); }. Now it would be better if you can simply write parent.IfNotNull ( x => x.XYZ ( ); );. Here IfNotNull is an extension method. Similarly you may wish to have a function which automatically converts first letter of a string to Uppercase, something like value.UppercaseFirstLetter( );

Implementation: Extension methods are static methods and generally you should place all static methods of your application in a separate class such as ExtensionMethods.cs. ExtensionMethod class should be a static class and all methods in this class should be public static methods. You can invoke these methods from any class in the same way as you can call instance methods. The extension method is called like an instance method, but is actually a static method. In fact the instance pointer 'this' is received as a parameter. You must specify the 'this' keyword before the appropriate parameter you want the method to be called upon.
Following code is the demonstation of InNotNull extension method.

public static class ExtensionMethods
      // Extension Method 1: IfNotNull
      public static U IfNotNull < T, U > (this T t, Func <T, U> function)
            return t != null ? function (t) : default (U);

       // Extension Method 2: UppercaseFirstLetter
       public static string UppercaseFirstLetter (this string value)
             if(value.Length > 0)
                   char[ ] array = value.ToCharArray( );
                   array [0] = char.ToUpper ( array [0] );
                   return new string (array);

1. IfNotNull extension method: Since this is a generic extension method i.e. it is on T, where T has no constraints, it is always available to any class or struct instance, much like Equals and GetHashCode. You'll notice that the IfNotNull method is only an obscure way to call the specified delegate on the instance, except that we check to see whether the instance is null, and don't call the delegate in that case, returning null.

2. UppercaseFirstLetter extension method: This method first checks if the string length is greater than 0 then converts first letter of that string to upper case.

Using Extension Methods:
1. Suppose you've a Child with Parent property and you want to get Name of its parent.
string parentName = child.Parent.Name;
In case either Child or Parent Name is null then you'd like the name variable to be null. You can achieve this as:
if (child != null)
        if(child.Parent != null)
               parentName = child.Parent.Name;

Now using the extension method you can simplify the above code as:
parentName = child.IfNotNull ( x => x.Parent ).IfNotNull ( x => x.Name);

Note that we're using lambda expression in the IfNotNull extension method making it least efficient so only use  it when you think that increased code clarity outweighs the performance loss.

2. Similar to above usage, we can use UppercaseFirstLetter method as:
string value = "myFirstLetterIsUpperCase";
value = value.UppercaseFirstLetter ( );

More Parameters: Extension methods can have many arguments other than the 'this' parameter that is required. You can even use variables 'params' arguments with extension methods, as with any method. Because extension methods are actually static methods, there is no significant performance difference between them and other methods.

Extension methods affect the syntactic representation of the source. They do not make the execution of the source code substantially different.

Sources: MSDN, Stackoverflow, DotNetPerls, Code logos, Brad Wilson.

Saturday, April 28, 2012

.NET Delegates explained

.NET delegate type is a type-safe, object-oriented, function pointer. A delegate dynamically wires up a a method caller to its target method. There are two aspects to a delegate: type and instance. A delegate type defines a protocol to which the caller and target will conform, comprising a list of parameter types and a return type. A delegate instance is an object that refers to one (or more) target methods conforming to that protocol.

A delegate instance literally acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method.

When you declare a .NET delegate, the C# compiler responds by building a sealed class that derives from System.MulticastDelegate which provide every delegate with the ability to maintain a list of method addresses, all of which may be invoked at a later time. A delegate type is declared/defined as:
public delegate int SpecialCalc( int x, int y);
Based on its definition SpecialCalc can point to any method taking two integers as arguments and returning an integer. Once compiled the defining assembly contains a class definition that is dynamically generated when you build your project, based on the delegate declaration. In above case this class looks like:
public sealed class SpecialCalc : System.MulticastDelegate
           public SpecialCalc ( object target, uint functionAddress);
           public void invoke (int x, int y);
           public IAsyncResult BeginInvoke (int x, int y, AsyncCallback cb, object state);
           public int EndInvoke ( IAsyncResult result );
Invoke method: this method is used to invoke the methods maintained by a delegate object in synchronous manner. Therefore the calling thread i.e. primary thread of the application, is forced to wait until the delegate invocation completes. Also note whenever you call any method in C#, it's called by Invoke method bydefault so you don't need to deliberately use Invoke method. For example, consider the following delegate instance declaration
Class Test
       static void Main()
           //Create delegate instance, could be write as = new SpecialCalc(SpecialSum);           SpecialCalc sc = SpecialSum;
           // Invoke Special Sum() in a synchronous manner. Could be write as sc.Invoke(3,4);           int result = sc(3,4);
            Console.WriteLine (result);           //  10       }
       static int SpecialSum ( int x, int y)
           // Pause to simulate a lengthy operation           Thread.Sleep(5000);
            return 2x + y;
 Within the SpecialSum() method, we are invoking Thread.Sleep() method to suspend the calling thread for approximately five seconds to simulate a lengthy task. As you are invoking the SpecialSum() method in a synchronous manner, the Main() method will not print out the result of the operation until the SpecialSum() method has been completed.

Although we made SpecialSum method a lengthy operation deliberately but it might be possible that you actually create a task which takes that much amount of time. While performing such operation (on main thready or synchronously) the application will appear to hang for some amount of time. Until this lengthy operation is completely processed, all other aspects of application such as menu activation, toolbar, console output, mouse click are unresponsive. Thus you should tell a delegate to invoke a method on a separate thread of a execution in order to avoid blocking all other aspects of application. Fortunately every .NET delegate type is automatically equipped with this capability.

BeginInvoke() and EndInvoke() methods: As we discussed earlier, when you declare a delegate its delegate class contains following two methods whose syntax is as under:
public IAsyncResult BeginInvoke(int x, int y, AsyncCallback cb, object state);
// used to invoke a method asynchronously.public int EndInvoke (IAsyncResult result);
// Used to fetch the return value of the invoked method.
 First stack of parameters passed into BeingInvoke() will be based on the format of the delegate, in our case SpecialCalc accepts 2 parameters that's why I mentioned two parameters. Last two parameters will always be System.AsyncCallback and System.Object.

IAsyncResult Interface: The BeginInvoke method always returns an object implementing the IAsyncResult inteface while EndInvoke() requires an IAsyncResult type as its sole parameter. The IAsyncResult object returned by the BeginInvoke() method is basically a coupling mechanism that allows the calling thread to object the result of the asynchronous method invocation at a later time via EndInvoke().
IAsyncResultInterface is defined as follows:
public intefact IAsyncResult
     object AsyncState {get;}
     WaitHandle AsyncWaitHandle { get; }
      bool CompletedSynchronously { get; }
      bool IsCompleted { get; }
}  // All of these members are explained below
In order to call SpecialCalc delegate asynchronously, you just need to modify the delegate invocation call from invoke to BeginInvoke so now your main method will look like
Class Test
     static void Main()
     SpecialCalc sc = SpecialSum;
     // Invoke Special Sum() in an asynchronous manner.
     IAsyncResult iasyncR = sc.BeginInvoke(3,4, null, null);
     // Do other work on primary thread and obtain the result of SpecialSum() when ready
     int result = sc.EndInvoke( iasyncR );
     Console.WriteLine (result); // 10
static int SpecialSum ( int x, int y)
     // Pause to simulate a lengthy operation
     return 2x + y;
When you run this code block you'll notice that there would be two threads one primary thread and other thread working on delegate operation. Your application won't be unresponsive this time, after invoking delegate you can carry on further operation and after performing them you can call EndInvoke() which will provide you the delegate method result.
Now suppose you did something after calling BeginInvoke method i.e
IAsyncResult iasyncR = sc.BeginInvoke (3,4, null, null);
DoThisHeavyOperation(); //Some other method int result = sc.EndInvoke ( iasyncR );
In above case if DoThisHeavyOperation method takes less than 5 seconds then again main thread will be blocked waiting for delegate to complete (i.e. EndInvoke call). Thus in order to overcome this big problem IAsyncResult interface provides the IsCompleted property. Using this member the calling thread is able to determine whether the asynchronous call has completed or not. If the method has not completed, IsCompleted returns false and the calling thread is free to carry on any other task. For example we can tweak above delegate invocation as:
IAsyncResult iasyncR = sc.BeginInvoke ( 3, 4, null, null);
DoThisHeavyOperation();  // Some other workwhile( !iasyncR.IsCompleted )    // Check whether delegate method is completed{
      // Do some other work till delegate is not completed}
// Delegate has finished its method, fetch result from EndInvokeint result = sc.EndInvoke( iasyncR );
In addition to the IsCompleted property, the IAsyncResult interface provides the AsyncWaitHandle property for more handling wait logic more smartly.
WaitHandle AsyncWaitHandle { get; }
AsyncWaitHandle returns an instance of WaitHandle type which exposes a method name WaitOne( ) using this method you can specify the maximum wait time. If the specified amount is exceeded, WaitOne( ) returns false. So you can replace the IsCompleted property implementation with WaitHandle as:
while ( iasyncR.AsyncWaitHandle.WaitOne ( 1000, true) )
           // Doing some other work} 
Although the above mentioned property does provide the way to synchronize your delegate call and main thread still its not a efficient approach.

Delegates with AsyncCallback: As we see above we keep on asking a delegate whether the asynchronously invoked method has completed or not, it would be more efficient to have the secondary thread inform the calling thread when the task is finished. To add such functionality to your delegate you need to pass an instance of the System.AsyncCallback delegate as a parameter to BeginInvoke( ) method. As soon as the asynchronous call will get completed, this AsyncCallback delegate will be invoked. Lets discuss about how these AsyncCallbacks are used with delegate.

As delegate type has specific syntax, AsyncCallback can only invoke methods having a specific pattern, which is a method having IAsyncResult as the sole parameter and returning nothing. i.e.
Notice the diffence between AsyncCallback & IAsyncResult spell.
void AsyncCallbackMethod ( IAsynchResult iasyncR)
Using AsyncCallback: Now create a new method with the syntax described above and which you want to execute after asynchronous method completes. Suppose in our example you we want to do another operation after SpecialSum operation is completed so create a new AsyncCallback to do that.
static void SpecialSumCompleted ( IAsyncResult iasyncR)
Console.WriteLine ("Special Sum operation completed and AsyncCallback is working");
// Invoking another special operation after SpecialSum is completedDoAnotherSpecialOperation( );
// Note that here I can't print the result of Special Sum method as that is not accessible here.}
The SpecialSumCompleted callback does not print the actual result of SpecialSum operation as the AsyncCallback delegate (SpecialSumCompleted) does not have access to the original SpecialCalc delegate created in the Main( ) scope and thus you can't call EndInvoke from within SpecialSumCompleted ( ). However there is a workaround for this problem which I'll discuss later.

This article is something which I used to read from couple of textbooks so noted down the excerpt here and will refer to it in future. Delegates and events are very interesting & useful topic in C# programming.

Wednesday, April 25, 2012

Datatrigger not updating control property, WPF

Have you ever noticed that if you try to modify a property in data trigger which is already specified in the control itself then data trigger won't have any effect even when data trigger conditions are met. Consider the following use case in which you've a textbox and a trigger defined on that.
<TextBlock x:Name="My TextBlock"
                  Text="Default Value">
          <Style TargetType={x:Type TextBlock}>
                <DataTrigger Binding="{Binding PropertyA}"
                <Setter Property="text"
                            value="Updated Value"/>
In above example even if PropertyA becomes true then text of the textblock will remain "Default Value" instead of "Updated Value".
Fix: In order to work it properly, you need to specify the "Default Value" in style not with the control. Here is the xaml:
<TextBlock x:Name="My TextBlock">
          <Style TargetType={x:Type TextBlock}>
          <Setter Property="text"
                      value="Default Value" />
                <DataTrigger Binding="{Binding PropertyA}"
                <Setter Property="text"
                            value="Updated Value"/>
 Above xaml will work perfectly. :). Still need to dig up the reason why data trigger behaves this way only.

Reusable comparison converter

Tuesday, April 24, 2012

'String' object cannot be added to ComboBox, WPF

Friends If you got stuck with this error while working on your WPF project then you'll absolutely smile after reading this post.

I was working on a task which involved creating new ComboBox and several complex binding and all but after some time I got stuck with an exception which was:
{"'String' object cannot be added to 'ComboBox'. Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.  Error at object 'System.Windows.Controls.ComboBox' in markup file '<Project Name>;<ComponentName>' Line 3180 Position 108."}
 And I spent nearly 4-5 hours to debug this issue, moreover you need to dig up in order to come to the conclusion that this is the exception which is causing issue to you and after lots of researching over net (which in fact dint give me a single link about this exception) I called up my colleague and he just saw my code and smiled- in fact I also smiled as soon as we both started to look into the code.
<Combobox x:Name="abcMyCombo"
                   .... Many other properties
 I hope you've just found the issue with it :). In case not notice >> in the end, Combobox was trying to add this as a string + its itemsource. I'll be more careful next time while writing xaml. Funny isn't?


Monday, April 2, 2012

Publish what you learn !!

Today I come across a very nice article by Louis Lazaris in which it is encouraged that one should publish whatever he learns. Here is a brief about that article:

  1. When you learn something, write about it, and don’t do it just to make money off it.
  2. Don’t be afraid to make mistakes.
  3. Teaching others will help you learn.
  4. Encourage collaboration by allowing a free flow of constructive comments.
  5. If you make a mistake, fix it.
I would encourage everyone to read the entire post, specifically for the people who generally don't post/publish over web much. It would surely change your thoughts about blogging.

Hope you enjoy it.

Friday, March 30, 2012

Priority Binding, WPF

Consider a scenario in which you've a base class A and there are two classes B & C derived from the class A. Also base class A has a virtual property named 'DisplayName' which represents the name of object of that class (Insignificant what it does). Now you want to show this DisplayName on UI, say in a textbox.
Simply setting Text = "{Binding DisplayName}" can serve this purpose. Quite Simple

Now say class B has a particular type and for that instead of showing DisplayName you need to use DisplayNameSpecific property. How you will achieve this?

Problem: How to specify two binding sources for a simple binding and use the one which holds priority.
We can do this by using Converters, in converter we can check if the current object type is of Class B then show DisplayNameSpecific else use DisplayName. It will work smoothly but there is one more smarter way to achieve this, wiz Priority Binding

Priority Binding:
MSDN defines it as: Priority Binding class describes a collection of binding objects that is attached to a single binding target property, which receives its value from the first binding in the collection that produces a value successfully. PriorityBinding lets you associate a property with a list of bindings. The first binding that returns a value successfully becomes the active binding.

The value DependencyProperty.UnsetValue is not considered a successful return value.

NOTE: The binding engine continues to listen for changes on all bindings. If at any point one of the bindings that has a higher priority returns a value successfully, the value for that binding becomes the active value and replaces the current value.

Thus in our example we'll do something like:
                    <Binding Path="DisplayNameSpecific" />
                    <Binding Path="DisplayName"  />

That's it. :)

Wednesday, March 28, 2012

Creating a hyperlink with both text and link, WPF

[WPF, C#] We generally use hyperlink in order to navigate to certain URL but have you ever wonder how you'll display a string with hyperlink in it? E.g. In help menu of your application, you need to show something link "For more information please contact 123-456-7890 or email". In this string, 'email' is a hyperlink, clicking on which open the outlook.

There is no simple or built in control for such thing and even you can't do this by clubbing text & hyperlink together in a grid. Here is a workaround to achieve this in code behind of your XAML file.

Add a hyperlink in xaml and don't specify it's text/content there, instead the content is specified using code behind in constructor of that usercontrol.

// string you need to show on GUI
string contactSupport = "For more information please contact 123-456-7890 or email";
// place holder constant. Content which you want to create hyperlink
const string EMAIL_PLACEHOLDER = "email";
string[] stringSeparators = new string[] {EMAIL_PLACEHOLDER };
// create hyperlink which will be called on clicking 'email'
Hyperlink hyperlink = new Hyperlink(){ 
NavigateUri = new URI("mailto: technicalsupport@abc.com")
// text to show for hyperlink content. Email here
hyperLink.RequestNavigate += Hyperlink_RequestNavigate;

// hyperlink created now you need to break the text string into two string one will be displayed as simple text and another will be hyperlink.
string beforeText = contactSupport.Split(stringSeparators, StringSplitOptions.None)[0];
string afterText = contactSupport.Split(stringSeparators, StringSplitOptions.None)[1];
//Now you've both text and hyperlink add them in the hyperlink which you've created in xaml
// 1. First part of text is added to that hyperlink. It will be displayed as simple text
this.supportHyperlink.Inlines.Add(new Run(beforeText));
// 2. Add hyperlink
// 3. Add any other text, if any you want to add after the hyperlink.
this.supportHyperlink.Inlines.Add(new Run(afterText));

Now, you're ready to use the hyperlink with both simple text & hyperlink.

Friday, March 23, 2012

Viewing contents of a DataSet or DataView in quick watch, C#

[Visual Studio] Have you ever faced any issue in visualizing the contents of a dataset while debugging a problem in Visual Studio? Generally we've a habit of  viewing the contents of a collection while debugging a particular problem but you can't do the same with DataSet. Here is a quick tip to view DataSet contents in QuickWatch.

Visual Studio Visualizers
This is what MSDN says about visualizers: A visualizer creates a dialog box or another interface to display a variable or object in a manner that is appropriate to its data type. For example, an HTML visualizer interprets an HTML string and displays the result as it would appear in a browser window; a bitmap visualizer interprets a bitmap structure and displays the graphic it represents. Some visualizers enable you to modify as well as view the data.
The Visual Studio debugger includes five standard visualizers.
1,2,3. The text, HTML, and XML visualizers, all of which work on string objects;
4. the WPF Tree visualizer, for displaying the properties of a WPF object visual tree;
5. the dataset visualizer, which works for DataSet, DataView, and DataTable objects. This is the one we should use in order to solver our problem.

Visualizers are represented in the debugger by a magnifying glass icon. When you see the magnifying glass icon in a DataTip, in a debugger variables window, or in theQuickWatch dialog box, you can click the magnifying glass to select a visualizer appropriate to the data type of the corresponding object.

Following figure will explain the way to use it:

Also note that: Visualizers are not supported on the Compact Framework.

Friday, March 16, 2012

Assigning a dynamic resource link programmatically

In XAML, you can specify whether a resource is static resource or dynamic by using the StaticResource and DynamicResource with binding. Also if you want to do this thing pro grammatically (in C#) then static behavior is simple. You just need to find the resource using TryFindResource() method and set the desired property of it. But if you want to have it dynamically updated then use SetResourceReference() method.

frameworkElement.SetResourceReference( dependencyProperty, resourceKey );


TFS: Compare with workspace version

Microsoft's Team Foundation Server provides different ways to compare your edited file with different versions. Among them are:
1. Unmodified Version
2. Workspace Version
3. Latest Version

Option 1 & 3 are self-explanatory however it is worth noticing the difference between WorkSpace version & Latest version.
WorkSpace version VS Latest Version
Comparing with workspace version actually compares the edited file with the version of file at the time you checked out. But comparing with latest version compares the edited file with latest version of file present at your code repository i.e. it might include changes made by your colleagues.

E.g. Say you check out a file on 1st november and did some changes till 3rd november. Now on 3rd november if you try to compare your edited file with Workspace version tfs will compare the edited file with the file present in tfs on 1st november (i.e. the time at which you checked out the file). It might be possible that your fellow colleagues made some changes to that file till 3rd november. So comparing the edited file with latest file with show those changes, basically it will compare the edited file with the latest version of that file.

In most of the scenario, programmers work on latest code (and it's a good practice that you atleast take latest code once in a day) that's why both option results in same output.

Thursday, March 15, 2012

Why and how you should create flexible applications?

What is a loosely couple application? Ever wonder why design architects always try to enforce application design to be loosely coupled even when you are confident that you can write a bug free app?
We should not develop an app which is completely loosely coupled. How you should evaluate the measure of coupling your application have and does it needs improvement or not?
What are the benefits of loosely couple application?

To answer here is a very good post by James Kovacs :Tame Your Software Dependencies for More Flexible Apps.

Link for detailed explanation of design pattern to use for building flexible composite application (very nice article, I would say must read for programmers working on windows application development) : Prism : Patterns For Building Composite Applications With WPF

Happy Reading.

Instantiating a view model in view (XAML)

You can create an instance of viewmodel in view (XAML) in order to create data binding at design time for a data context that is assigned at run time using DESIGN INSTANCE.

Syntax: d:DataContext="{d:DesignInstance Type=local:ABC}"

More information about it on MSDN article : Click here

Wednesday, February 22, 2012

Is WPF purely case-sensitive?

What do you think about case sensitivity of WPF?
At first glance, your answer might be YES, it is case-sensitive. But if this has to be true then how come width="auto" & width="Auto" both works fine? On the other hand if is case-insensitive then why do controls don't accept 'width' as its property? You can define the width of a control only using 'Width' (Capital W).

Well the answer is it is partly case-sensitive.

From the MSDN:
XAML is generally speaking case sensitive. For purposes of resolving backing types, WPF XAML is case sensitive by the same rules that the CLR is case sensitive. Object elements, property elements, and attribute names must all be specified by using the sensitive casing when compared by name to the underlying type in the assembly, or to a member of a type. XAML language keywords and primitives are also case sensitive. Values are not always case sensitive. Case sensitivity for values will depend on the type converter behavior associated with the property that takes the value, or the property value type. For example, properties that take the Boolean type can take either true or True as equivalent values, but only because the native WPF XAML parser type conversion for string to Boolean already permits these as equivalents.
Excerpt: Instead of saying WPF is case-sensitive, we can say that XAML IS case-sensitive but the property values are not always case dependent. It depends on property value converter. That's why both 'Auto' and 'auto' works, although in some special cases the property converter might not be able to handle them with case-insensitivity. In other words, you can say that property names are case-sensitive; however, property values might not be case-sensitive.

Sources: MSDN, Stackoverflow.

Monday, February 13, 2012

Solution Platforms and Configurations

UPDATE: Earlier this blog post was big and have my inputs too but majorly the intent was from visual studio hacks link. Now I've removed that and suggest you to go directly to this link http://visualstudiohacks.com/articles/visual-studio-net-platform-target-explained/. They have explained it very nicely.

Team Build deals with solution configurations - these are the platforms (e.g. .NET or Win32) and configurations (e.g. Debug or Release) you typically see in combo boxes within Visual Studio when you have a solution loaded (if you hover over these boxes the tooltips will say "Solution Platforms" and "Solution Configurations", respectively).

Thursday, February 9, 2012

Reset Visual Studio to default settings

Use "devenv /resetsettings" command to reset your Visual Studio settings to default one as it comes when you install a fresh copy of VS.

Thursday, February 2, 2012

Migrating a shelveset from one branch to another

Are you working on an application development which follows code branching strategy in order to deliver timely product releases? If yes, then you might need to merge a shelveset from one branch to another. Here are the simple steps to do the same.

1. Visual Studio 2010
2. Team Foundation Server power tools 2011. Link To Download

Steps to follow:
TFS Power Tools provides the ability to migrate a shelveset, but with the limitation that you can use this feature only through command line.
1. Quick link to open Visual Studio command prompt is press Windows key and type "Command" in search box.

2. "tfpt unshelve" is the command provided by power tools for code migration and that's all you need to know. To get a brief overview about the command type "tfpt unshelve /?" in command prompt.

Quite simple, you just have to use the command as mentioned in usage. However, you need to take care of the source and target branch path. 

3. Simple Rule:
I'm assuming that both source and target branch are under the same folder say "Gulliver" here and branch hierarchy is "Gulliver/Code-branch-1", "Gulliver/Code-branch-2". You have created a shelveset in code-branch-1 and want to migrate it to code-branch-2. Also, your solution lies in Code-branch-1, Code-branch-2 folder.

Change your command prompt directory from default one to the both branch common folder, Gulliver here. Thereafter your command to migrate will be:

tfpt unshelve "<shelveset name>";<developername> /migrate /source:"<source branch solution path>" /target:"<target branch solution path>"

e.g. : tfpt unshelve "demo_shelveset";rkandhal /migrate /source:"$/Code-branch-1" /target:"$Code-branch-2/"

Note: Few imp points worth noting,
1. In above command $ in source/target path represents the root directory of your TFS repository. So take care of both paths considering their hierarchy in tfs.
2. You may receive an error entitled: "Unhandled exception has occured in a component in your application. The path 'adbcadsfasdf' contains the character ';'. Remove the ';' and try again." This issue happens because of wrong target  branch path. Provide the target branch path somewhat similar to "$/branch-2/"  - no colon in the end.

Thats it, you are done. On command execution, if your code is password protected, then you will be prompted for TFS password then Unshelve dialog will open and you're required to select the shelveset which you want to merge. There after auto-merge dialog prompts up and in case you have not provide the correct target branch path, resolution will results to an error otherwise your code changes will be merged to target branch. Here is the snapshot of command output:

Notice that for each file there is a result status in command window.