Showing posts with label Programming interview questions. Show all posts
Showing posts with label Programming interview questions. Show all posts

Monday, November 24, 2014

Can we overload MVC controller action methods? (MVC Polymorphism)

This Saturday and Sunday when i was taking MVC class in Mumbai one of the participants asked this weird question, Can we overload MVC action methods?. This question was asked to him during a MVC interview recently.

For moment I wondered why interviewer such kind of questions which does not test anything about programmer's ability. But let's leave that argument from some other day and lets answer this question.

Well the answer is YES and NO depending on your expectation. Now before you turn me in to a politician who answers from both side's let me explain you why i have given such kind of a dubious answer.

Overloading or in other words polymorphism is a feature of object oriented programming. So if you have some kind of a below controller code which has methods overloaded with same name and different argument's it would compile very well.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

publicActionResultLoadCustomer()
        {
return Content("LoadCustomer");
        }
publicActionResultLoadCustomer(string str)
        {
return Content("LoadCustomer with a string");
        }
    }
But now if you are thinking that when you call "http://localhost:3450/Customer/LoadCustomer/" it should invoke "LoadCustomer" and when you call "http://localhost:3450/Customer/LoadCustomer/test" it should invoke "LoadCustomer(string str)" you are WRONG.

If you try to this you will end with a below error. Read the word "Ambiguous" in the error , does something click. Ok , let me explain in more detail what the below error means.










Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism it works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

And i know if you answer with the above argument MVC interviewer would still press that he wants to implement polymorphism , so how do we go about doing it.

If you wish to keep polymorphism and also want the HTTP request to work you can decorate one of the methods with "ActionName" as shown in the below code.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

publicActionResultLoadCustomer()
        {
return Content("LoadCustomer");
        }

        [ActionName("LoadCustomerbyName")]
publicActionResultLoadCustomer(string str)
        {
return Content("LoadCustomer with a string");
        }
    }
So now you can invoke with URL structure "Customer/LoadCustomer" the "LoadCustomer" action and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.























In case you want to start learning MVC , below is a nice MVC step by step video series which will help you to learn MVC in 16 hours i.e. 2 day's. Give a try.



Saturday, August 16, 2014

Things you will miss in ASP.NET MVC as an ASP.NET Webform developer

Introduction

No CodeBehind

No Server controls

No Page life cycle

No ViewState


Introduction


I have been a great fan of ASP.NET Webform development but for past 2 years ASP.NET MVC is the talk of the town. If you are new to MVC start here and if you want to learn MVC super-fast start here.

Note: - If ASP.NET MVC and ASP.NET WebForm vocabulary is confusing please read this before moving ahead :-http://computerauthor.blogspot.in/2014/08/aspnet-vs-mvc-vocabulary-confusion_15.html.

When I started ASP.NET MVC development it took lot of time as an ASP.NET webform developer to get adjusted and acquainted with ASP.NET MVC development thought. This article walks you through some important mind set changes you need to make when working with ASP.NET MVC.

 

No CodeBehind


The whole thought of MVC is to get rid of behind code. Because behind code is not reusable , not testable .So when you add a view / UI in MVC is you will be find no behind code. You will find “.ASPX” but there is no “ASPX.CS”. You will find CSHTML but there is no CSHTML.CS.


Now the time we say “No Behind code” this has a cascading effect. The remaining points are the after effect of “No code behind” concept.

No Server controls


ASP.NET webform Server controls was always a life savior. It was like a magic where you drag and drop and you are done.Now because we do not have any behind code server controls will not be seen in your tool box. You have to use HTML to create your MVC UI. The maximum support officially you have currently is HTML Helper classes , you can read about it from here.


You can use server controls on an ASPX view but it’s not advisable as it will generate inline code behind again defeating the purpose of MVC.

No Page life cycle


Because we do not have behind code there is no such thing as page life cycle in ASP.NETMVC.In ASP.NET Webform the first hit comes to the Page and then rest of the things happen. ASP.NET Webform is UI first approach while MVC is class first approach.

In MVC the first hit comes to the controller class and then to the UI. So all the logic of page life cycle goes in the controller.So no more discussion on page life cycle and which event what code needs to be written.

No ViewState


There are no automated generated hidden fields like viewstate. We have more robust and fine tuned way of session management viewdata , tempdata ,viewbag and session variables. You can read more about them from clicking here.

Want to Learn MVC in 2 days start from this video






Friday, August 15, 2014

ASP.NET VS MVC – Vocabulary confusion

If you have clicked on this article thinking that ASP.NET is the old thing and MVC is the new thing then you need to seriously read this article.


Recently I was taking Learn MVC in 2 days in Andheri Mumbai and I saw lot of participants thinking ASP.NET is different and MVC is different. During the MVC training many were referring ASP.NET as the old thing and MVC as the new thing. But actually they are one and the same thing.

ASP.NET is a web framework of Microsoft and MVC is a visual studio code template to  write code using MVC architecture style. The proper name of OLD ASP.NET is “ASP.NET webforms”. So ASP.NET webform is the old ASP.NET with behind code and MVC is the new thing.


This is also very much evident when you create an ASP.NET Web project using visual studio. In visual studio you will see two different templates one with the name “ASP.NET Webform” and the other with “ASP.NET MVC”.


Note :- Web and Webform are one and the same thing.

If you want to learn MVC step by step start from the below link

http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in

Tuesday, July 8, 2014

What is CodeLens?

Code lens is a new feature in visual studio 2013 which helps us to understand three important things about our code while we are coding inside visual studio.

All these three things(Impact, test and latest) are seen right above your class / method when you code in visual studio as shown in the below figure.


Impact: - First thing code lens shows is when we change the code what isthe impact of those changes. For instancein the above figure you can see it stating that if you make any changes to the log method it will be impact 1 reference.

If you click on references further it will also show which the classes it’s referencing. With this we come to know the level of impact this change will have further.

In the below screen it’s stating that “ConsoleApplication2” and “UnitTest1.cs” are the classes which.


If you further click on “Show on Code Map” menu you should see a graphical representation of dependencies.


Test :- Second important thing code lens tells is whether this method was unit tested or not.  For instance you can see it say’s 1 passing means this method was unit tested.


Latest: -Third thing it tells where this is a latest code or not. You can see the last menu which states this is not a latest code and you need to do a get latest from the server.

But now for the bad news nothing is free, code lens is currently available only in ultimate edition. Wish it was free as air….. ;-)


Below is a nice and short video of codelens created by www.questpond.com team.



Sunday, April 27, 2014

IEnumerable vs IQueryable ? ( .NET Interview question)

Both these interfaces are for .NET collection’s so if you are new to .NET collection please first see this video https://www.youtube.com/watch?v=hDykzD-3z8k  before moving ahead with the article.

The first important point to remember is “IQueryable” interface inherits from “IEnumerable”, so whatever “IEnumerable” can do, “IQueryable” can also do.


There are many differences but let us discuss about the one big difference which makes  the biggest difference. “IQueryable” interface is useful when your collection is loaded using LINQ or Entity framework and you want to apply filter on the collection.

Consider the below simple code which uses “IEnumerable” with entity framework. It’s using a “where” filter to get records whose “EmpId” is “2”.



This where filter is executed on the client side where the “IEnumerable” code is. In other words all the data is fetched from the database and then at the client its scans and gets the record with “EmpId” is “2”.


But now see the below code we have changed “IEnumerable” to “IQueryable”.







In this case the filter is applied on the database using the “SQL” query.  So the client sends a request and on the server side a select query is fired on the database and only necessary data is returned.


So the difference between “IQueryable” and “IEnumerable” is about where the filter logic is executed. One executes on the client side and the other executes on the database.

So if you working with only in-memory data collection “IEnumerable” is a good choice but if you want to query data collection which is connected with database “IQueryable” is a better choice as it reduces network traffic and uses the power of SQL language.

Below is a nice FB video which demonstrates this blog in a more visual and practical manner.












Sunday, September 1, 2013

What are portable class libraries? ( .NET interview questions with answers)

This interview question is taken from the famous .NET interview question with answer book published by Bpb publications.

The whole point of creating a class library project is reusability. Now we want this reusability not only within a .NET application, not across .NET applications but across different types of .NET applications. Now different types of .NET application means WPF, Windows, Silver light, Windows phone etc.


Now each one of these applications run on different platforms and have different flavors of .NET frameworks. For example silver light application runs inside a browser and has a down sized version of .NET.

So in a silver light application if you try to reference a simple “Class project” you would end with a below error. That’s where portable class libraries are useful. By creating a portable class we can reference it in any kind of .NET project types.


To create a portable class we need to use the portable class template which is available in visual studio as shown in the below figure.



We are thankful to questpond.com to provide financial support for this site. Questpond.com has interview question videos on C# , .NET, MVC, ASP.NET , SQL Server and design patterns.

Below is a simple youtube video which demonstrates What are Portable Class library in c#.

Sunday, August 4, 2013

Testing private methods/functions using VSTS unit test with c#

In case you are new to VSTS unit testing, you can read my article from codeproject.com:- 12 FAQ’s on VSTS unit testing.

Before you make an opinion about me and this article let me admit I am a strong opponent of unit testing private methods. For me a “UNIT” in unit testing means the “Class” as a whole. So if I test public methods of the class the private methods get tested as well.

It’s like should we test the wall or should we test individual bricks of the wall. Logically if the wall stands then the bricks are doing good as well.

But then there is a saying:-




So we have some other school of thought who think “UNIT” can be lines of code and methods. So they think that if you are testing private methods it’s ok and ethically right. And also many times you are in some weird situation like you are trying to zero on the method where the defect is ? , private testing seems to be a reasonable solution.

So with due respect to the second school of thought this blog will discuss how we can test private functions /method using VSTS test.

For example below is a simple “Maths” class which has an “Add” function. This “Add” function does not allow negative numbers. So to check if the number is negative there is a simple private function called as “IsNegative”. So how do we test “IsNegative”  through VSTS unit test framework?.

public class Maths
{
        public int Add(int num1, int num2)
        {
            if(IsNegative(num1) && IsNegative(num2))
            {
                throw new Exception("Number should not be negative");
            }
            return num1 + num2;
        }

        private bool IsNegative(int num)
        {
            if (num > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

In order to invoke private methods in VSTS unit test we have a class called as “privateobject”. Create the object of “PrivateObject” class and pass the class whose private method needs to be invoked. You can then use the “PrivateObject” object to invoke the private methods / functions as shown in the below code.

PrivateObject o = new PrivateObject(typeof(Maths));
bool b = Convert.ToBoolean(o.Invoke("IsNegative", -1));

FYI internally “PrivateObject” uses reflection to invoke the private members.

As said previously, unit testing private methods means there is seriously something wrong in the class design. This is also a sign that the class is overloaded with lot of responsibility and is not following SRP ( single responsibility responsible ). 

In this case the “Maths” class should only be doing arithmetic operations (Add, Subtract etc), but it is also loaded with responsibility of doing validation. So probably it’s a good idea to move the validation to a separate class called as “Validator” who will do the numeric checks and then use this class inside the “Maths” class.

You can then write test cases on the “Validator” class separately which is a cleaner approach than the previous approach of using “PrivateObject” and invoking them via reflection.

public class Validator
    {
        private bool IsNegative(int num)
        {
            if (num > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

Below is a simple video I have created which shows how to use “PrivateObject” class to invoke the private methods.

Sunday, July 21, 2013

.NET interview questions with answers: - Build solution VS Rebuild solution VS Clean solution

I am not aware of a single day in my life when I have not clicked on “Build”, “Rebuild” or “Clean” menu of visual studio. Even though I use it on a daily basis  or sometimes even minute to minute basis when my keyboard was high on coding, I was still not clear what exactly each one of these menus do.  I had very vague idea, but I wanted to be sure about the exact differences between them.

When I hunted the differences what came out was surprising, below goes a detailed explanation of the same.


Build solution menu: - This will perform an incremental build. In other words it will only build code files which have changed. If they have not changed those files will not touched.

Rebuild solution menu: - This will delete all current compiled files (i.e. exe and dll’s) and will build everything from scratch, irrespective if there is code change in the file or not.


Clean solution menu: - This menu will delete all compiled files (i.e. EXE’s and DLL’s) from “bin” / “obj” directory.

Now if you read the above 3 points I have discussed you can conclude that:-

Rebuild = Clean + Build

So the next question would be If you do a “Rebuild” and if you do “Clean” + “Build” , what is the difference ?.

The difference is the way the build and clean sequence happens for every project. Let’s say if your solution has two projects “proj1” and “proj2”. If you do a rebuild it will take “proj1” , clean ( delete) the  compiled files for “proj1” and build it. After that it will take the second project “proj2” , clean compiled files for “proj2” and compile “proj2”.

But if you do a “clean” and build”. It will first delete all compiled files for “proj1” and “proj2” and then it will build “proj1” first followed by “proj2”.

Below image explains the same in a more visual format.


















Below is a simple youtube video which demonstrates difference between these entities.



Big thanks to questpond.com to provide these c# and .NET interview questions with answers videos.






Saturday, July 13, 2013

C# and .NET interview questions with answers: - How can we mark a method as deprecated?

This question is taken from the book .NET interview questions written by Shivprasad Koirala.

Many times you want to warn developers that some methods or classes should not be used as they are either replaced or going to be replaced with new versions. This is possible by using the “[Obsolete]” attribute.

In the below class we have a method called as “Method1”. Now let’s say you have created a better improvised version of “Method1” called as “NewMethod1”. You want to send an alert to all your developers who are consuming this class to use “NewMethod1” rather than using “Method1”.

So you can decorate “Method1” with the “[Obsolete]” attribute as shown in the below code.

public class Class1
{
        [Obsolete]
        public void Method1()
        {

        }

        public void NewMethod1()
        {
        }
}

Now if any programmer consumes the above class he will get a warning message as shown in the below figure.













In case you want to show some message to the developers you can pass the message in the “Obsolete” attribute as shown in the below code snippet.

[Obsolete("Please use NewMethod1")]
public void Method1()
{

}

If you want to be bit strict and do not developers to use that method, you can pass ‘true” to the “Obsolete” attribute as shown in the below code.

[Obsolete("Please use NewMethod1",true)]
public void Method1()
{

}

Now in case developers try to make a call to “Method1”   they will get error and not just a simple warning.













Also visit our site from more such c# interview question with answers videos.

Also read this interesting .NET interview question with answer: - What is TPL ( Task parallel library ) ?





   

Thursday, July 4, 2013

C# circular dependency interview questions with answers.

Can you define circular dependency?

Circular dependency is a situation where “classlibrary1” references “classlibrary2” and “classlibrary2” is trying to reference “classlibrary1”.


If you ever try to reference class libraries with each other visual studio throws the below exception.


Can you explain a scenario where circular dependency situation occurs?

Consider a situation of a 3 layer architecture where the middle layer is consuming data access layer. Below is a simple “Customer” class which belongs to the middle layer and its making call to the data access layer using the “CustomerDal” class.

For now assume that both these classes are in different c# project.

    public class Customer : ICustomer
    {
        public int CustomerCode { get; set; }
        public string CustomerName { get; set; }
     
        public void Add()
        {
            CustomerDal oDal = new CustomerDal();
            oDal.Add(this.CustomerCode,
                             this.CustomerName);
        }
    }

public class CustomerDal
    {
        public void Add(int CustomerCode,
                        string CustomerName)
        {
         
            // database insert code goes over here
        }
    }

Now if you see the “CustomerDal” class the add method has data passed in variables. It would be great if we can pass the “Customer” object directly. In other words we are looking at a modified version of “CustomerDal” as shown below.In order to achieve the same “CustomerDal” project needs to reference the “Customer” project.

public class CustomerDal
    {
        public void Add(Customer cust)
        {
            
            // database insert code goes over here
        }
    }


Now already the “Customer” project is referencing the “CustomerDal” project and if you try to reference the “Customer” project in “CustomerDal” project, it would throw a circular dependency error as shown below.


How can we overcome the circular dependency problem?

Circular dependency problem can be overcome by using interfaces or events. So for the above problem we can introduce an interface in between the “MiddleTier” and “Dal”


So below is the solution. You can create an altogether different c# project and create an interface “ICustomer” as shown in the below code.

public interface ICustomer
    {
        int CustomerCode { get; set; }
        string CustomerName { get; set; }
    }
This interface project you will implement in the middle layer project on the  “Customer” class.

public class Customer : ICustomer
    {
        public int CustomerCode { get; set; }
        public string CustomerName { get; set; }
        
        public void Add()
        {
            CustomerDal oDal = new CustomerDal();
            oDal.Add(this); // passing the object ( polymorphism)
        }

      
    }
Now in the data access layer project you can reference the interface project and use the interface rather than passing the individual variables in the method.  When the middle layer makes a call to data access layer he will pass “this”. Due to polymorphism the customer object would be automatically type casted to the data access layer in the interface format. Please see the code of “Customer” class where in the “Add” method we have passed “this” object.

public class CustomerDal
    {
        public void Add(ICustomer cust)
        {
            
            // database insert code goes over here
        }
    }

Note: - Circular dependency is a sign of bad design and tight coupling. So when you get in to a circular dependency situation rather than fixing it directly by interfaces or events, question yourself why you landed in this situation.

Sunday, May 12, 2013

Dependency injection (DI) VS Inversion of Control (IOC)

The main goal of Inversion of control and Dependency injection is to remove dependencies of a application. This makes the system more decoupled and maintainable.

First let’s try to understand IOC (Inversion of control).  If you go back to old computer programming days, program flow used to run in its own control.  For instance let’s consider a simple chat application flow as shown in the below flow diagram.
  1. End user sends chat message.
  2. Application waits for the message from the other end.
  3. If no message is found it goes to Step 2 or else moves to Step 4.
  4. Displays the message.
  5. User continues with his work ahead.

Now if you analyze the program flow closely, it’s sequential. The program is in control of himself. Inversion of control means the program delegates control to someone else who will drive the flow. For instance if we make the chat application event based then the flow of the program will go something as below:-
  1. End user sends chat message.
  2. User continues with his work ahead.
  3. Application listens to events. If a message arrives event is activated and message is received and displayed.



If you see the program flow it’s not sequential, its event based.  So now the control is inverted. So rather than the internal program controlling the flow, events drive the program flow. Event flow approach is more flexible as their no direct invocation which leads to more flexibility.

A word of caution here, do not conclude that IOC are implemented by only events.  You can delegate the control flow by callback delegates, observer pattern, events, DI (Dependency injection) and lot of other ways.

IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC. IOC is a concept where the flow of application is inverted.   So for example rather than the caller calling the method.

SomeObject.Call();

Will get replaced with an event based approach as shown below.

SomeObject.WhenEvent += Call();

In the above code the caller is exposing an event and when that event occurs he is taking action.  It’s based on the Hollywood principle “Don’t call us we will call you”.  In Hollywood when artists used to give auditions the judges would say them “Don’t call us we will call you”.

The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.





DI provides objects that an object needs.  So rather than the dependencies construct themselves they are injected by some external means.  For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.



The biggest benefit achieved by the above approach is “Decoupling”. You can now invoke the customer object and pass any kind of “Logger” object as shown in the below code.

Customer obj = new Customer(new EmailLogger());
Customer obj1 = new Customer(new EventViewerLogger());


Monday, April 29, 2013

.NET 4.0 FAQ Part 1 -- The DLR




Simple 7 steps to run your first Azure Blob Program


Introduction

Step 1:- Ensure you have things at place

Step 2:- What will we do?

Step 3:- Create a web role

Step 4:- Set the blob connection string

Step 5:- Create the blob on webrole onstart

Step 6:- Code your ASP.NET UI


Step 7:- Run the project and enjoy


Introduction


In this section we will create our first program using Azure blobs. This article creates a simple web page where we upload image files which are stored in azure blobs. We have also created a simple search text box which will help us to search the image blobs with the image file name.
In case you are a complete newbie to azure you can download my two azure basic videos which explain what azure is all about Video1 Video2.

Please feel free to download my free 500 question and answer eBook which covers
.NET , ASP.NET , SQL Server , WCF , WPF , WWF@
http://www.questpond.com .





Step 1:- Ensure you have
things at place




In case you are a complete fresher to Azure,
please ensure you have all the pre-requisite at place. You can read the below
article to get the basic prerequisite

http://www.codeproject.com/KB/cs/Simple5stepsAzure_.aspx
.




Step 2:-
What will we do?




Azure Blobs help to store large items like
files, in other words its file storage system. In this article we will create a
simple program to upload image files in Azure blob system.




Step 3:-
Create a web role




The first step is to a create a web role
project. In case you are fresher in Azure, you can go through

http://www.codeproject.com/KB/cs/Simple5stepsAzure_.aspx
to understand
how to create a web role project.



So let’s create a simple project with name ‘BlobStorage’. Once you have created
the project it creates two projects one is the cloud service project and the
other is the web role project. Cloud service project has all the necessary
configuration needed for your cloud service project while the web role project
is your asp.net project.









Step 4:- Set the blob
connection string




Now the next step is to define a blob
connection string in the service configuration file. So expand the ‘BlobStorage’
project, right click on roles and select properties.








Once you select properties, go to settings tab and add the blob connection
string as shown in the below figure. In the below figure we have added blob
connection string name as ‘BlobConnectionString’.








Click on the right hand eclipse and select ‘Use
development storage’. All the changes done using the setting UI will be
reflected in the ‘ServiceConfiguration’ file as shown above.





Step 5:- Create the blob
on webrole onstart




Now it’s time to start coding. Open the web
role project and open ‘WebRole.cs’ file.








Now let’s write a code on the ‘onstart’ event
to create the blob container.



public override bool OnStart()


{








}



Use the ‘CloudStorageAccount’ static class to
set the configuration environment.



public override bool OnStart()


{


// Set the configuration file


DiagnosticMonitor.Start("DiagnosticsConnectionString");


CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>


{


configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));


});


....


....


....


....


}



The next step is to get a reference of the
cloudstorageaccount object using the blob connection string which was provided
when you setup your web role project.



// get the blob connection string


CloudStorageAccount objStorage = CloudStorageAccount.FromConfigurationSetting("BlobConnectionString");



Once we have access to the storage account
object, use the blob end point to create the blob client.



// get the client reference


CloudBlobClient objClient = new CloudBlobClient(objStorage.BlobEndpoint, objStorage.Credentials);



Give a nice name to the container and create
the container object using the client object which you have just created using
the blob end point. Call the ‘CreateIfnotExist’ method of the container to
ensure that you create the blob container only if it does not exist to avoid any
errors.



// Get the reference to container


CloudBlobContainer objContainer = objClient.GetContainerReference("mycontainer");





// Create the container if it does not exist


objContainer.CreateIfNotExist();



Step
6:- Code your ASP.NET UI




The final step is to create the ASPX page which
will help us upload image files in the blob container which we just created in
the ‘WebRole.cs’ file. You can see in t he below figure we have create a browse
button which help us upload image files and a search text box which will help us
search blob files.

So create the below defined ASPX UI.








In the above ASPX CS UI first get the reference
to the below specified name spaces.



using Microsoft.WindowsAzure;


using Microsoft.WindowsAzure.StorageClient;



In the file upload button we need to insert the
below code snippet to upload the file. So get access to the container object
‘MyContainer’ and call the ‘GetBlobReference’ function to get access to the
cloud blob object.



// Get the storage account reference


CloudStorageAccount objStorage = CloudStorageAccount.FromConfigurationSetting("BlobConnectionString");


// get the Client reference using storage blobend point


CloudBlobClient objClient = new CloudBlobClient(objStorage.BlobEndpoint, objStorage.Credentials);


// Get Container reference


CloudBlobContainer objContainer = objClient.GetContainerReference("mycontainer");


// Get blob reference


CloudBlob obj =objContainer.GetBlobReference(FileUpload1.FileName.ToString());



Set the meta data of the cloud object and open
a blob stream object to write the file. Do not forget to close the blob steam
object once you are done.



// Set meta values


obj.Metadata["MetaName"] = "meta";


// Open a stream using the cloud object


BlobStream blobstream = obj.OpenWrite();


// Write the stream to the blob database


blobstream.Write(FileUpload1.FileBytes, 0, FileUpload1.FileBytes.Count());


blobstream.Close();



Once we upload the file, we will browse through
the blob list to get the list of blobs present in the container.



// Browse through blob list from the container


IEnumerable<IListBlobItem> objBlobList = objContainer.ListBlobs();


foreach (IListBlobItem objItem in objBlobList)


{


Response.Write(objItem.Uri + "<br>"); 


}



In the same UI we have provided a search object
to search a blob. To search a blob first get access to the container object and
call the ‘GetBlobReference’ function with the blob name to get reference to the
cloud object.



// Get the blob reference using the blob name provided in the search


CloudBlob obj = objContainer.GetBlobReference(txtSearch.Text);


BlobStream blobstream = obj.OpenRead();



Read the blob stream using the blob steam
object and finally attach this stream with the Image object to display the same
in the HTTP response.



// Create the image object and display the same on the browser response


System.Drawing.Image objimg=null;


objimg = System.Drawing.Image.FromStream(blobstream,true);


Response.Clear();


Response.ContentType = "image/gif";


objimg.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);




Step 7:- Run the project and enjoy




Finally enjoy your first blob program. You can
see in the below figure we have uploaded some image files in the blob.








We can also search the blob using the search
blob text box and you should be able to get the below image display from the
blob database.