Thursday, June 27, 2013

MVC 5 tutorial

Wednesday, May 29, 2013

Simple Membership MVC4


Simple Membership

The Asp.Net MVC 4 introduced the many new features one of the main features is SimpleMembership. SimpleMembership is also support for Outh. SimpleMembership has been designed as an advanced of previous ASP.NET Role and Membership provider system.
Whenever we create a new MVC 4 project, Simple Membership is automatically implemented and the related views, models and controllers are also automatically generated. Let‘s we look at this bellow image.








WebSecurity


Simple membership provides the new class called WebSecurity. MSDN definition (“Provides security and authentication features for ASP.NET Web Pages applications, including the ability to create user accounts, log users in and out, reset or change passwords, and perform related tasks.”-MSDN).
In the class have SimpleMembership related methods are there, I would explain some basic methods and how to use in our projects.

1) Login

WebSecurity.Login(UserName,Password, persistCookie:RememberMe)

The login method to check the given user is authorized person or not, it has three parameters Username-The User Name, Password-The user password, and persistCookie- It is (Optional) true to specify that the authentication token in the cookie should be persisted beyond the current session; otherwise false. The default is false.

1) LogOut

WebSecurity.Logout();

The logout method is used to clears all authentication cookies from the cookie cache in other words to disconnect the user

3) Create Account

WebSecurity.CreateAccount(userName, password, requireConfirmationToken = false);
WebSecurity. CreateUserAndAccount(userName, password, propertyValues = null, requireConfirmationToken = false);
If our application wants more detail about the user we will use CreateUserAndAccount method otherwise we use Create Account
The bellow image shows the all other methods of web security




Roles  

SimpleMembership provides another one class named as Roles. . MSDN definition” Manages user membership in roles for authorization checking in an ASP.NET application. This class cannot be inherited.”
In the class have Role based methods are there, I would explain basic methods and how to use in our projects.

Roles.CreateRole("RolesName");
 The method has been used to add a new role the database. It has single parameter named as rolename.
2)DeleteRole
Roles.DeleteRole("rolename");
The method has been used to Removes a role from the data source. . It has single parameter named as rolename.
The bellow image shows the all other methods of websecurity roles


Database structure


Simple membership uses the entity framework model first approach whether when we execute the application it would be automatically create the database and tables. Let we see the tables
1)      UserProfile-It is a extension table for users.
2)      webpages_Membership-User security related data’s are their like “password , password salt etc”.
3)      webpages_OAuthMembership- Outh related information’s  stored in this table.
4)      webpages_Roles- The roles are stored like(“Admin, Editor etc..”).
5)      webpages_UsersInRoles- which user have which role that informations are stored this table.


Conclusion

In this article I simply explained how to use SimpleMebership, it’s only for beginners



Tuesday, May 14, 2013

How to call a stored procedure through MVC 4 and Entity Framework 5.0


Create database


  •         Just we have to create a simple database named as student
  •         We also create simple table named as student
  •        Write a simple stored procedure

USE [Student ]
GO
/****** Object:  StoredProcedure [dbo].[GetStudents]    Script Date: 05/14/2013 12:56:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[GetStudents]

As
Begin
   select * from dbo.StudentDetails
End

Add Edmx

As we know how to add edmx file. In the second step of adding edmx file (choose your database objects and settings). Let we choose the stored procedure and functions checkbox and expand the checkbox and select which stored procedure you want. Then proceed the other steps finally we get an edmx files and related context classes.



As we know about EDM (Entity Data Model) However, just remember the Storage model, It is your database design model which includes tables, views, stored procedures and their relationships and keys.The Storage model stored procedure configuration like below 

public partial class GetStudents_Result
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Class { get; set; }
    }

  public virtual ObjectResult<GetStudents_Result> GetStudents()
        {
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetStudents_Result>("GetStudents");
        }


Then we access the stored procedure in controller. So we create a object for our entity class 
            
            StudentEntities entity = new StudentEntities();

            var sd = entity.GetStudents().ToList();
            return View(sd);

Conclusion 

If any one have any doubts and corrections plese comment me  Thanks
Abiruban@ Niventh





Monday, May 6, 2013

Email Tracking using ASP.NET


We have many more ways to advertise a business or a product. But one of main way is Email through advertisement.
However, how many users opened their advertisement emails or newsletter emails. So we needs the opened email counts. In this article describes, how can we count the opened email?
   public void SendMail()
   {
       string toEmail = "abiice.1987@gmail.com";
       System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
       eMail.From = new System.Net.Mail.MailAddress("test@test.com");
       eMail.To.Add(toEmail);
       eMail.Subject = "test track";
       eMail.IsBodyHtml = true;
eMail.Body = "test body<IMG height=1       src='http://localhost:12207/EmailTrack/emailtrack.aspx?emailsent='"+toEmail+"'   width=1>";
       System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();
       SMTP.Send(eMail);
       eMail.Dispose();

    }

The above code describes the, how to send an email through Asp.Net. We needs Track the email so we could append an image inside the email body and we add a query string value to the SRC attribute. The query string helps to identify the user.
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            if (Request.Params["emailsent"] != null)
            {
            }
        }
    }
Then user open an email the request comes to web server and we get a querystring values and maintain the counts using database


Friday, May 3, 2013

ASP.NET MVC routing


MVC routing

In ASP.NET MVC one of the main parts is routing. The routing is helps to map the particular view and particular controller.
When we create an ASP.NET MVC application routing is preconfigured in web.config and Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Account", action = "Login", id =     UrlParameter.Optional }
            );
}

protected void Application_Start()
{
      RegisterRoutes(RouteTable.Routes);
}

The above code shows preconfigured routing on Global.asax.
When we run the our an ASP.NET MVC application the request comes to "Application_Start()"

 The method inside we called the routing configuration method so at the same time RegisterRoutes method also fired and registered the routing configurations.
RegisterRoutes method has some default routing tables, the default routing table has some segments, and the segments have arguments.
First we look at the first segment "name". It is the name of the routing table.
Second segment "URL" have some arguments, the first argument mention the controller name second argument mention the action method and the third argument mention the query string .
The third segment "defaults" provide the some default values. Occasionally we don't have provided any controller, action and id that time it would be took the given default values.

More detail about routing  read the scottgu blog 

Thursday, April 11, 2013

Calculate age in C#

Hi,
Try this method it might be help to calculate a person age


     public static Int32 GetAge(this DateTime dateOfBirth)
        {
            var today = DateTime.Today;

            var a = (today.Year * 100 + today.Month) * 100 + today.Day;
   var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 +                          dateOfBirth.Day;

            return (a - b) / 10000;
        }

Sunday, March 31, 2013

Multiple File upload with image preview in Asp.Net


In the last week I searched in the Google for multiple image upload with image preview in Asp.Net while I find some articles however it wasn’t satisfied me. Finally I got the Mr Sam article it was very amazing article. Although the example project was very confused to me. So I modified the project and Attached here
Thanks
Niventh@ abiruban 

Thursday, March 21, 2013

How to implement Dependency Injection in MVC



Introduction

In This article describes the, How to implement Dependency Injection in MVC. Dependency Injection is allows for easier TDD and Dependency Injection used avoid tight coupling.

How can we do this?  We do this in five steps.

Step1: Add Model class
Step2: Add data access class
Step3: Create UnityDepentacyReslover
Step4: Configure the Global.asax
Step5: Add Controller

Let's we create a simple MVC application named as DependencyInjectionPOC.

Step1: Add Model class

Let's we create a new model class name as "Student", it's a DTO (Data Transfer Object) class used to transfer data across multiple layers of an application. Just look at this code in bellow.

     public class Student
    {
        public int StudentId;
        public string StudentName;
    }

Step2: Add data access class

We create an Interface named as "IStudentRepository”. Interface can have multiple methods weather we have simply used only one method. In this time your mind has ask some question, why we would create Interface. We want swap the mock class (Used to define TDD) so only we used Interface.  How to swap the class?  I will be describe in to next blog


  public interface IStudentRepository
    {
        void AddStudents(Student student);
    }

Then we create a data access class named as "Student Repository". This class must be inherited into IStudentRepository Interface then we implement the Interface method in to "StudentRepository" class as shown in the following code

  public class StudentRepository : IStudentRepository
    {
        public void AddStudents(Student student)
        {
            List<Student> StudentList = new List<Student>();
            StudentList.Add(student);
        }
    }


Step3: Create UnityDepentacyReslover

Let's we create a class named as "UnityDepentacyReslover". This implementation will accept an IUnityContainer and will use this container for resolving the requested types. If the DependencyResolver is unable to resolve a type, it should always return null for the GetService method and an empty collection for the GetServices method. That is why a try catch is used in the UnityDependencyResolver.

   public class UnityDepentacyReslover : IDependencyResolver
    {
        IUnityContainer Container;

        public UnityDepentacyReslover(IUnityContainer Container)
        {
            this.Container = Container;
        }
        public object GetService(Type ServiceType)
        {
            try
            {
                return Container.Resolve(ServiceType);
            }
            catch
            {
                return null;
            }
        }
        public IEnumerable<object> GetServices(Type ServiceType)
        {
            try
            {
                return Container.ResolveAll(ServiceType);
            }
            catch
            {
                return null;
            }

        }
                       
    }

Step4: Configure the Global.asax

Let's we create a class name as "UnityConfig". This class is used to configure the UnityContainer.

  public class UnityConfig
    {
        public static void RegisterUnityContainer()
        {
           // A simple, extensible dependency injection container.
            UnityContainer container = new UnityContainer();
            //RegisterType a type mapping with the container, where the created instances
            container.RegisterType<IStudentRepository, StudentRepository>();
            DependencyResolver.SetResolver(new UnityDepentacyReslover(container));
        }
    }

Then call the above method into Global.asax , in the Application_Start method. Like

     protected void Application_Start()
        {
            UnityConfig.RegisterUnityContainer();
           
        }

Step5: Add Controller

Then we create a new controller named as "StudentController"

   public class StudentController : Controller
    {
        [Dependency]
        public IStudentRepository repository { get; set; }

        public ActionResult Index(Student student)
        {
            repository.AddStudents(student);
            return View();
        }

    }

Conclusion

This post is used to, How to implement Dependency Injection in MVC