CSharp – Suraj | Coding Passion Tue, 09 Oct 2018 07:03:49 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 Send SMS using C# application /send-sms-using-c-application/ /send-sms-using-c-application/#comments Thu, 31 Mar 2016 12:22:25 +0000 /?p=540 Introduction

In this article I will be sharing a quick and an interesting way to send SMS using a simple C# application. I will be using ViaNett API to send messages from my application. I will be creating a simple windows form which will trigger the API and send the SMS.
Sending SMS has become a common objective for almost every site nowadays. Though they keep irritating you with continuous messages regarding their advertisements.
1
We use a simple REST API which provided by various providers in the market. You can try out some of them using the free trial version and send SMS. The reliable and faster one can be chosen. Also check for the Support the team provides.
I have thrown my hands at ViaNett and Twilio APIs. Here I will be discussing using ViaNett. Let’s start without actually wasting time.

Get Started

To start with, visit the ViaNett website (ViaNett Free demo Account). Sign up and register you with your email address for the free account, which will provide you with 5 free SMS.
After that, you land on a page having contents like below
2
Click on the Technical Api and that will navigate to different kinds of API it provides. We here would need the HTTP API in order to send the SMS, as we would be using the WebClient in order to use the API. We will be seeing the code below.
After you click on the HTTP API, you will be navigated to another page which will have the API listed under an Example like below:

Create a script to generate a URL like this: https://smsc.vianett.no/v3/send.ashx?src=xxxxx&dst=xxxxx&msg=Hello+world&username=xxxxx&password=xxxxx Retrieve this web page from your script/application, and the SMS will be sent.

This is the API URL which our Web client will be using.
Now to start with our demo application, we will be creating a windows form application. Now, I will not be writing up and lengthing my article with the step by step image for creating a Windows Form application. Those who are really new to windows form, please follow one of the best links below.
Walkthrough To create Windows Form application
After you create a simple windows form application, it would look something like below:
3
Create as simple as you can , as this is just for learning purpose. The UserName is the user name you had provided during the ViaNett registration i.e. the email address
The password is the password you had given during the registration in the ViaNett.
Then for the button click we have the following code:

private void button1_Click(object sender, EventArgs e)
        {
            using (var web = new System.Net.WebClient())
            {
                try
                {
                    string userName = txtUserName.Text;
                    string userPassword = txtUserPassword.Text;
                    string msgRecepient = txtPhNumber.Text;
                    string msgText = txtMessage.Text;
                    string url = "https://smsc.vianett.no/v3/send.ashx?" +
                        "src="+msgRecepient +
                        "&dst="+msgRecepient +
                        "&msg="+System.Web.HttpUtility.UrlEncode(msgText,System.Text.Encoding.GetEncoding("ISO-8859-1")) +
                        "&username=" + System.Web.HttpUtility.UrlEncode(userName) +
                        "&password="+userPassword;
                    string result = web.DownloadString(url);
                    if(result.Contains("OK")){
                        MessageBox.Show("Sms sent successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else{
                        MessageBox.Show("Some issue delivering","Message",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    
                }
            }
        }

The above code would look simple rather it is. 😛

When you select a Windows Form Application, by default System.Web  is not added to the reference list. Thus, you need to add that from the assembly list.

System.Web is required as we add the WebClient to use the API and download the response.

Here in the code, just giving a brief on what this snippet intends:

We retrieve each text input from the user, i.e. the User name, User password, Text Message & the User Phone Number. We use these as the URL params to the Service API of the ViaNett.

Then after that we will check for the response after sending the message and accordingly we update the User.

**Point to note is: The country code needs to be prefixed to the phone number, in order to send the message else it will mail back regarding the failure to the registered email.

Conclusion

Thus, this is a small article on the integration and sending SMS using C# aaplication. I hope this helps beginners!! I will come up with more articles with other APIs and their other SMS features they support.

References

ViaNett

]]>
/send-sms-using-c-application/feed/ 5
Validation & Security in MVC application /validation-security-in-mvc-application/ /validation-security-in-mvc-application/#respond Sun, 06 Sep 2015 16:32:15 +0000 /?p=407 Introduction

Validations in any application is so critical now a days that developers ought to be on their toes while developing any such critical and sensitive applications. Hackers are now in every corner of the society, avoid them restrict them to post non sense data into your applications. The attacks are so vulnerable that security guard of any application is mandatory.
security1
The security checks and implementations should be alert and active in the application to counter the attacks. Lets start learning about different types of validations we can have in our MVC application.

Server-Side Validation

Lets begin with simple server side validations. Server side validation are required when we post something to the server with an expectation for the response,usually while posting form data. The form data post is generally very vulnerable. The attacks are quite easier for the attacker here. Thus, we need to check on the server if we are receiving valid data or not on our end. Thus, server side validation can to some extent prevent nonsense input data. Lets discuss how to do validation explicitly using view model. Lets discuss how:
Explicitly means, we would be checking on server side after form post by the user, if the data input are valid input or not, then we post back the user with the validation message as response.
Suppose we have a model for the Registration of a user to an application. The model goesas below:

public class RegistrationViewModel(){
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string TelNo { get; set; }
}

Thus in the view/UI user will be displayed with the above labels and respective text boxes for input. The razor engine view page in the application looks like:

@model ServerSideValidationDemo.Models.RegistrationViewModel
@{
 ViewBag.Title = "Registration Page";
}

@using (Html.BeginForm())
{

    • @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName, new { maxlength = 50 }) @Html.ValidationMessageFor(m => m.FirstName)
  • @Html.LabelFor(m => m.LastName) @Html.PasswordFor(m => m.LastName, new { maxlength = 50 }) @Html.ValidationMessageFor(m => m.LastName)

 

  • @Html.LabelFor(m => m.Address1) @Html.PasswordFor(m => m.Address1, new { maxlength = 50}) @Html.ValidationMessageFor(m => m.Address1)

 

  • @Html.LabelFor(m => m.Address2) @Html.TextAreaFor(m => m.Address2, new { maxlength = 200 }) @Html.ValidationMessageFor(m => m.Address2)

 

  • @Html.LabelFor(m => m.TelNo) @Html.TextBoxFor(m => m.MobileNo, new { maxlength = 10 }) @Html.ValidationMessageFor(m => m.MobileNo)

 

 

}

Thus, the above snippet would bring the user the UI where the users would post their input and click submit. In the razor view page, you can see the HTML Helper ValidationMessageFor. This helper displays the Validation message returned after validation from the server as response, at the respective model property. Like for example, we want the user to enter the Model property First name as mandatory, then after validation the helper would display the validation message beside the First Name Text Box.
Now lets have a look at the Action snippet to which the post would call after Submit click.

[HttpPost]
public ActionResult UserRegistration(RegistrationViewModel registerModel){
     if (string.IsNullOrEmpty(registerModel.FirstName))
         {
             ModelState.AddModelError("FirstName", "Please enter your first name");
         }
     if (!string.IsNullOrEmpty(registerModel.TelNo))
         { 
             Regex telNoRegex= new Regex("^9\d{9}$");
             if (!telNoRegex.IsMatch(registerModel.TelNo))
             ModelState.AddModelError("TelNo", "Please enter correct format of Telephone Number");
         }
     if(ModelState.IsValid){
         return View("Sucess");  //Returns user to success page
         }
      else {
         return View();  //Returns user to the same page back again
        }
 }

Before explaining the above snippet, lets understand how this will be called after Submit click.
@using (Html.BeginForm()), this does the trick even without specifying the Action and controller. This actually internally calls the Post method of the current url, i.e. looks for the HttpPost attribute to the respective action name of the current url. Thus, in this way the post method of UserRegistration gets called and this also post the required view model to the action, fetching the values input by the user.
After the Action Result method gets called, there is check for the properties explicitly. Here, we check if the user has input into the First name or not. If the user skipd the First Name textbox and submits, then we post the user with the validation message saying “Please enter the first name”. This validation check will not let the user post the input, unless he adds the first name. Similarly, the telephone number is also validated with the regular expression(for the indian telephone number) given.
This was all about the validation being done explicitly.
Now, since we are developing an MVC application, it provides pre defined attributes which can be used to validate our post data. The attributes are called Data-Annotations attribute. Lets look at their usages below:
The use of data annotations can be extensively done in order to avoid heavying the controller post action,explicitly checking for each property. The data annotations attribute in a view model would look like below:

public class RegistrationViewModel(){
    [Required]
    [Display(Name = "First name")]
    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    [Required(ErrorMessage = "Please Enter Telephone Number")]
    [Display(Name = "Tele Phone")]
    [RegularExpression(""^9\d{9}$"", ErrorMessage = "Please Enter Correct format of Telephone No.")]
    public string TelNo { get; set; }
}

The view model above uses Data Annotations attributes and all the required validations for the properties are provided. Lets discuss one by one:

    1. Required:- This attribute forces the user to enter the value for that specific property and then submit the form, else diplays “The FirstName is required.”. Mark here, the previous message would be a default error message where as for the Tele phone number, the custom error message would be displayed.
    2. Display(Name = ):- This attribute sets the label for the model property. We just need to specify
      @Html.LabelFor(m=>m.TeleNo). This would display the specified custom label for the property, here it would display Tele Phone
    3. RegularExpression:- This attribute is very handy specially when we have properties like Email Address, Tele Phone Numbers and specific expressions for passwords in the forms. We just specify the expression in the attribute and it validates the input from user and states if it is valid or else displays the error message.

Thus, here the view page would go like the same as above. And when we submit, the action post method called would be different i.e. much less code. Lets have a look at the action below:-

[HttpPost]
 public ActionResult UserRegistration(RegistrationViewModel registerModel){
    if (ModelState.IsValid)
      {
         return View("Success");//Return to the success 
      }
    else
      {
         return View();//Return back to the same view 
      }
 }

Thus, the data annotations here made it so simple and easy.
Here then comes another security vulnerability, i.e. Cross-Site Request Forgery Attacks, which can be easily attacked using the simple Fiddler. When we post any data, we can easily manipulate the data posted by one user using the fiddler and damp into the application and even ruin it. This is indeed very dangerous. Lets see how to prevent Cross site forgery attacks

Preventing Cross Site forgery Attacks

In MVC applications, while posting the form data, it is quite simple to prevent such request if understood properly. MVC provides the attribute [ValidatAntiForgeryToken] on the respective action. Lets see the flow in the snippet first.
First we need to place the AntiForgeryToken helper in the razor view page like:

@using(Html.Form("UserRegistration", "Register")) { 
    @Html.AntiForgeryToken() 
    //Then here normal rest form as mentioned above    
 }

Then in the controller “Register” for the action “UserRegistration”(POST) add the attribute like below:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UserRegistration(RegistrationViewModel registerModel){
   //ModeState Valid check and rest code goes here
}

Ok, so we have seen what two simple steps we need to do. Now lets understand how it does. What happens exactly when we do not place these attributes. How vulnerable our controller is and to what extent an attacker can affect the application. Suppose we are on an Edit page, where a user soughts to edit few of his login information. Now an attacker from over a third party domain and host a simple HTML that would post some information to the same Edit action, the user were to. Then, some how the user if navigates to the Html page set up by the attacker, the user unknowingly is posting unwanted data to the server and normal saving to the database. Here the attacker may be replacing the email ids or any other vulnerable information to his own and retrieving the user’s data. BOOM! This is crash, rather a crap!
Thus, what we need to do here, we need to check if the request to the server action is coming from the same domain, the user has logged in ! for this we need to have some header or property which will be mapped when a request is made and if matches then post else let the authentication fail.
This is actually what the attribute does. The ValidateAntiForgeryToken actually sets a cookie to the incoming reuest called __RequestVerificationToken, and the same __RequestVerificationToken is set for the domain in which the user is logged in. Thus, when a request is made from the same domain, the request header cookie should match and let the user post the data, but when a request is made from the third party domain, then the request is rejected since the __RequestVerificationToken will never match, just failing the authentication and preventing the Cross Site Forgery by any attacker.
Now here there is another problem. If any how the attacker gets to know the Anti Forgery Token, then what!! again crap! No there is a way out here as well. The attribute has ability to add a unique/different Salt every time so that the same token is not reused everywhere.

@Html.AntiForgeryToken("SALT") //The salt can be any sort of string(homogeneous mixture :))

[ValidateAntiForgeryToken("SALT")]

Another concept that is vulnerable to such attacks and may breach the security in the application is SQL Injection Lets discuss this in brief. 🙂

SQL Injection Attacks & Prevention Techniques

What exactly is SQL Injection attack? thinkzoo
SQL Injection is an attack to fool and manipulate the application database. This is done through the malicious input from the user during post methods and if the posted data is not validated before being executed as sql query. This is really very dangerous which can let attackers get all the sensitive data or even delete the records from all tables, truncating them, just by posting a simple query to drop instead of actual data.
In this, the objective of the attacker is to post their query into the application and let the server run and give him the response if not handled in the server end. Lets see how:
Suppose we have a sql query to select the names of houses and display. The query would be like:

var sqlTobeExecuted = "SELECT HouseID, HouseName"+
    "FROM House " +
    "WHERE Address LIKE '" + searchInputParam +"%';
SqlDataAdapter da = new SqlDataAdapter(sqlTobeExecuted , DbCommand);

The above query is not parameterized and is a simple query in string format to get the house details. Now suppose the attacker posts the searchInputParam (which originally comes from the textbox input of the user) as

‘ UNION SELECT id,name FROM sysobjects;–

Mark the statement what becomes after that is passed to the string query,

SELECT HouseID,HouseName FROM House
WHERE Address LIKE ” UNION SELECT id,name FROM sysobjects;–%’

The first apostrophe in the searchInputParam closes the Like parameter in the SQL query and the double dashes “–” comment out the rest of the query. Thus that gives the list of all the HouseNames and also all the tables present in the database . Even they can also get the ids of the sysObjects and use the Ids to retrieve the column names of the database table they want. Suppose there is a table named Users. Oviously the table would have all the user details. Thus, with the id and the table name the attacker can retrieve the column names of the Users table using the below query:

‘ UNION SELECT name FROM syscolumns WHERE id = “USERID”;–

Thus,the whole of the database can be exposed to malicious users at a single click.
To prevent this,

      • Encrypt the essential and sensitive data like password, credit card info and other details. So that to some extent if by any how they get the details they cannot decrypt it. Use one way hashing to encrypt the record data.
      • Using parameterized queries instead of strings, in order to avoid directly injecting the values from the User input to the query as we saw in the above section. A parameterized query would prevent the malicious input and it would look like below:
        var commandToBeExecuted = "SELECT HouseID, HouseName FROM House"+
            "WHERE Address  Like @Address";
        SqlCommand cmd = new SqlCommand(commandToBeExecuted , conn);
        cmd.Parameters.Add("@Address",address);

        As we see in the above query we avoid passing directly the string input, instead we are using parameters into the SQL query, which would prevent such attacks.
      • use of parameterized Stored Procedures, which also prevent and prove to be a good solution to these mallicious attacks of injection. Also it is advisable to not trust them completely/blindly so it is always better to check for the sensitive data from user inputs and then execute the Stored procedure. This can be done, where the developer can think there are chances of vulnerability.
      • Entity Framework & LINQ, it is interesting to note here is while using LINQ to entity, the query generation does not use the string based approach, rather it uses the object model API, thus being not susceptible to SQL injection attacks.

Authentication & Authorization

These two are very very very…important in any application and these are two different concepts all together but are used to solve the same thing,i.e. Security. When we develop an secure application, the Login is highly essential. Thus, properly authenticating users to the application & authorizing users to particular section of the application is challenging. Usually Forms Authentication is implemented across MVC applications. In the web.config file, the following configuration is set:

Only this will not set the authentication. You need more set up be done. This would involve a lot of configuration. WebSecurity in MVC makes it easy and secure to be implemented. It provides tables and hashing as well. The hashing it provides is one way and very secure. You can learn more about implementing Web Security in MVC from
Web Security In MVC
Thus after setting this authentication, then the important thing is Authorization, which can be provided on controller level, action level, which can be customized in order to check for the access levels along with the sessions. Only Authorize attribute would let the check for the session, we can customized to check for the roles and access levels for the screens as well.

[Authorize]
 public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

In the above snippet, the entire controller has been authorized. That is each method inside the controller will be first authorized.

public class HomeController : Controller
    {
      public ActionResult Index()
        {
            return View();
        }
       [Authorize]
       public ActionResult GetHome(){
         return View()
       }
    }

Here, only the action method GetHome is authorized, not the whole controller.
Thus, Authentication and Authorization are very important factors that ought to be taken into consideration.

More security considerations in MVC

Straight from the OWASP scurity points,
Its advisable to hide the MVC versions as well as Asp.Net versions we use, never expose the versions through the headers.

X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 5.0

We need to hide the versions which appears in the Network tab of the developer table.
Lets know how to remove the versions of Asp.Net and Asp.Net Mvc from the headers.

    • Asp.net Version:-To hide the X version of the Asp.Net we use the below Web.Config change.

      The above will hide the Asp.net versions.
    • Asp.Net MVC Versions:- To hide the X version of the Asp.Net MVC we use the below change in the Application_Start method of the Global.asax. The snippet would go like below:-
      protected void Application_Start()
              {
                  MvcHandler.DisableMvcResponseHeader = true;

      This hides the Asp.Net MVC version from the headers in the Network tab.
    • Lastly, there are chances of exposing the Users to the Yellow screen of death, when an exception occurs in the application and is unhandled. Thus, it is advisable to have a custom error page, where users will be landing when exception occur. Lets see how:
      Custom errors in the Web config needs to be on. There are three modes of the Custom errors. They are:

      1. On:-
        –Prevents the stack trace that is shown when exceptions arise
        –Also allows to display custom error pages to the end user
        –Custom error pages shown to both Remote Clients as well as Local
      2. Off:-
        –Makes the end user view the description of the exception along with the entire stack trace.
        –ASP.NET error/exception and stack trace shown to both Remote clients and Local as well.
      3. Remote only:-
        –This is the best among all for the developers’ perspective, as this allows the Remote clients to view thecustom error messages/pages.
        –Allows the Local users/especially developers to view the ASP.NET errors.
        –This is the default value.

      The other attribute which is used to the custom error element is defaultredirect. This is used to redirect the users to a default page when exceptions occur.

      The exceptions can also be handled globally , application level by using the below snippet:

      protected void Application_Error(Object sender, EventArgs e)
      {
          Exception ex = Server.GetLastError();  //self explanatory gets the most recent error
          Server.ClearError();  //self explanatory clears the error 
              //(Required to clear as otherwise user gets to see the default ASP.NET error handlers)
          Response.Redirect(""); //default redirect. 
      }

      For details you can follow: Custom Errors

      Conclusion

      Thus, security and validations are very important features to be implemented in any application now a days. According to forbes in a day 30,000 sites were hacked. This is truly an astonishing numbers. And in today’s world most of the sensitive information are being stored on cloud. Thus, in any application the data have a great chance of being exposed and hacked. So security is a major concern and needs to be handled very carefully.
      Hopefully, Some of the major points are discussed above and can be implemented in any application to avoid any sort of breaching.

      References

      How can I miss the references from which I learnt and got this opportunity to share with the world.
      OWASP Cheat Sheet
      Security testing
      Sql Injection and Entity Framework

]]>
/validation-security-in-mvc-application/feed/ 0
Using Exception Filters in MVC applications /exceptionfilters-mvc/ /exceptionfilters-mvc/#respond Sun, 12 Jul 2015 16:27:30 +0000 /?p=396 Introduction

Exceptions, are like part and parcel of an application. They are boon and ban for an application to. Is’nt it?This would be controversial, for developers it helps them track minor and major defects in an application, and somtimes they are frustrating when it lets users land on the Yello screen of death each time. This would make the users mundane to the application. Thus to avoid this, developers handle the exceptions. But still sometimes there are a few unhandled exceptions. Now what is to be done for them? MVC provides us with built-in filters ‘Exception Filters’ about which we will discuss. Lets start..
exception cc: Google

Yellow screen of Death can be said as wadrobe malfuction of our application. 😀

Get Started

Exception filters run when some of the exceptions are unhandled and thrown from an invoked action. The reason for the exception can be anything and so is the source of the exception.

Creating an Exception Filter

Custom Exception Filters must implement the built in IExceptionFilter interface. The interface looks as :

public interface IExceptionFilter{
    void OnException(ExceptionContext filterContext)
}

Whenever an unhandled exception is encountered, the OnException method gets invoked. The parameter as we can see, ExceptionContext is derived from the ControllerContext and has a number of built in properties that can be used to get the information about the request causing the exception. There properties ExceptionContext possess are shown in the table:

Name Type Detail
Result ActionResult The result returned by the action being invoked.
Exception Exception The unhandled exceptions caused from the actions in the applications.
ExceptionHandled BOOL This is a very handy property, which returns a bool value (true/false) based on if the exception is handled by any of the filters in the applicaiton or not.

The exception being thrown from the action is detailed by the Exception property and once handled (if), then the property ExceptionHandled can be toggled, so that the other filters would know if the exception has been already handled and cancel the other filter requests to handle. The problem, lies that if the exceptions are not handled, then the default MVC behaviour shows the dreaded yellow screen of death, to the users, which puts up a very bad impact on the users and more importantly, it exposes the application’s handy and secure information to the outside world, which may have hackers and then the application gets into the road to hell. Thus, the exceptions need to be dealt very carefully.
Lets demonstrate one small custom exception filter.
This filter can be stored inside the Filters folder in the web project of the solution. Lets add a file/class called CustomExceptionFilter.cs

public class CustomExceptionFilter : FilterAttribute, IExceptionFilter {
     public void OnException(ExceptionContext filterContext) {
        if(!filterContext.ExceptionHandled && filterContext.Exception is NullReferenceException) {
            filterContext.Result = new RedirectResult("customErrorPage.html");
            filterContext.ExceptionHandled = true;   
        }
    }
 }

Now let us understand what this actually does. as we can see this implements the interface as mentioned earlier and thus implements the method, OnException. This mehtod has the parameter ExceptionContext, the properties of which is mentioned in the table. In this custom filter we have handled the most common and neglected exception “Null Reference Exception”, arises when a value returning null is not handled/checked and used in further implementations. The custom filter derives the FilterAttribute as to be used as Attribute over the action or the controller directly like [CustomExceptionFilter]. In this implementation above, we have used almost allthe important properties of the ExceptionContext. First, the check is used for the ExceptionHandled which returns a boolean value if the exception has been handled or not. If not then Check for the type of exception arisen. Since here we have used the NullReferenceException, we check for that exception. Then if the conditions are satisfied/passed we manipulate the result and return the RedirectResult (ActionResult type) and let the users land on a custom error page created in the application, to avoid the yellow dreaded screen.

The use of the filter is pretty simple as this custom filter extends from the FilterAttribute. So based on the usage, this can be used as [CustomExceptionFilter] on the Controller Levelor the individual Action level,which ever is mandate.

//Over controller
 [CustomExceptionFilter]
 public class HomeController:Controller {
    //......
 }
//Over the Action
 [CustomExceptionFilter]
 public ActionResult Index() {
    //.......
 }

Now, lets discuss about the in built HandleAttribute. This is a built in class which is used similar way as a filter attribute in MVC applications. The most important thing is this attribute works only when the custom errors in the web.config is enabledor set to true.

the default mode for this element is RemoteOnly, which willonly work out when application is deployed and request is made from some other systems.
Lets look at the properties of the HandleError Attribute.

  • ExceptionType: This property, as the name suggests tells the attribute the type of exception it needs to handle.
  • View: This is the property, which we need to specify inorder to lets the attribute, land the end users after handling the exception
  • Master: If there is a special layout, we have for the error page, then this master can be set to that layout path, if left empty, this will take the default layout of the application for the error pages.

Thus, the below code snippet shows how to use the HandleError attribute

[HandleError(ExceptionType = typeof(NullReferenceException), View = "CustomErrorPage")] {
public Action Result {
    //........
    var testVal = null;
    //Unhandled and used..
 }

Caution: While reading through the Adam Freeman, a very interesting note of caution was mentioned while using the HandleError attribute. In the custom error page, we would be using the HandleError Info like the Stack Trace, the exception message etc. Since we would not like to show this to the end user, we need to put the stack trace inside a hidden field or make the html tag invisible because The view is not displayed tothe user unless the Exception.StackTrace is included in the View..

Conclusion & References

Thus, we learnt the creation of custom exception filters as well as the built-in filters in MVC applications.There are various ways/tools now tohandle exceptions, but stillwe can make use of these filters in order to avoid detrimental effects on our applications.
References: Adam Freeman-Professional Asp.Net MVC 4 & MSDN
I hope this would help developers & beginners. The concept is interesting when we use them. So start using and enjoy Coding. 🙂

]]>
/exceptionfilters-mvc/feed/ 0
Understanding Filters in MVC /understanding-filters-in-mvc/ /understanding-filters-in-mvc/#respond Sun, 08 Mar 2015 10:18:59 +0000 /?p=308 Introduction

There are scenarios when we have an implementation which will be reused at many places, which is not confined to a single place or method. This is fulfilled by the Filters in MVC. This is a very good concept introduced in MVC. The implementation which is mentioned above is called cross-cutting concerns. Thus, in simple terms, this add an extra logic to be implemented into the request being processed. Some of the examples of cross cutting conerns are Authorization & Output Caching. Lets discuss the different types of filters and how to create them and use them.

Getting started

Lets see first a glimpse of how the filters are used:-

namespace WebSecurityDemoTest.Filters
{
    public class WebSecurityAuthorize:AuthorizeAttribute
    {
        protected bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.Request.IsAuthenticated)
            {
                return false;
            }
            if (HttpContext.Current.Session["SessionHelper"] == null)
            {
                return false;
            }

            return true;
        }

        protected void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectResult("/");
            base.HandleUnauthorizedRequest(filterContext);
        }

    }
}

The above snippet is an example of an CustomAuthorize attribute. This attribute is a kind of Filter only. As this is defined here once and is used as an MVC attribute at many places as this needs to be checked at every controller level in every application where athorization is a must. Now lets see if this would not have been the case, how explicitly we would have checked at every action level.

namespace WebDemo.Controllers{
    public class DemoController : Controller {
        //..instances or constructor if any read onlyvariables used
        public ActionResult Index() {
         if(!Request.IsAuthenticated) {
           FormsAuthenticationn.RedirectToLoginPage();//MVC WebSecurity
          }
         //else rest implementation..
         }
     }
}

In the above snippet as you can see the Request.IsAuthenticated is checked at each action level, as the authentication needs to be checked before letting the anonymous user access the action. Thus is redundancy can be normalized by the use of Filters.

By just using [Authorize] or [CustomAuthorize] at the controller/action level. Thus we can say Filters are attributes that help in adding an extra check at the routing level. As this needs to be checked during the request processing only. Attributes are special classes which get derived from the namespace System.Attribute. 

Basically there are four types of filters that the MVC framework support. They are:

Filter Type Inheritance What this does
Authorization IAuthorizationFilter Runs first during the request processing before any other filters or the action execution
Action IActionFilter Runs before the action execution(Action level)
Result IResultFilter Runs before after the action execution(Action level)
Exception IExceptionFilter Runs only when any action method or any other filter throw exception

Before the invokation of any action method, the framework first looks for any definition of any filter attributes, then moves into the action method execution, which in turn gives an extra level of security to the application without writing redundant codes.
Lets look into each briefly.

Authorization Filter

This as the name suggests is required to provide authoization level in the application. The default attribute is [Authorize]. Its constructor also can accept parameters like Roles [Authorize(Roles=”Admin”)] which is very handy as the roles based application are very common now a days.
Authorization filters as mentioned in the table above runs the first before any filter’s execution or even before the action methos execution.
The below snippet shows how the Interface from which it extends looks like:

namespace System.Web.MVC {
    public interface IAuthorizationFilter {
        void OnAuthorization(AuthorizationContext filterCOntext);
    }
}

The best thing is we can customize the Authorize attribute by extending our custom authorize class from the Authorize attribute class and manipulate our logic there, which I have mentioned in the very first snippet. A nice tip here is to keep the Custom Authorize attribute very simple.

Built in Authorize attribute also accept the Users parameter like [Authorize(Users=”Suraj”,”Simon”,”Mike”)], which filters the action based on the users access level.

The use is also very simple. Either we can use at the controller level or the action level. Just place [CustomAuthorize]  before the controller class or the action methods.

Action Filter

The action filter can be used for any purpose, why any as the Interface it extends supports two methods to be invoked. Asmentioned in the table, this filter may be executed before the Action execution but not the first. Lets look at the Interface

namespace System.Web.MVC {
    public interface IActionFilter {
       void OnActionExecuting(ActionExecutingContext filterContext);
       void OnActionExecuted(ActionExecutedContext filterContext);
    }
}

As you can see in the above snippet, the interface has two methods to be defined, as the method names suggest, the first one OnActionExecuting tells us that before the action method has been invoked we can use this method, similarly the second one says that once the action method gets executed then this can be invoked. Now lets see each of them one by one .

actionFilter

OnActionExecuting Method

As we have already discussed this method is invoked before the action starts getting executed.The filterContext of type ActionExecutingContext passed as the parameter contains the following properties:

Name Description
ActionDescriptor This provides the details of an action method
Result This gives the result for the action method, the filter can be manipulated to cancel the request also

Lets look into the implementation of this method, in a custom action filter attribute:

namespace Filters.WebDemoInfra {
    public CustomActionFilter : FilterAttribute , IActionFilter {
       public void OnActionExecuting(ActionExecutingContext filterContext)
         if(filterContext.HttpContext.Request.IsLocal) {
              filterContext.Result = new HttpNotFoundResult();
          }
       }

Thus when we try and understand what we have written in the snippet above, we find that, whe before the action gets executed, this method gets invoked, the method OnActionExecuting returns a not null result i.e. HttpNotFoundResult, which will land the user on a 404 not found error page, even if the action has a view defined. This is the power of this filter.

Now lets look into it’s sister’s implementation.

OnActionExecuted

This method as defined ago, can be invoked to span the execution of the action method being processed based on the request. Lets check with the help of an example which will measure the time taken for the action to complete the full execution.

namespace Filters.WebDemoInfra {
    public class CustomActionFilter : FilterAttribute , IActionFilter {
      private StopWatch watch; //System.Diagnostics
      
      public void OnActionExecuting(ActionExecutingContext filterContext) {
         timer = Stopwatch.StartNew();
       }

      public void OnAcionExecuted(ActionExecutedContext filterContext) {
       timer.Stop();
       if(filterContext.Exception == null) {
         filterContext.HttpContext.Response.Write(string.Format("Total Tme taken: {0}", timer.Elapsed.TotalSeconds));
       }
    }
  }
}

The above snippet is a very simple sippet to understand. The private variable is of type StopWatch which is an in-built class in the namespace System.Diagnostics. In the executing method, we are initializing the timer and after execution of the action method since the executed method gets invoked, so to the httpContext which contains both Request and response as well, we assign the time elapsed in seconds to the Response.

Lets look at the properties provided by the OnActionExecuted method.

Name Description
ActionDescriptor This provides the details of an action method
Cancelled If incase the action has been cancelled by any other filter this property returns true
Exception If any filter or any action throws an exception, it is returned by this property
ExceptionHandled If any filter or any action throws an exception and it has been handeled, this property returns true
Result This gives the result for the action method, the filter can be manipulated to cancel the request also

Thus, this was all about the Action filters.

Result Filter

These are quite similar to the Action Filters. These are the filters which are invoked or operate on the results being produced by the Action Result methods. This implements from the IResultFiler interface which also looks quite similar to the IActionFilter. Lets see how:

namespace System.Web.MVC {
    public interface IResultFilter {
       void OnResultExecuting(ResultExecutingContext filterContext);
       void OnResultExecuted(ResultExecutedContext filterContext);
    }
}

OnResultExecuting

OnResultExecuting method gets invoked when result has been returned by the Action method but before the the action is executed fully. This also has the same properties as the OnActionExecuting method as described in the table.

OnResultExecuted

OnResultExecuted method gets invoked after the action result has been executed. Here also the parameter filterContext contains the same properties as the OnActionExecuted method has described in the table above. The demostration
can be the same Timer as described in the Action filter section.
Below snippet will show you the built-in Action and Result Filter class.

public Abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter {
  public virtual void OnActionExecuting(ActionExecutingContext filterContext){
     }

public virtual void OnActionExecuted(ActionExecutedContext filterContext){
     }

public virtual void OnResultExecuting(ResultExecutingContext filterContext){
     }

public virtual void OnResultExecuted(ActionExecutedContext filterContext){
     }
   }
}

Using Global Filters

This is a very nice feature that can be implemented in the MVC application. Global.asax as we all know is the heart of the MVC web application. The Application_Start method is called from here whenever the application starts. We have a FilterConfig.cs file inside our App_start folder, where we can find a static method called RegisterGlobalFilters. In this method we register our custom filter which needs to be invoked through out the application which is applied to all controllers and actions in the application. Lets see how we register:

namespace Filters { 
    public class FilterConfig {
        public static void RegisterGlobalFilters(GLobalFilterCollection filters) {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new CustomAllAttribute());
        }
    }
}

Thus the second filter added/registered as the global filter is our custom attribute. This custom attribute implementation needs to be thought upon and then written as this would be used through out the application, so this should also be very simpleso that can be manipulated and maintained at any point of time.

Filter Ordering

In MVC framework, the order in which the filter get invoked (if there are more than one at the action), doesnot matter much. But even if you wish to add ordering based on the business logic we have, then we can use the Order keyword which accept an int value to set the order of the Filter invokation/execution. Lets take an example and understand

[ProfileA(Message = "First")]
[ProfileB(Message = "Second")]
public ActionResult Index() {
   //Implementation
 }

In the above snippet we have two custom filters ProfileA and ProfileB that take message as parameter and print that using the context response write method. Thus, this would write

“First” (For OnActionExecuting)

“Second”  (For OnActionExecuting)

“Second”  (For OnActionExecuted)

“First”  (For OnActionExecuted)

Thus if we wish to modify the order like the “Second” would come first then the “First”, then we need the use of Order.

[ProfileA(Message = "First"), Order=2]
[ProfileB(Message = "Second"), Order=1]
public ActionResult Index() {
   //Implementation
 }

Thus, here the output as previous will change based on the order specified in the above snippet. Thus based on the requirement we can specify as many filters may it be built-in or custom and set the order of execution also. This is how flexible MVC framework is. 🙂

Conclusion

Thus here I tried to explain the Filters that are being used in MVC framework. Here I have discussed Authorize, Action & Result filters. I will try and explain the Exception filter in the next section.
Thanks for your patience.
Corrections and suggestions are humbly accepted. 🙂

References

  • Adam Freeman- Pro ASP.NET MVC
]]>
/understanding-filters-in-mvc/feed/ 0
Mini Profiler from Nuget /mini-profiler-from-nuget/ /mini-profiler-from-nuget/#respond Tue, 24 Feb 2015 19:16:35 +0000 /?p=272 Introduction

Being developers we always face a challenge, to debugand optimize the queries we have written for any request made to the server. Getting the exact time of the queries requested for each page load is next to impossible. Usually we count one two three.. and see the average.. :D. But is this the solution, how often can we do this!! This is not as developers we would want. The network tab in the developers tool gives us the information about the per request made for a page load, but that is not enough for us to know which query is taking more time and which query reuires optimization.
As MiniProfiler suggests

It is capable of profiling calls on raw ADO.NET (SQL Server, Oracle, etc), LINQ-to-SQL, EF (including Code First), Lightspeed and a range of other data access scenarios.

Is’nt that great!! Yes indeed.

Versions

There are different versions available for .NET MVC projects based on the MVC versions. We can get the Install Package with versions from the below provided Links.

Get Started

As we all know, for getting the package, we use the Package Managerconsole or Nuget Package. I would be using the PM console for this purpose. I will be installing Miniprofiler for MVC application. Check the image below:

Capture1

This will add the references to the project. Not ending with this, there comes next the configuration which needs  to be done. Check out the configurations below.

Configurations

At first in an MVC application, as we know the heart of the MVC lies in the Global.asax, so we need to configure here first. There is no hard and first rule like, this but I follow this. 😀

protected void Application_BeginRequest()
        {
         if(request.IsLocal)MiniProfiler.Start(); 
         //or any number of other checks, up to you, if for all request you need profiling then remove the if condition
        }

        protected void Application_EndRequest()
        {
            MiniProfiler.Stop(); //stop as early as you can, even earlier with Mvc MiniProfiler.MiniProfiler.Stop(discardResults: true);
        }

This is all we need to do to let Miniprofiler get registered to the application. Now comes the question how will the Miniprofiler be displayed to the user(developer). This is simple, we just need to check which page load takes more time and has the maximum number of qeries being called at the same time. Then we just need to place a simple peice of code snippet mentioned below, in the view page, as that needs to be rendered on the view only.

@using StackExchange.Profiling //namespace to be added
<head>
    @MiniProfiler.RenderIncludes()
</head>

Just note the namespace used : using StackExchange.Profiling

Thus when we run the application, the view/layout wherever the RenderIncludes() is there the profiling is done and displays the entire list of queries executed and the time taken. The below is how the profiler looks:

Capture2

Now you would be wondering where did I mention the profiling to connect to the Entity Framework!! Hold on.. For that we need to install another package through the same PM console and that is Miniprofiler for the EF version based on used in the application.

Capture3

 

this will add the package and all the dependencies if not present will be added. Then we need to add a simple code line to the Application_Start method in the Global.asax as below:

MiniProfilerEF.Initialize();

This as it explains itself, will initialize the profiling for the Entityframework operations or the db operations and show the user the entire sql querybeing called/executed during the page load and also the time taken.

Capture4

 

The highlighted part in the above image, show the sql query being called and how many times. The red mark indicates that there are duplicate calls being made in the page load, based on which we will be optimizing the queries and reduce the number of db operations to make the page load faster, thus improving performance.

I hope this small peice helps developers beginning their careers. Any modifications, suggestions are mostly welcome.
CP

]]>
/mini-profiler-from-nuget/feed/ 0
Using Font Awesome from Nuget /using-font-awesome-from-nuget/ /using-font-awesome-from-nuget/#respond Thu, 19 Feb 2015 19:29:02 +0000 /?p=264 Introduction

Still using images for icons!! Now in every other web site/web pages, we find intensive use of icons to help user navigate and understand easily the whole purpose. Making the icons simple and understandable from user point of view is what the motive stands here. But using images for icons!! would that be fine!!Would not that affect the page performance as the image has some size right readers!!Let me introduce here to you a small package upgraded and light-weight and easy to use which makes the GUI so simple to implement. Lets get started..

Getting Started With Font-awesome

As the name itself suggests, this package is awesome. From a github post,

Font Awesome is a full suite of 519 pictographic icons for easy scalable vector graphics on websites, created and maintained by Dave Gandy.

These are simple text, which can easily be manipulated like normal texts using the fonts. You stretch or enlarge an image(.png) icon it gets blurred, it looks bad in simple language. You enlarge any font from the package of fontawesome it would never get blurred or pixalated. Moreover no width no height is required as used in image as attributes, just increase the font-size, it manipulates the icon.
The best thing is this package can be downloaded from the Nuget Package or the Package manager console too. The below image will show how to install the package from the PM Console.
Capture1
As you can see in the above Image, you need to get to the PM Console window and hit the yellowed Install command.
Install-Package font-awesome -Version 4.1.0
After Installing you may face some error for the assembly package. That is the dependencies on this library and their version may cause some issue here. As for example which I have encountered while adding in my project was the assembly Web.Optimization as this version of this library require varsion 1.1.3. . If any package upgradation/update is required as its dependencies then without any hesitation just update the packages. Infact, the updates for the packages should be checked and updated regularly. After adding the following files/folders get added to the web project.Capture2
When added/installed two css files are added for the font-awesome. To a shock,both the files are same, now wonder why then both??Because a small difference between both matters a lot: .min.css is the minified version of the css file that is small light and good for performance. So, while adding the reference in the layout, minified version is preferred/made mandate actually.
Capture3
The other thing that gets added is shown in the above image.
Lets get some information about the extensions of the files inside the folder. Information are from WIKI:

.eot :- Embedded Open Type fonts are a compact form of OpenType fonts designed by Microsoft for use as embedded fonts on web pages.

.svg :- This is common and known, but still, Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation.

.ttf :- This is developed by Apple, stands for True Type font. This means the font can be scaled to any font size even without tampering the quality.

.woff :- Stands for Web Open Font Format. This is a font format to be used in the pages rendered on web, that is Webpage.

.otf :- Stands for Open Type Font

This was all about the extensions of the files in the folder.

Usage

To use this as I have already mentioned, we need to have the minified version of the .css file in the layout itself, as the icons would be used intensively. The reference goes as below:

<link href="~/Content/font-awesome.min.css" rel="stylesheet" />

Now to use the class out of the .css defined classes, the use is as below:-

<i class="fa fa-2x fa-fw "></i>

As you can see in the above snippet, this is the way fontawesome classes defined in the <em>.css</em> file.

Class fa is defined as below:-

.fa {
  display: inline-block;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

fa-fw is defined as below:

.fa-fw {
  width: 1.28571429em;
  text-align: center;
}

These are the definition of the classes defined in the css. You think I have missed fa-2x, ok Guys there are fa-1x, fa-3x and more as they represent the font-size simplified as <em>1em, 2em, 3em & similarly..</em>

Then the actual class for the icon is to be used along with these which define its characteristics. The class name is prefixed with “fa-“. The many icons along with the classes that can be used are given in the link/cheatsheet:-Font Awesome Cheatsheet
You find a lots of icons with their class name to be used. Just specify the name as below and see the icon onscreen. Even another fact is we can even change the color of the icon as we want, using the similar color css property.

<i class="fa fa-2x fa-fw fa-adjust"></i>

Conclusion

This is how this awesome Font Awesome can be used so simply in our projects. Thus reducing the time & size for the page being loaded. So start using this beautiful, light-weight and authentic library for the icons to be used.

References

Font Awesome Examples
Wiki
CP

]]>
/using-font-awesome-from-nuget/feed/ 0
Sart with C# from scratch- Part 1 /sart-with-c-from-scratch-part-1/ /sart-with-c-from-scratch-part-1/#respond Sun, 15 Feb 2015 10:17:29 +0000 /?p=255 Topics to be covered:-
  • Welcome to C#
  • Working with Variables, Operators & Expressions
  • Understanding your first C# program

Welcome to C#

C# .NET is a powerful language, which is generally called Component Oriented Language. Now we have heard of Object Oriented Language, but what is component oriented language!! Though the difference is fairly blurr and thin, but the reason why this new concept came associated with C# is that a new technique was to be introduced that would develop software combining some pre-existing features (OOP) and welcoming some new components. Some of the components are :

  • Properties
  • Methods
  • Events
  • Attribute(Metadata-Data about Data)
  • Assemblies/Packages

Another major characteristic is introduction to SOC and SOA. SOC is separation of concern via partial classes in c# and SOA is service oriented architecture concept while programming in C#.

Versions in C#

I am mentioning below the versions till date. Data issued from C# Indepth. Please visit or follow the book to know more about the different Versions.

  • C#- version 1
  • C#- version 2: As mentioned, in this version, Generics, Nullable types(), anonynous types & Iterators(blocks) were introduced.
  • C#- version 3: As mentioned implicit typing, object and collection initializers, anonymous types, automatic properties, lambda expressions, extension methods, query expressions were introduced.
  • C#- version 4: As mentioned dynamic typing, optional parameters, named arguments, and generic variance were introduced.
  • C#- version 5: As mentioned asynchronous functions, caller info attributes(This is a very new concept and an interesting one too. These attributes track information about the calling methods/properties and many more.), and a tweak to foreach(one of the example is Parallel.Foreach(with Lambda expression)) iteration variable capture were introduced.

A small incident to share, I always wondered why C sharp?? It is kind of a successor for C++ or what? I always wondered, and I feel many beginner developers would be wondering. Thanks to Wiki the datawarehouse for every bit of concept in the world for letting me know why? Without any delay, straight from the WIKI,

The name “C sharp” was inspired by musical notation where a sharp indicates that the written note should be made a semitone higher in pitch. The sharp symbol also resembles a ligature of four “+” symbols, which thus implies that it is an increment of C++.

Now lets get along and start learning from basics.

Camel & Pascal Case Notations

Every time a developer gets into these concepts, but sometimes beginners like me would wonder what these actually are!!.
Camel case are used for naming fields where as Pascal case are used for naming properties, function names. In Pascal case, the starting letters in the multiword name are capitalized where as in Came case except the very frst letter all are capitalized like below:

  • Pascal Case:- GetSumFromNumbers
  • Camel Case:- getFirstNumber

Working with Variables, Operators & Expressions

Before getting into the variables, lets get into what is an identifier. Identifiers are the names that are used to identify elements in the program. In C#, there are certain conventions to be followed:

  • Only letters are allowed(may it be uppercase or lowercase), digits and underscore(_) characters are allowed.
  • An identifier should always start with a letter.

For example, _getSum, GetSum, Get_sum are valid identifiers. Just to remember or keep in mind everytime that C# is case sensitive so getSum and GetSum are different and give different meanings.
Keywords, there are many keywords that are predefined in C#, for more info on the keywords, follow the below link: C# keywords

Now lets get back to our topic of discussion, variables. A variable is a location with memory or storage location that stores/holds a value. A variable in a program holds a unique name, its like madatory to give it a unique name. A variable holds temporary information. A variable is used to get the value that it holds after assigning. Below I specify the naming conventions to be followed while declaring variables specified by Microsoft .NET team:

  • Underscores are advised not to be used
  • Case differing names for variables should be avoided. Like, abcTest or AbcTest to be used in the same file and same time. This would also mean Identifiers with same name and different case should be avoided.
  • It is advised to start the name with a lowercase. This would be consistent through out as it would lead to easy mantenance.
  • Camel case notations should be used, forexample, abcTest, myVariable, as such.

Declaring Variables is easy and simple. Usually keyword var is used when the type is to be implicitly decided. If any datatype is already used during declaring the vriable, then it is explicitly typed.

var setAge; //implicitly typed
int setAge; //explicitly typed
setAge = 45; //values assigned

As in the above peice of snippet, you can see the statement ends with a semicolon “;” that as simple marks the end or compiler to know that the statement ends here. Equals operator is used to assign the value to the declared variable. C# also uses same the operators that we as developers have been using in the former programming languages (+(plus), -(subtraction), *(asterix/multiplication), /(divide) and also the modulo operator(%)). These are as we know called the arithmetic operators. We cannot apply the arithmetic operations on the datatypes except int(integer type) in a similar way.

int a = 4 + 3;
string b = "4"+"3";
Console.Writeline(a);//Prints 7
Console.Writeline(b);//Prints 43 not 7

However using explicit conversion, string can be converted into integers. For incrementing the values, the increment and decrement operators are also strongly followed in C#.

count= count + 1; //Can be incremented but should not be written like this
count++; //This is how increment should be done

count = count - 1;
count = count--;

Understand your first C# program

As we all know, every program follow a common rule that is Input, Process & Output. Lets have go at it.

using System;
namespace ConsoleDemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName; //Variable for storing string value
            string lastName;

            //Displaying message for entering value
            Console.WriteLine("Please Enter Your First Name");
            //Accepting and holding values in name variable
            firstName = Console.ReadLine();

            Console.WriteLine("Please Enter Your Last Name");
            lastName = Console.ReadLine();

            //Displaying Output
            //{0}{1} take the variable names that are assigned during the runtime by the user
            Console.WriteLine("Welcome {0} {1} in your first C-sharp program", firstName,lastName);

            //Holding console screen
            Console.ReadLine(); 
        }
    }
}

When we run the above program, we get the below output. I am showing the output step wise, so that you get to know the importance of the Console.WriteLine & Console.ReadLine

.output1 As we see in the image, the console window opens up when the project runs and asks for the first name as we see in the program first comes Console.WriteLine(), then when user enters the name Console.ReadLine(), plays its role and stores it in the variable memory firstName.

output2 As we see in the image, the console window opens up when the project runs and asks for the last name as we see in the program first comes Console.WriteLine(), then when user enters the name Console.ReadLine(), plays its role and stores it in the variable memory lastName.

output3  Now when a final enter is pressed by the user with curosity to know what the program gives! Yes it gives the desired out put. It concats the variables where the names/values entered by the user are temporarily stored in memory. {0} {1}, this actually contain the values entered by the user when asked and as mentioned concats the input and displays the full name as the output. This could also have been achieved by using the “+” operator like: 

string fullName = firstName + " " + lastName; //+ operator concats the strings
Console.WriteLine("Welcome {0} in your first C-sharp program", fullName);

There are many libraries that may be used in your program. These libraries need to be mentioned at the top of your program i.e. which is called Namespaces and they are used using a using keyword. 😀 Yes so many use…!!

When on the console window, something needs to be displayed, Console.WriteLine() is used and when we need to take the Input from the user and store in memory, Console.ReadLine() is used. This is a simple and basic difference. The {0} used in our program, acts as asimple placeholder where the dynamic values are used by specifying the argument at the end. The many the arguments, the many the placeholders to be used.

Conclusion

Thanks guys for having patience and reading through. This is what I could cover in the first part and will continue some more interesting topics in the second part. Lets learn Lets explore and Lets share…

Any suggestions and corrctions are humbly accepted as we all keep learning at every step.
Follow the C# 6 New Features for more info on the upcoming version C# 6.

Refrences

CP

]]>
/sart-with-c-from-scratch-part-1/feed/ 0