Tuesday, December 23, 2014

Check whether an email address is valid or not ?

Some times, we require some common function like Get Random GUID, or some validations like passowrd is strong or not.

So, here i show you the validation of Email address field that checks whether the entered email address is valid or not ?

I have created a function "CheckEmail", which accepts the EmailAddress imput as an parameter.
You have to pass your input Emailaddress value to this function and this function will return you a boolean (true/false), if the entered email address is valid then it will return true until false.

    //<param name="emailAddress">Your Email Address</param>
    public static bool CheckEmail(string emailAddress)
        bool isValid = true;
        if (string.IsNullOrWhiteSpace(emailAddress.Trim()))
            isValid = false;
            RegexStringValidator re = new RegexStringValidator(@"^[a-zA-Z0-9][-\w\.]*@([a-zA-Z0-9][\w\-]*\.)+[a-zA-Z]{2,3}$");
                isValid = false;
        return isValid;
    For RegexStringValidator class, you have to add this namespace
using System.Configuration

Monday, December 22, 2014

Difference between ApiController and Controller in ASP.NET MVC

In Today's generation all the peoples are very smart. They are using mobiles, tablets etc. device in those days rather than browser and these device have unlimited apps for make a life smooth. At the end, we all are moving from the web world towards the app world.

So, why not we will develop a worth program which will be helpful in both web and app world.
So, For that i suggest go through ApiControllers.

Difference :

1) You can use controller to render your normal views only.
but using the ApiController action only returns the data which is serialized and sent to client.
So, that you can use it any Html based application.

2) You can self hosting using ApiController but not from MVC Controllers.

3) If you are aware with ASP.NET MVC then you are already knows about the controllers.
And the APIControllers are same as MVC controllers, but it inherits the ApiController class instead of the Controller class.

4)  APIControllers is a lightweight architecture excepting the web Apps.

5)  MVC Controller shows the URL Samples matching the default route pattern"{controller}/{action}/{id}". and the ApiController shows "api/{controller}/{id}".

6) Web API Supports the self hosting, content negotiation where the MVC doesn't support it.

7) Use Controller when - If you're writing an HTML based web/internet application (with the occasional AJAX call returning json here and there).
Use ApiControllers When - If you want to provide a data driven/REST-ful interface to a system.

8) For Example,
     //In ASP.NET MVC
     public class PostsController : Controller
         // GET: /Tweets/
         public ActionResult Index() {
               return Json(Facebook.GetAllPosts(), JsonRequestBehavior.AllowGet);

     //ASP.NET Web API
public class TweetsController : ApiController { // GET: /Api/Tweets/ public List<Posts> GetAllPosts() { return Facebook.GetAllPosts(); } }
So, You have to use the API which is compatible with the browsers and all the modern devices apps.
Actually, the Web API is a open source platform for building a REST-ful services over the .Net Framework.  

Now, I hope you have got when to use Web API over MVC and how it works.
Please keep commenting every author needs motivation.

Friday, December 19, 2014

MVC Interview Questions and Answers

Model View Controller

By reading these MVC interview question it does not mean you will go and clear MVC interviews. The whole purpose of this Post is to quickly brush up your MVC knowledge before you for the MVC interviews.
Before Going for Question Answers, i will give you a little bit of introduction about MVC.

What is MVC?

MVC is a framework pattern that splits an application’s implementation logic into three component roles: models, views, and controllers.
  • Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
  • View: The user interface that renders the Model into a form of interaction.
  • Controller: Handles a request from a View and updates the Model that results in a change of the Model’s state.To implement MVC in .NET, we need mainly three classes (ViewController and the Model).

    Explain MVC Architecture?

  •              The architecture is self explanatory. The browser (as usual) sends a request to IIS, IIS searches for the route defined in MVC application and passes the request to the controller as per route, the controller communicates with the model and passes the populated model (entity) to View (front end), Views are populated with model properties, and are rendered on the browser, passing the response to browser through IIS via controllers which invoked the particular View.

  Features of MVC 2.0

  • Introduction of UI helpers with automatic scaffolding with customizable templates
  • Attribute-based model validation on both client and server
  • Strongly typed HTML helpers
  • Improved Visual Studio tooling
  • There were also lots of API enhancements and “pro” features, based on feedback from developers building a variety of applications on ASP.NET MVC 1.0, such as:
    • Support for partitioning large applications into areas
    • Asynchronous controllers support
    • Support for rendering subsections of a page/site using Html.RenderAction
    • Lots of new helper functions, utilities, and API enhancements

  Features of MVC 3.0

  • The Razor view engine
  • Support for .NET 4 Data Annotations
  • Improved model validation
  • Greater control and flexibility with support for dependency resolution and global action filters
  • Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding
  • Use of NuGet to deliver software and manage dependencies throughout the platform

  Features of MVC 4.0

  • Enhancements to default project templates
  • Mobile project template using jQuery Mobile
  • Display Modes
  • Task support for Asynchronous Controllers
  • Bundling and minification

  Advantages of MVC

  1. Provides a clean separation of concerns between UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller)
  2. Easy to UNIT Test
  3. Improved reusability of views/model. One can have multiple views which can point to the same model and vice versa
  4. Improved structuring of the code

  Explain Routing in MVC

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.
Routing within the ASP.NET MVC framework serves two main purposes:
  • It matches incoming requests that would not otherwise match a file on the file system and maps the requests to a controller action.
  • It constructs outgoing URLs that correspond to controller actions.

  Now Ready for Question – Answers:

1. What are the 3 main components of an ASP.NET MVC application?
1. M – Model
2. V – View
3. C – Controller
2. In which assembly is the MVC framework defined?
3. 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.
4. 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.
5. 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.
6. Which approach provides better support for test driven development – ASP.NET MVC or ASP.NET Webforms?
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.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.
10. 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.
11.Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax
12. 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
13.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.
14. 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.
15. 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://dotnetternikhil.com/Nikhil/Home/1
Controller Name = Nikhil
Action Method Name = Home
Parameter Id = 1
16. 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.
17.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.
18. 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.
19. Is the following route definition a valid route definition?
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.
20. What is the use of the following default route?
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.
21. 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.
22. 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.
23. What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface
24. 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.
25. What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx
26. What symbol would you use to denote, the start of a code block in razor views?
27. What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

Facebook Integration in MVC 3.0 (.Net)

Now, Time for Facebook Integration in .Net MVC 3.0.
Step 1 :  Download Library package reference of Facebook from NuGet Package Installer.
Step 2 :  import namespace of facebook as like,             
    using facebook;
Step 3 :  This uri method handles Our call back method that will returns from facebook site after Completed Login screen. 
private System.Uri RedirectUri
            var uribuilder = new UriBuilder(Request.Url);
            uribuilder.Query = null;
            uribuilder.Fragment = null;
            uribuilder.Path = Url.Action(“FacebookCallBack”);
            return uribuilder.Uri;
public ActionResult Facebook()
      var fb = new FacebookClient();
      var loginurl = fb.GetLoginUrl(new
                  client_id = “463931757029793”,
                  client_secret = “add31b78281d6ffccc7d1b887f77d9d4″,
                  redirect_uri = RedirectUri.AbsoluteUri,
                  responce_type = “code”,
                  scope = “email,publish_stream,user_hometown,user_website”
      return Redirect(loginurl.AbsoluteUri);
Step 4 :  Now, get the Details from facebook Client..
public ActionResult FacebookCallBack(string code)
      var fb = new FacebookClient();
      dynamic result = fb.Post(“oauth/access_token”, new
                  client_id = “463931757029793”,
                  client_secret = “add31b78281d6ffccc7d1b887f77d9d4″,
                  redirect_uri = RedirectUri.AbsoluteUri,
                  code = code
      var accessTocken = result[0];
      Session[“AccessTocken”] = accessTocken;
      fb.AccessToken = accessTocken;
      dynamic me = fb.Get(“me?fields=first_name,last_name,id,email”);
      String email = me[3];
      return RedirectToAction(“LoginView”);
Now, Finally this is Done…!!!
Yippee. Always Enjoy coding !!

Twilio API Integration for sending SMS and List of Sent SMS

Now, you can send SMS using Twilio API easily by just following the few Steps:
1.  Login in to the http://www.twilio.com and if you are not user then sign in.
2.  Now Open Visual Studio and start your project and download twilio and twilioML library from NuGet package installer.
3.  After Login in twilio it will gives you a “ACCOUNT SID” and “AUTH TOKEN” and also “TELEPHONE NUMBER”. Save this credentials and apply in our project as..
//you have to add namespace for twilio as like,
using twilio.com;
//and Now apply that Credentials in to our project..
String AuthToken  "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"; // Authentication Tocken.. 
String TelephoneNo  'NNNNNNNNNN'; // Telephone No from the message will sent.
Now, Create Instance of Twilio Rest Client..
var client newTwilioRestClient($AccountSid$AuthToken);
Now, Call the Method SendSmsMessage(“Sender No with country Code”, “Receiver No with Country Code”, “Message Body…”) for sending SMS. as like,
cvar sendsms = client.sendSmsMessage(from,to,msg);
Done…. Yuppp…
Your Project is Working…..
* Note:
You can also set Validation on that like “Message length should not be greater than 160 Characters.. etc.”

Now, You can easily manage sent message list..
as below,
public SMSMessage getMessageList(String to, String from)
String AuthToken = "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"; // Authentication Tocken..
var client = new TwilioRestClient(AccountSid,AuthToken);
SmsMessageResult msgs = postMaster.ListSmsMessages();
List msg = msgs.SMSMessages;
foreach (var smsmsg in msgs.SMSMessages)
 if (smsmsg.Status == “received” && smsmsg.From == from && smsmsg.To == to)
  return smsmsg;
 return null;

Send Data from Java Script to Controller in .NET MVC

Now, When you are working on some Java script APIs or like for some other purpose you have to send java script data to Controller for storing that value in Database.
So, for that you have use the $.Ajax() for pass this java script data to controller.
and at Controller side, you can get that data easily…
As Like,

var uname = 'Nikhil Prajapati';
        url: "/Main/getRequestID",      // This is path of your Controller with Action Result.
        dataType: "json",                // Data Type for sending the data
        data: {                         // Data that will be passed to Controller
                'my_name': uname,     // assign data like key-value pair
                  // 'my_name'  like fields in quote is same with parameter in action Result
        type: "POST",                  // Type of Request
        contentType: "application/json; charset=utf-8", //Optional to specify Content Type.
        success: function (data) { // This function is executed when this request is succeed.
        error: function (data) {
                alert("Error");   // This function is executed when error occurred.

Now, At Controller Side,
in MainController.cs
        public ActionResult getRequestID(String my_name)
                MYDBModel myTable = new                 Models.MYDBModel();
                myTable.FBUserName = my_name;
                                db.SaveChanges();                          // db object of our DbContext.cs.
                //return RedirectToAction(“Index”);      // After that you can redirect to some pages…
                return Json(true, JsonRequestBehavior.AllowGet);    // Or you can get that data back after inserting into database.. This json displays all the details to our view as well.
So, Yupp, you can pass the java script data easily to Controller..

Thursday, December 18, 2014

Password Encryption and Decryption in ASP.NET

  1.  This Method illustrates the Password Encryption...
public static string Encrypt(string originalString)
      if (originalString == null)
            return originalString = “”;
      if (String.IsNullOrEmpty(originalString))
            throw new ArgumentNullException
            (“The string which needs to be encrypted can not be null.”);
      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream memoryStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
      cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
      StreamWriter writer = new StreamWriter(cryptoStream);
      return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
Now, You can call this mehod as ClassName.Encrypt("Your Password");

  2. This Method illustrates the Password Decryption...
public static string Decrypt(string cryptedString)
      if (String.IsNullOrEmpty(cryptedString))
            throw new ArgumentNullException
            (“The string which needs to be decrypted can not be null.”);
      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream memoryStream = new MemoryStream
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
      cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
      StreamReader reader = new StreamReader(cryptoStream);
      return reader.ReadToEnd();

Now, You can call this mehod as ClassName.Decrypt("Your Encrypted Password")

Note :  for that you have to add namespace of System.Security.Cryptography as like, 
 using System.Security.Cryptography;