Blog

Get location (Latitude & Longitude) for given address in c# using google api

In my application I wanted to find Latitude & Longitude of address of a person.

To do this I have used google api.

Bellow is c# code:

Here What I did is just called google service & just extracted the latitude & longitude from the xml response which I got from service.

This free service has limitation of 2500 request per IP per day, so If your application is will request more than that then google api will block your IP temporarily & If you continue to do this then It may ban your IP also.

I your application will request more that 2500 request per day per IP then you may have to buy service from google.

Get distance between two points using cloudmade

In my application I wanted to find distance between several points (latitude & longitude) which I had plotted on my leaflet map.

After searching for some time I found that coludmade provides service for finding distance & time between points.

Lets See how can we do this:

Bellow is my javascript

In getDistanceTime() function I am creating url string for service & calling it using ajax.

On click of this button service will be called & in response we will get shortest distance between two points.

Demo : http://jsfiddle.net/FhfVW/15/

Here I have found shortest distance in kms traveling by “car”.We can also find traveling by “foot” or “bicycle” also.We can also find distance between two points via come mid points

Demo : http://jsfiddle.net/Am69G/

More Details of this service can be found on http://developers.cloudmade.com/projects/routing-http-api/examples

Solving Error ‘SET OPTION SQL_QUOTE_SHOW_CREATE=1′ in mysql while exporting data

While exporting my database from MySql Database using Workbench 5.2 I got error as bellow

Before that when I clicked then I got this warning
“mysqldump.exe is version 5.5.16, but the MySQL Server to be dumped has version 5.6.10.
Because the version of mysqldump is older than the server, some features may not be backed up properly.
It is recommended you upgrade your local MySQL client programs, including mysqldump to a version equal to or newer than that of the target server.
The path to the dump tool must then be set in Preferences -> Administrator -> Path to mysqldump Tool.”

After searching for solution for some time I got solution for it.
Just follow the steps
1. Go To Edit -> Preferences -> Administrator.

2. In ‘Path to mysqldump Tool’ we have to chose path for mysqldump.exe.
But there are two mysqldump.exe present
1) C:\Program Files\MySQL\MySQL Workbench CE 5.2.47\mysqldump.exe
2) C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe
If we see details of files then we will come to know that 1st file version is 5.5.16 & 2nd files version is 5.6 & By default Workbench considers 1st file

3. Select File which is at path ‘C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe’

Its done now try to export database, you will be able to export it without any errors.

create polylines with different colors in leaflet/ dynamically change color of polyline

Recently while working with leaflet polyline I had a situation where I wanted to add multiple polylines with different colors.
number of polylines were different all the time, so I was not able to give different color to each polyline as my javascript was generic for adding all polylines to map.
So I found way for creating dynamic color for each polyline.
Bellow is function which creates polyline for each set of points.

Here If we see instead of giving any color I am calling function get_my_color()
This function is shown bellow.

This will create color dynamically & send it to color property of polyline

How to draw polyline using leaflet

For creating polyline we need to have at least two points.

So we first create two points.

Polyline needs an array of points to be entered, so will create array for this points.

Now we will create between these two points.

We can add different properties like weight, colour, opacity, smoothFactor, etc. to polyline also.
See bellow example

Solving “The requested service, ‘http://MyService.svc’ could not be activated. See the server’s diagnostic trace logs for more information.” error

While working in WCF project I got this error while accessing wcf service.
“The requested service, ‘http://MyService.svc’ could not be activated. See the server’s diagnostic trace logs for more information.”

But when I was running service separately then It was running.

After searching for some time I got one solution which works for me.

Solution is as follows:

In of your web.config of your application just add

Understanding OOPS SOLID Principles

SOLID principles

Thanks to Al-Farooque Shubho’s article on codeproject

Single Responsibility Principle

“There should never be more than one reason for a class to change.”
Or, differently said: “A class should have one and only one responsibility”.

It says, “Just because you can implement all the features in a single device, you shouldn’t”. Why? Because it adds a lot of manageability problems for you in the long run.

If you have a class that has more than one reason to change (or has more than one overall responsibility), you need to split the class into multiple classes based upon their responsibility.

You surely can have multiple methods in a single class. The issue is they have to meet a single purpose. Now, why is splitting important?

It’s important because:
• Each responsibility is an axis of change.
• Code becomes coupled if classes have more than one responsibility.

We should break up the class based on its responsibilities.SRP seems to be an idea of breaking things into molecular parts so that it becomes reusable and can be managed centrally.

So, shouldn’t we apply SRP in the method level as well? I mean, we might have written methods that have many lines of code for doing multiple things. These methods might be violating SRP.

Yes, you should break down your methods so that each method does a particular work. That will allow you to re-use methods, and in case a change is required, you are able to do the change by modifying minimal amount of code.

E.g.:
Let’s say we have Rectangle class which implements two functionalities i.e. Calculate Area & Draw Rectangle.
So we should break this rectangle class
1. Rectangle: This class will only calculate area.
2. RectangleUI: This will inherit Rectangle class & will implement method which will draw rectangle.

Open-Closed Principle

“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”

At the most basic level, that means, you should be able to extend a class’s behaviour without modifying it. It’s just like I should be able to put on a dress without doing any change to my body.

Liskov’s Substitution Principle

“Subtypes must be substitutable for their base types.”
Or, if said differently:
“Functions that use references to base classes must be able to use objects of derived classes without knowing it.”

E.g.:
Lets consider Class Bird which implements method Fly () & Kingfisher class which will extend Bird class.

Here, the Kingfisher class extends the Bird base class and hence inherits the Fly () method, which is pretty good.
Let’s create one more class Ostrich which also extends Bird class.

Now, can it fly? No! Here, the design violates the LSP.

So, even if in real world this seems natural, in the class design, Ostrich should not inherit the Bird class, and there should be a separate class for birds that can’t really fly and Ostrich should inherit that.

Interface Segregation Principle

“Clients should not be forced to depend upon interfaces that they do not use.”

Suppose you want to purchase a television and you have two to choose from. One has many switches and buttons, and most of those seem confusing and doesn’t seem necessary to you. Another has a few switches and buttons, which seems familiar and logical to you. Given that both televisions offer roughly the same functionality, which one would we choose?

Obviously the second one with the fewer switches and buttons.

Yes, but why?

Because we don’t need the switches and buttons that seem confusing and unnecessary to us.

Similarly, suppose we have some classes and we expose the functionality of the classes using interfaces so that the outside world can know the available functionality of the classes and the client code can be done against interfaces. Now, if the interfaces are too big and have too many exposed methods, it would seem confusing to the outside world. Also, interfaces with too many methods are less re-usable and such “fat interfaces” with additional useless methods lead to increased coupling between classes.

This also leads to another problem. If a class wants to implement the interface, it has to implement all of the methods, some of which may not be needed by that class at all. So, doing this also introduces unnecessary complexity, and reduces maintainability or robustness in the system.

The Interface Segregation principle ensures that Interfaces are developed so that each of them has their own responsibility and thus they are specific, easily understandable, and re-usable.

E.g.:
Consider IBird Interface which defines behavior like Fly (), Walk (), Chirp (), Eat ().
Note that the IBird interface has many bird behaviours defined along with the Fly () behaviour. Now, if a Bird class (say, Ostrich) implements this interface, it has to implement the Fly () behaviour unnecessarily (Ostrich doesn’t fly).

The “Fat Interface” should be broken down into two different interfaces, IBird and IFlyingBird, where the IFlyingBird inherits IBird.

If there is a bird that can’t fly (say, Ostrich), it would implement the IBird interface. And if there is a bird that can fly (say, KingFisher), it would implement the IFlyingBird interface.

Dependency Inversion Principle

“High level modules should not depend upon low level modules. Rather, both should depend upon abstractions.”

Let’s consider a real world example to understand it. Your car is composed of lots of objects like the engine, the wheels, the air conditioner, and other things.None of these things are rigidly built within a single unit; rather, each of these is “pluggable” so that when the engine or the wheel has problem, you can repair it (without repairing the other things) and you can even replace it.

While replacement, you just have to ensure that the engine/wheel conforms to the car’s design (say, the car would accept any 1500 CC engine and will run on any 18 inch wheel).Also, the car might allow you to put a 2000 CC engine in place of the 1500 CC, given the fact that the manufacturer (say, Toyota) is the same.

In real world, Car is the higher level module/entity, and it depends on the lower level modules/entities like the Engines or Wheels.

Rather than directly depending on the Engines or Wheels, the car depends on the abstraction of some specification of Engine or Wheels so that if any the Engine or Wheel conforms to the abstraction, these could be assembled with the car and the car would run.

Binding static dropdown list with model in mvc3/mvc4 razor

In this tutorial I will show you that how can you bind your static drop down list with you view model.

Above code is placed in view only.
First what I did is that I made list of listitems (Here I have used example of marital status)

After this I have just passed this list to @Html.Dropdownlistfor where model & list are bidden.

Like this you can bind your static list with model.
If model has any default value then it will be selected in drop down & also when we will select any value in drop down then we can get this value from model in controller.

MVC Interview Questions & Answers

What is MVC?
MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.
“Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).

“Views” in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).

“Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.

What are the 3 main components of an ASP.NET MVC application?
1. M – Model
2. V – View
3. C – Controller

1- In which assembly is the MVC framework defined?
System.Web.Mvc

2- Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application.

3- What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

4- What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

5- Which approach provides better support for test driven development – ASP.NET MVC or ASP.NET Webforms?

ASP.NET MVC

6- What is Razor View Engine?
Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.

7- What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

8- Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?

Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don’t have to run the controllers in an ASP.NET process for unit testing.

9- What is namespace of asp.net mvc?
ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.
System.Web.Mvc namespace
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application
System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.

10- Is it possible to share a view across multiple controllers?

Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

11- What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

12- Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

13- Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

14- What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view

15- What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

16- What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

17- How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

18- What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment – Controller Name
2nd Segment – Action Method Name
3rd Segment – Parameter that is passed to the action method

Example: http://google.com/search/label/MVC
Controller Name = search
Action Method Name = label
Parameter Id = MVC

19- ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.
How do you avoid XSS Vulnerabilities in ASP.NET MVC?
Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

20- What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user’s action and therefore are more easily understood by users.

21- What are the 3 things that are needed to specify a route?
1. URL Pattern – You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler – The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route – Name is optional.

22- Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

23- What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

24- What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

25- How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

26- What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

27- Give 2 examples for scenarios when routing is not applied?
1. A Physical File is Found that Matches the URL Pattern – This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
2. Routing Is Explicitly Disabled for a URL Pattern – Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

28- What is the use of action filters in an MVC application?
Action Filters allow us to add pre-action and post-action behavior to controller action methods.

29- If I have multiple filters implemented, what is the order in which these filters get executed?

1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

30- What are the different types of filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

31- Give an example for Authorization filters in an asp.net mvc application?

1. RequireHttpsAttribute
2. AuthorizeAttribute

32- Which filter executes first in an asp.net mvc application?
Authorization filter

33- What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method
2. Controller
3. Application

34- Is it possible to create a custom filter?

Yes

35- What filters are executed in the end?
Exception Filters

36- Is it possible to cancel filter execution?
Yes

37- What type of filter does OutputCacheAttribute class represents?
Result Filter

38- What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx

39- What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.

40- What symbol would you use to denote, the start of a code block in razor views?
@

41- What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

42- When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

43- When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

44- What are sections?
Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

45- What are the file extensions for razor views?
1. .cshtml – If the programming lanugaue is C#
2. .vbhtml – If the programming lanugaue is VB

46- How do you specify comments using razor syntax?
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end.

47- What is Routing?
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.

Creating vertical column in html table

In this tutorial I will show you that how can we create vertical column in HTML table.
Bellow is HTML for it:

& bellow is css code for it:

Click here to see demo of This

Bellow is live example:

1 2 3 13  Scroll to top