Tag Archives: asp.net

STEP BY STEP INSTRUCTION FOR BUILDING RESTFUL API WITH ASP.NET WEB API – PART II

Register the repository

when install the ninject packages, it will create a file NinjectWebCommon.cs  under the App_Start foler, open it, go the method: RegisterServices, register your service.


  private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind().To().InSingletonScope();
            kernel.Bind().To().InSingletonScope();
        }     

what is this do, you don’t need new a object, instead of the ninject container will create a instance in your controller or repositaory class. And the ninject also will handle the life cycle of the object.

Create  MovieDataViewModal.cs file under the ViewModal foler, we using it for validation and create and put Movie record.


  using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MovieDemo.ViewModal
{
    public class MovieDataViewModal : IValidatableObject
    {
        public int MovieId { get; set; }
        [Required]
        [Remote("DoesTitleExist", "Movies")]
        public string Title { get; set; }
        [Required]
        public string Genre { get; set; }
        [Required]
        public string Classification { get; set; }
        [Range(0, 5)]
        public int Rating { get; set; }
        public int ReleaseDate { get; set; }
        public string[] Cast { get; set; }

        public IEnumerable Validate(ValidationContext validationContext)
        {
            var result = new List();

            if (Title == Genre)
            {
                result.Add(new ValidationResult("Title can not be the same as your Genre", new string[] { "Title" }));
            }
            return result;
        }
    }
}

In the Global.asax add the config for using Automap


Mapper.Initialize(config =>
            {
                config.CreateMap<MovieData, MovieDataViewModal>().ReverseMap();
            });

Create the controller

In the solution explorer, create MoviesController.cs undert the Controllers foler


using System;
using System.Web.Http;
using MoviesLibrary;
using System.Web.Http.OData;
using MovieDemo.Services;
using AutoMapper;
using MovieDemo.ViewModal;

namespace MovieDemo.Controllers
{
    public class MoviesController : ApiController
    {
        private readonly IDataRepository _repo;

        public MoviesController(IDataRepository dataRepository)
        {
            _repo = dataRepository;
        }

       
        [EnableQuery(PageSize = 5)]// this is for suport url query working with oData
        public IHttpActionResult Get()
        {
            try
            {
                var movies = _repo.GetAllMovies(); 
                return Ok(movies);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }
    

        //GET: api/Movies/5
        public IHttpActionResult Get(int id)
        {
            try
            {
                if (id > 0)
                {
                    var movie = _repo.GetMovieById(id);
                    var result = Mapper.Map(movie);
                    if (result != null) return Ok(result);

                    return NotFound();
                }
                return NotFound();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // POST: api/Movies 
        public IHttpActionResult Post([FromBody]MovieDataViewModal newMovie) 
        {
            try
            {

                if (newMovie == null)
                    return BadRequest("Movie can not be null");

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var movie = Mapper.Map(newMovie);

                if (_repo.CreateMovie(movie)) return Ok(newMovie);

                return Conflict();

            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // PUT : api/Movies/5
        public IHttpActionResult Put(int id, [FromBody]MovieDataViewModal movieModified)
        {
            try
            {

                if (movieModified == null)
                    return BadRequest("Movie can not be null");

                if (movieModified.MovieId <= 0 && movieModified.MovieId != id)
                    return Conflict();

                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var movieData = _repo.GetMovieById(id);
                if (movieData != null)
                {
                    var movie = Mapper.Map(movieModified);
                    _repo.UpdateMovie(movie); 
                    return Ok();
                }

                return NotFound();

            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }

        public IHttpActionResult DoesTitleExist(string title)
        {
            if (_repo.DoesTitleAlreadyExist(title))
            {
                //Invalid
                return Ok();
            }
            //Valid
            return BadRequest("Title already existing");
        }
    }
}

then run the solution, open postman make query:

here is the example: http://localhost:53871/api/movies?$skip=2&$top=1
api06.PNG

for allmovies: api05.PNG

more detail  about odata query:
http://www.odata.org/documentation/odata-version-2-0/uri-conventions/

How to write a method render out a List that including all of your class members’ name

To write a Method Render a list to include all class names is very useful (perhaps not for my current project – but that is another story!). To achieve this we need to render all the member variables out from an existing class and put it into List(). This is pretty simple, here is my method:

        public static List GetMenuNodes()
        {            
            var memberOfObject = typeof(yourClassOrinstanceOfClass).GetFields();
            List propertyList = new List();
            for (var i = 0; i < memberOfObject.Length; i++)
            {               
                propertyList.Add(memberOfObject.GetValue(i).ToString());
            }
            
            return propertyList;
        }

Create custom section in Web.Config file

In previous my project that I alway put my infomation to the appSetting inset of my web.config file. But working for currently company that I learned how to create a custom section in the web.config file and could read it from the entire website and it is much better and it is very easy to achieve that. And it also help you organize your web.config.

For example I have those settings

<appSettings>

<add key=”business” value=”youremaile@hotmail.com” />
<add key=”IsSandbox” value=”true” />
<add key=”currency_code” value=”AUD” />
<add key=”return” value=”http://xxxxxx/Url&#8221; />

Now I like create a Section just named PayPalAPI

First, create the section named “PayPalAPI” just below your configuration.

<configuration>
<configSections>
<section name=”PayPalAPI” type=”YourProjectName.ConfigFile.PayPalAPIConfiguration,YourProjectName.ConfigFile” requirePermission=”false” allowLocation=”true” allowDefinition=”Everywhere” />

Second, move all the property inside of your appsettings to like this put it before </configuration> closed.

like this

<PayPalAPI IsSandbox=”true” Currency_code=”AUD” ReturnUrl=”http://xxxxxx/Url&#8221; />
</configuration>

Final step, just create a PayPalAPIConfiguration inherit from ConfigurationSection

Here is the sample:

public  class PayPalAPIConfiguration : ConfigurationSection
    {
        public static PayPalAPIConfiguration GetConfig()
        {
            var config = (EmailAccountConfiguration)ConfigurationManager.GetSection("PayPalAPI");
            return (config == null) ? new PayPalAPIConfiguration () : config;
        }
        //below is read for the property
        [ConfigurationProperty("isSandbox", DefaultValue = "", IsRequired = false)]
        public string IsSandbox
        {
            get
            {
                return this["isSandbox"] as string;
            }

            set
            {
                this["isSandbox"] = value;
            }
        }


        [ConfigurationProperty("currency_code", DefaultValue = "AUD", IsRequired = true)]
        public Boolean Currency_code
        {
            get
            {
                return (Boolean)this["currency_code"];
            }

            set
            {
                this["currency_code"] = value;
            }
        }
[ConfigurationProperty("returnUrl", DefaultValue = "http://xxxxxx/Url", IsRequired = true)]
        public Boolean ReturnUrl
        {
            get
            {
                return (Boolean)this["returnUrl"];
            }

            set
            {
                this["returnUrl"] = value;
            }
        }

    }

How to use it, since it allow use every where so inside your project just call this:

PayPalAPIConfiguration .GetConfig().IsSandbox;

Create custom HtmlHelper to Render different type of Twitter Card

In this day, all the social media site is very important, I have task need implement the Twitter Cards into all the existing projects.

Render partial View is fine, but since just need same meta data, so I just create a custom HtmlHelpler, I put my works here, anyone think that helpful, could plug into your site.

public static class TwitterCardHelper
    {
        //this is the base method
        public static MvcHtmlString TwitterCard(this HtmlHelper html, string cardType, string title, string description, string image = null, object listAttributes = null,object productAttributes = null)
        {           
            
            var format = @"<meta name=""twitter:{0}"" content=""{1}"" />";
            var sb = new StringBuilder();
            var config = ProjectConfigurationSection.GetConfig();
            sb.AppendFormat(format, "card", html.Encode(cardType));
            sb.AppendFormat(format, "site", config.ProjectEnvironment == ProjectEnvironment.Production ? config.ProjectDisplayName : String.Format("{0} ({1})", config.ProjectDisplayName, config.ProjectEnvironment.GetDescription()));
            sb.AppendFormat(format, "title", html.Encode(title));
            sb.AppendFormat(format, "description", html.Encode(description));
            if (cardType == "summary" || cardType == "summary_large_image")
            { 
                sb.AppendFormat(format, "image", UriExtensions.Parse(image).AbsoluteUri);
            }

            if(listAttributes !=null)
            {
                 sb.Append(GetHtmlAttributes(listAttributes));
            } 

            return MvcHtmlString.Create(sb.ToString());
        }

        //below is several overloads method for your to choose different type of TwitterCard 
        public static MvcHtmlString TwitterSummaryCard(this HtmlHelper html, string title, string description, string image = null)
        {
            return TwitterCard(html, "summary", title, description, image);
        }

        public static MvcHtmlString TwitterSummaryCardWithLargeImage(this HtmlHelper html, string title, string description, string image = null)
        {

            return TwitterCard(html, "summary_large_image", title, description, image);
        }


        //listAttributes sample:
        //    new{
        //         iphoneName ="iphoneName",
        //         iphoneId="iphoneId",
        //         iphoneUrl="iphoneUrl",
        //         ipadName = "ipadName",
        //             ipadId="ipadId",
        //         ipadUrl="ipadUrl",
        //         googleplayName="googleplayName",
        //         googleplayId="googleplayId",
        //         googleplayUrl="googleplayUrl"
        //      }
        public static MvcHtmlString TwitterAppCard(this HtmlHelper html,string title,string description,object listAttribute)
        {
            return TwitterCard(html, "app", title, description, null, listAttribute);
        }

        
      //below two member is to render anonymous type of object to string
        private static string GetHtmlAttributes(object listAttributes)
        {
           
             var format = @"<meta name=""twitter:app:{0}:{1}"" content=""{2}"" />";
            var sb = new StringBuilder();

            if (listAttributes != null)
            {
                var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(listAttributes);
                foreach (var item in attributes)
                {
                   
                    if (item.Key == "iphoneName") sb.AppendFormat(format, "name", "iphone", item.Value);
                    if (item.Key == "iphoneId") sb.AppendFormat(format, "id", "iphone", item.Value);
                    if (item.Key == "iphoneUrl") sb.AppendFormat(format, "url", "iphone", item.Value);

                    if (item.Key == "ipadName") sb.AppendFormat(format, "name", "ipad", item.Value);
                    if (item.Key == "ipadId") sb.AppendFormat(format, "id", "ipad", item.Value);
                    if (item.Key == "ipadUrl") sb.AppendFormat(format, "url", "ipad", item.Value);

                    if (item.Key == "googleplayName") sb.AppendFormat(format, "name", "googleplay", item.Value);
                    if (item.Key == "googleplayId") sb.AppendFormat(format, "id", "googleplay", item.Value);
                    if (item.Key == "googleplayUrl") sb.AppendFormat(format, "url", "googleplay", item.Value);
                    
                }

            }

            return sb.ToString();
        }

Custom ActionFilterAttribute to pass data to the viewbag before the action executed

Currently projects the SEO setting has been manually hard code it to the view. But since the SEO setting will be frequently change, so my task is to move those hard code text to database, and for render it out to the page. I just created a ViewBag to pass those information to the view.

Asp.net mvc ActionFilterAttribute allow your to pre-process logic to the method before or after the method just executed.

How to do it, just create a class inherit from: ActionFilterAttribute, and inside this class you could see there are 4 members allow you to override it.

        public virtual void OnActionExecuted(ActionExecutedContext filterContext);      
        public virtual void OnActionExecuting(ActionExecutingContext filterContext);        
        public virtual void OnResultExecuted(ResultExecutedContext filterContext);        
        public virtual void OnResultExecuting(ResultExecutingContext filterContext);

For my task, I just overide the OnActionExecuting method.
here is my solution:
step1, create a class named: SeoSettingAttribute.cs
step2,

   public class SeoSettingAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            string action = filterContext.ActionDescriptor.ActionName;
            filterContext.Controller.ViewBag.SeoSettings = GetSeoSettings(action);
        }

        private SeoSettingViewModel GetSeoSettings(string actionStr)
        {
            SeoSettingViewModel seoModel = new SeoSettingViewModel();
            var AdminService = NinjectWebCommon.CurrentKernel.Get();
            seoModel = AdminService.GetCurrentSeoSetting(actionStr);
            NinjectWebCommon.CurrentKernel.Release(AdminService);

            return seoModel;
        }
    }

step3:

decorate it to your the method inside your controller that you like use it.

      [SeoSettingFilter]
        public ActionResult Index(){....}

Using two Way Adding “active” tag to your navigation list in an asp.net mvc Layout page

Recently my task need convert this website http://www.royalecoach.com.au/royale.asp (this is wrote by using classic asp) into asp.net MVC.

First I need to create a layout.cshtml for my the new version of this website.Then navigation need add a class named active to it when the action method has been called.

The first way is very simpley, you could wirte a logic to your view, here is one solution:

addClassNametoLi

But the rule of MVC is the view must be simply as possible, I don’t like this nasty and yuck c# code sit in there. So there is a way just by write a CustomHtmlHelpers to improve it.

here is my class file:

htmlHelper

 

Then in your layout page ,your could use it like:

layoutMenu

That’s it. By the way, I am using asp mvc4. Hope that could help some one else.

Have fun:)

Create marquee news in front page and the news is read from the database with expired data,also included management page to insert news

My boss just saw other company website has a marquee new on the front page, so she asked me if I could make one and arrow her to insert news and the news will dispear at the expired data.

For achieve that task, first I create a table in my database table, here is my table:

breadNewTable

then I write a store proceedure, a little tip for fresh guy, alway use store preceedure to insert data for security reasons.

breadNewStoreProceedure

Now, We could start the front end job. I create a user control:marquee.ascx(so you could put it in anyway you like), to display the new, here is my html code:

frontUCmarquee

here is the backcod, I used ado.net to open the database and qurery what I need, and bind it to my BulledtedList:

databasereadertomarquee

See the code this if(!IsPostBack) is not neccessary, but I use web froms so it wil inherit maintain state so I don’t need retrieve database everytime postback.

here I am also happy to share the css file for style this unorder list to display inline:

MarqueeCssStyle

A tip for fresh guy, put this in the page your use control will stand it.

Now, you just need drag the usercontrol to any page you want it with this css style in top of the header it. You coud see it.

Then We could start create a page to arrow my boss to insert the bread news, I used boostrap format so it save my time to write css. here is the front page look like:

addNews

here is the html code:

htmlCodeAddnews

The form use jQury Validate, the jquery-ui.js, is for my boss click then will pop up the jQuery calender to arrow her to put the expired date. So simple isn’t, I am love JQure very much, save a lot of time. It remind me when I first time write javascript over 10 years ago, for every simply function I need write a lot codes.

Finally I just need write a event could be fired by this button.

storeIntodatabase

Ok, That’s all. Have fun!

Using c# code to force bootstrap modal stay open after page postback

Recently I write a small function into my asp.net application.To enable the driver to input the time the submit the pick up client and drop off the client time.
My boss like the pick up time and drop off time should been populate by just click.so I write a code on the back of page to retrive the time every time the driver click the button.
But the dropoff button driver me to nuts,Because When the dropoff button click I pop out the bootstrap modal.But the problems came out this button need make page postback to retrive the current time and after postback my modal need stay open.
It take me a while to fix out this.
Here is my solution.
first, I need write javascript like this is for to open the modal: #dropoffModal is my hidden modal.

 function openModal() {
$('#dropoffModal').modal({ show: true });
}
 

Second I have the the button is like this(See the button click will fire a event named:”Button_DropOff_Click” behind it):

 button_click_event_fire_javascript

Finally, just write your event on the page behind file:


protected void Button_DropOff_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
}

here just a solution. by the way, You could use ScriptManager.RegisterStartupScript() this command call another function in your frond page javascript.

Cookies in ASP.NET

Cookies is a small piece of information stored on the client machine. This file is located on client machines “C:\Document and Settings\Currently_Login user\Cookie” path.  Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called  Systen.Web.HttpCookie before we use cookie.
 
Type of Cookies?

  1. Persist Cookie – A cookie has not have expired time Which is called as Persist Cookie

  2. Non-Persist Cookie – A cookie has expired time Which is called as Non-Persist Cookie

How to create a cookie?
 
Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie
 
Example 1:
 
        HttpCookie userInfo = new HttpCookie(“userInfo”);
        userInfo[“UserName”] = “Annathurai”;
        userInfo[“UserColor”] = “Black”;
        userInfo.Expires.Add(new TimeSpan(0, 1, 0));
        Response.Cookies.Add(userInfo);

Example 2:
 
        Response.Cookies[“userName”].Value = “Annathurai”;
        Response.Cookies[“userColor”].Value = “Black”;
                       
How to retrieve from cookie?

Its easy way to retrieve cookie value form cookes by help of Request object.
 
Example 1:
 
        string User_Name = string.Empty;
        string User_Color = string.Empty;
        User_Name = Request.Cookies[“userName”].Value;
        User_Color = Request.Cookies[“userColor”].Value;

Example 2:
 
        string User_name = string.Empty;
        string User_color = string.Empty;
        HttpCookie reqCookies = Request.Cookies[“userInfo”];
        if (reqCookies != null)
        {
            User_name = reqCookies[“UserName”].ToString();
            User_color = reqCookies[“UserColor”].ToString();
        }
 
When we make request from client to web server, the web server process the request and give the lot of information with big pockets  which will have Header information, Metadata, cookies etc., Then repose object can do all the things with browser.

Cookie’s common property:

  1. Domain => Which is used to associate cookies to domain.

  2. Secure  => We can enable secure cookie to set true(HTTPs).

  3. Value    => We can manipulate individual cookie.

  4. Values  => We can manipulate cookies with key/value pair.

  5. Expires => Which is used to set expire date for the cookies.

Advantages of Cookie:

  1. Its clear text so user can able to read it.

  2. We can store user preference information on the client machine.

  3. Its easy way to maintain.

  4. Fast accessing.

Disadvantages of Cookie

  1. If user clear cookie information we can’t get it back.

  2. No security.

  3. Each request will have cookie information with page.

How to clear the cookie information?

 

  • we can clear cookie information from client machine on cookie folder

 

  1. To set expires to cookie object
    userInfo.Expires = DateTime.Now.AddHours(1);
    It will clear the cookie with one hour duration.

 

This article  is copy from http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ some article is very useful, I past it here, so I could use it  when I need it.

How to use the procedure I write it in last post in your asp.net web application

In my last post I just create a store procedure to insert data into 2 tables, here is the c# code how do you use it in your project.

I write a event so for anyone need it just change you connection string then will be reuse.


protected void ButtonClick_StoreRecords(string parameterRef, string parameterLM_Booking_Ref,  string parameterLMStatus, DateTime parameterEntry_datetime)
    {
        string CS = ConfigurationManager.ConnectionStrings["youconnectionstringhere"].ConnectionString;
        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlCommand cmd = new SqlCommand("spStoreLMStatusRecording", con);
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter paramRef = new SqlParameter();
            paramRef.ParameterName = "@parameterRef";
            paramRef.Value = parameterRef;
            cmd.Parameters.Add(paramRef);

            SqlParameter paramLM_Booking_Ref = new SqlParameter();
            paramLM_Booking_Ref.ParameterName = "@parameterLM_Booking_Ref";
            paramLM_Booking_Ref.Value = parameterLM_Booking_Ref;
            cmd.Parameters.Add(paramLM_Booking_Ref);
         

            SqlParameter paramLMStatus = new SqlParameter();
            paramLMStatus.ParameterName = "@parameterLMStatus";
            paramLMStatus.Value = parameterLMStatus;
            cmd.Parameters.Add(paramLMStatus);


            SqlParameter paramEntry_datetime = new SqlParameter();
            paramEntry_datetime.ParameterName = "@parameterEntry_datetime";
            paramEntry_datetime.Value = parameterEntry_datetime;
            cmd.Parameters.Add(paramEntry_datetime);

            con.Open();
            cmd.ExecuteNonQuery();

        }
     
    }