Sunday, September 29, 2013

Pass complex object to Web API in MVC

ASP.NET Web API is one of the most powerful recent addition to ASP.NET framework. Sometimes, you have to post a form data using jQuery-JSON to Web API or MVC method, which have so many input fields. Passing each and every input field data as a separate parameter is not good practice, even when you have a strongly typed-view. The best practice is, pass a complex type object for all the input fields to the server side to remove complexity.

Let us know- how to pass complex types object to the Web API and MVC methods to remove complexity at server side and make it simple and useful with the help of this example.

Model Class

Suppose you have the following Product class and repository for product.
public class Product
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }

interface IProductRepository
Product Add(Product item);
//To Do : Some Stuff

public class ProductRepository : IProductRepository
private List<Product> products = new List<Product>();
private int _nextId = 1;

public ProductRepository()
// Add products for the Demonstration
Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });
Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });
Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });

public Product Add(Product item)
if (item == null)
throw new ArgumentNullException("item");

// TO DO : Code to save record into database
item.Id = _nextId++;

return item;
//To Do : Some Stuff

View (Product.cshtml)
<script type="text/javascript">
//Add New Item by Web API
$("#Save").click(function () {

//Making complex type object
var Product = {
Id: "0",
Name: $("#Name").val(),
Price: $("#Price").val(),
Category: $("#Category").val()

if (Product.Name != "" && Product.Price != "" && Product.Category != "") {
//Convert javascript object to JSON object
var DTO = JSON.stringify(Product);
url: 'api/product', //calling Web API controller product
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: DTO,
dataType: "json",
success: function (data) {
function (xhr, textStatus, err) {

else {
alert('Please Enter All the Values !!');


<h2>Add New Product</h2>
<label for="name">Name</label>
<input type="text" id="Name" title="Name" />

<label for="category">Category</label>
<input type="text" id="Category" title="Category" />

<label for="price">Price</label>
<input type="text" id="Price" title="Price" />
<br />
<button id="Save">Save</button>
<button id="Reset">Reset</button>

Web API Controller
public class ProductController : ApiController
static readonly IProductRepository repository = new ProductRepository();
public Product PostProduct(Product item)
return repository.Add(item);

Difference between shadow and override inheritance in c#

Let's know the solution of following questions
Ques: What is difference between shadow and override inheritance in c#
Ques: Shadowing and Overriding in C# dot net
Ques: Inheritance features in C# dot net 
"Shadowing and overriding are both used when a derived class inherits from a base class, and both redefine one declared element with another. But there are significant differences between the two"
When you extend a class, you shadow fields with the same name in the base class and override virtual methods with the same name and parameter list in the base class. Overriding makes the base class method invisible. Shadowing a field only hides the field from view. You can still explicitly touch the hidden shadowed field if you wish. You can't touch an invisible overridden method.

class Base
        public void PrintOnScreen()
            Console.WriteLine("Base Method");
    class Derive : Base
        public new void PrintOnScreen()
            Console.WriteLine("Derive Method");
    class MethodShadowingDemo
        public static void Main(string[] args)
            Base objDerive = new Derive();

  • The calling sequence consists of the element type (FunctionSubOperator, or Property), name, parameter list, and return type. You cannot override a procedure with a property, or the other way around. You cannot override one kind of procedure (FunctionSub, or Operator) with another kind.
  • If you do not specify either Shadows or Overrides, the compiler issues a warning message to help you be sure which kind of redefinition you want to use. If you ignore the warning, the shadowing mechanism is used.
  •  If the shadowing element is inaccessible in a further derived class, shadowing is not inherited. For example, if you declare the shadowing element as Private, a class deriving from your derived class inherits the original element instead of the shadowing element.

Saturday, September 28, 2013

Difference between dynamic and object keywords in C# dot net

Let's have a look on answers of following queries

We have two similar type of variables in C# sometimes we get confuse that which one in better with optimization point of view and which type of variable should used where.
Let’s have a look now at object keyword first. I’m not going to talk a lot about it because it’s been around since C# with old versions while dynamic introduced with later version of C# 4.0. Object keyword is nothing more than a shortcut for System.Object, which is the root type in the C# class hierarchy. and as we know everything in C# derives from object. so you can assign almost any value to instances of this type.

Examples How and When to use Object keyword 
Here is a short example that demonstrates some of the benefits and problems of using the object keyword.
object obj = 10;

// Prints System.Int32 because 
// this is the type of the value stored in this object.

// A compiler error, because 
// at compile time the type of obj is System.Object.
// obj = obj + 10; 

// You need to explicitly cast obj to a necessary type.
obj = (int)obj + 10;

// However, this does not mean that you are really safe. 
// You can cast to a wrong type 
// and the compiler will not detect it. 
// Here you get an exception at run time, 
// because obj is an integer, not a string.
// obj = (string)obj + 10;

// You also get a run-time exception 
// if you cast to a wrong numeric type, 
// even if there is an implicit conversion in the language.
// obj = (double)obj + 10;
As you can see, although obj stores an integer, the compiler does not let you to perform any mathematical operations without a cast. It may look like casting helps you to ensure that you really have an integer, but it doesn’t. You can cast to a completely different type and the compiler will not detect it. As a result, you get a run-time exception.
So you have to perform an explicit cast that does not guarantee anything just because the compiler doesn’t let you to run your program without a cast.

Examples How and When to use Dynamic keyword
Here is where the new dynamic keyword in C# 4.0 comes in. It tells the compiler not to enforce additional rules upon your code.

dynamic dyn = 10;
// Same as "object". 
// Prints System.Int32 because 
// this is the type of the value stored in this object.

// No compiler error, because 
// the compiler does not try to identify 
// the type of the dynamic object at compile time.
dyn = dyn + 10;

// Also, this operation will succeed for all numeric 
// or other types that support a “+” operation.
dyn = 10.0;
dyn = dyn + 10;

dyn = "10";
dyn = dyn + 10;
This is one of the main differences between object and dynamic – with dynamic you tell the compiler that the type of an object can be known only at run time, and the compiler doesn’t try to interfere. As a result, you can write less code. And I want to emphasize that this is no more dangerous than using the original object keyword. However, it is not less dangerous either, so all the type-checking techniques that you need to use when operating with objects (such as reflection) have to be used for dynamic objects as well.
The next question that often comes up is something like the following: “Since a dynamic object can be anything and the compiler doesn’t check what it is, does it mean that you can pass a dynamic object to my unsuspecting method/system and make it crash?”
Let’s assume we have a simple method.
public static void Print(string arg)
Now let’s look at how you can pass a dynamic object to it.
dynamic dyn = 10;

// You get an exception at run time here.
As you can see, although the compiler allows you to pass a dynamic object to your method, your method never gets this object if it has a wrong type. An exception is thrown before the method is actually called. The only way you can pass a dynamic object to your method is if it contains a necessary value, in this case, a string.
dynamic dyn = "10";
Again, this is not that much different from the behavior you get with the object keyword.
object obj = 10;

// Doesn't compile.

// Compiles, but there is an exception at run time.

// This code works because obj is now a string, 
// but you still need a cast.
obj = "10";
Some people say that it isn’t hard to read (int)obj, so why bother with dynamic? Well, there are situations when you have to perform so many cast operations that it makes your code almost unreadable.
Also, the dynamic keyword and dynamic language runtime enable many scenarios that were either impossible or difficult to do before, including interoperation with dynamic languages.
So, if you often use the object keyword and have to perform a lot of casting and/or use reflection to call methods and properties of objects, you probably should take a look at the dynamic keyword. In some cases it’s more convenient than object and with less code to write.
Hence, he conclusion is that there is no need to fear that someone can break your code by using dynamic features. It is no more (and again, no less) dangerous than the object keyword.

Friday, September 27, 2013

No new feature added to VB and C# in Visual Studio 2013- Says MSDN Team

Bofore some days I had a curiosity that what new features are added with C# and VB dot net in Visual Studio 2013 new version. I browsed from MSDN and got this surprised information  about the new version changes in VS 2013.

Let us have a look what says MSDN community-
 "As you can see in the VS2013 Preview, we have not added new language features to C# and Visual Basic in the next version of Visual Studio. I’d like to share our thinking on this. There are essentially two main reasons why we chose not to evolve the languages this time around."

The most important is that we just shipped new versions of these two languages less than a year ago, with support for asynchrony being a major new and impactful language feature in both. Developers are still learning how to integrate and benefit from the asynchrony shift in languages and APIs. We are very excited about the quicker pace of release for VS, but we believe from experience that language versions need a little more time to settle in. Our current thinking therefore is that C# and Visual Basic should stay closer to the pace they have been on for the past decade. It’s a balance between providing stability and new value, and we feel like we already have that balance about right.

Download Visual Studio 2013 Free Version
Install and try Visual Studio 2013 today and seize the future of development.
To download VS2013 click here
There is a more tactical reason for us as well, which is that we are nearly done reimplementing the compilers and language services for C# and Visual Basic from the ground up. You may have heard of this effort as the Roslyn project, and there will be many end user benefits to this work when it ships. From our internal perspective on the language team, the new infrastructure makes it vastly easier to implement and test new language features with confidence, quality and great tooling. While the old compiler infrastructure is rock solid and supports VS 2013 beautifully, any effort we spend implementing new language features on it takes away from investing in the tooling, language features and compiler APIs that will power the future.
Download Visual studio 2013-new features

We are actively working on the next versions of C# and Visual Basic. The language design team is in full gear, led by Anders Hejlsberg as usual, and we are considering lots of new language features, big and small. We are looking very much forward to sharing more details about this work as the ideas mature, and to ultimately ship these new language features in a future version of Visual Studio.

How Requests Are Processed by the Thread Pool
How Requests Are Processed by the Thread Pool

Tuesday, September 24, 2013

Disable laptop's built-in keyboard to use an external USB keyboard

Let us find the solution of following questions
Que: How to change your laptop keyboard step by steps?
Que: Laptop KeyBoard not working problem
Que: Laptop Keyboard keys working automatically issue
Que: How can I disable my laptop's built-in keyboard  to use an external USB keyboard?

Hurray !!! Now get the solutions

Disable laptop keyboard to use an external USB keyboard
Solution 1: It will help you to disable your laptop keyboard by uninstalling your keyboard driver.
  •         Go to Start–>Search type in gpedit.msc
  •         Click the file to open the Local Group Policy Editor and show Windows who is in control!! You want to go here: Computer Configuration->Administrative Templates->System->Device Installation. Click on the sub folder Device Installation on the left and on the right side you will see the possible restrictions.
  •         Right Click on Prevent Installation of Devices not described by other policy settings and edit this option, set it on ENABLED.
  •         Reboot Windows and enjoy its inability to pollute your system with its standard driver, open gpedit.msc again and revert the change so you will be able to install your driver.

Solution 2: This is shortest as well  easiest way
Please go to C:\Windows\System32\Drivers\.... You will see some files start with kb, change kbfiltr to kbfiltr_del. And you will have done it.

This will disable laptop keyboard. At the moment, Now use USB keyboard and there is no problems for keys anymore.
Disable your laptop's keyboard to use an external USB keyboard
For more information and to change your laptop keyboard step by steps, read my next post...

Sunday, September 22, 2013

How Requests Are Processed by the Thread Pool

Let us know the answer of following questions.
Ques: How requests are processed by the thread pool?
Ques: What is HTTP 503 Error?
Ques: What is thread starvation in ASP .Net

Http 503 errorOn the Web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request. 

Thread Starvation & HTTP 503 Error
This might not be a problem, because the thread pool can be made large enough to accommodate many blocked threads. However, the number of threads in the thread pool is limited. In large applications that process multiple simultaneous long-running requests, all available threads might be blocked. This condition is known as thread starvation. When this condition is reached, the Web server queues requests. If the request queue becomes full, the Web server rejects requests with an HTTP 503 status (Server Too Busy).

Some Common Errors While We Use ASP .Net Controls

DropDownList.ClearSelection() to avoid "Cannot have multiple items selected in DropDownList"

ListItem item = DropDownListTest.Items.FindByValue("Test");
  if (item != null)
     item.Selected = true;


dropDownList.Items.FindByValue(myValue).Selected = true;

Tuesday, September 3, 2013

Set Expiration Time for your Tweets twitter feeds

Some times we need to display our tweet for a short period suppose, if you are sharing a discount coupon code that is set to expire in an hours OR some days, your tweet could still appear in the timeline of followers who happen to login the next day though that offer would have definitely expired.

Example- I have a coupon for Snapdeal website that is valid till next two from today So I am rating a tweet that will be automatically deleted when the deal coupon expires. It's a real coupon code so you can use it before 5th, Sep, 2013.

How to delete tweets after a given time days

Pierre Legrain, who was previously product marketing manager at Twitter, offers a very simple solution to this problem in the form of Spirit. You can set an expiration time for your tweets with the help of hash tags and the tweet will self-destruct after that time has passed.

To get started, you need to log into Spirit with your Twitter account and grant read & write permissions to the app. That’s it. The app will work behind the scenes and monitor your Twitter timeline for any time-sensitive tweets. If it finds one, the tweet will be automatically deleted after the set amount of time as specified by you in the hash tag.

It means You can use hash tags like #12m (for 12 minutes), #2h (for 2 hours) or #5d for tweets that are to be auto-deleted after 5 days. You can post tweets from the web, from your phone or even through an email message and Spirit will find it as long as you have added the hash tag in the correct (#\d+[mhd]) format.

Note : If you ever wish to pause or disable Spirit from deleting your tweets, just go to your Twitter account settings page and revoke access to the app.

Sunday, September 1, 2013

Importance of Digital Media Agency in Businesses

"In this day and age, a lot of people are using the internet to look for information, products, and services that they need because they find it very convenient. Based on recent reports, almost 90% of consumers shop online that’s why many business proprietors have decided to put up an online business. Before you manage an enterprise in the digital arena, you have to make sure that you know how to compete with your numerous rivals. Keep in mind that the competition is tough. Therefore, you should realize that you need a back-up in order to beat the global competition"

What type of agency do you need?

Before you create a website for your enterprise, you have to understand the importance of online marketingservices first. In order to have a competitive edge in the online world, you should find a reputable and outstanding digital media agency. It is the agency that you should hire because they specializeson online marketing services like SEO (Search Engine Optimization), PPC (Pay Per Click), Social Media & Web Design.
By working together with a competent digital media agency, reaching your business goals will become easy and fast. Remember that the power of digital has progressively grown in stature with the help of innovative technological products like computers, digital televisions, radios, and many more. This is the one you need to make your business’ future become brighter than ever.

What is a digital agency?

It is an online company that specializes in web-related services. It is a group of professional online marketers and web developers. They have the skills and expertise regarding online social networking, marketing, and other related tasks. They alsodesign and build functional websites for their clients.
If your business doesn’t have online presence yet, then hiring an online marketing company is the solution. By employing a competent digital agency, you will see great results in your online marketing campaign projects. You will surely get your money’s value when you let the experts do the complex marketing tasks. Their experience gives you guaranteed desirable results. They know how to deliver and execute a comprehensive online marketing campaign.

How to choose the right online marketing company?

Digital agencies play a vital role in helpingonline businesses in their marketing needs. That’s why they are considered as significant entities in the online world. However, not all of them offer the same quality of services. You should know how to choose the right agency for your firm’s advantage. Choose the one which has a good reputation when it comes to providing online marketing services.
Author : Anne Barrios

Powered by Code Imagine