Truth in Javascript and simple example using in angularjs

Javascript is loose language and understand the truth is very help you to write javascript code. Here it is:

var num = 0;
var myObj1 = undefine;
var myObj2 = null;
var myObj3 = {};
var myStr = "";
if(num) // false
if(myObj1) // false
if(myObj2) //false
if(myStr) //false
if(myObj3) // true

Very simple and common used in angularjs


<div ng-show="myObj3"></div> // will show

<div ng-show="myStr" class="ng-hide"></div> // will hide

The architecture of real live AngularJS — Get start with angularJs — Part 2

A good project should has a good architecture, and in angularjs is very easy to modular your projects. And also your project will be easy to extend it.

For example like this:

(function () {
    "use strict";
   
   // app.js
    var app = angular.module("productManagement",
                            ["services",
                             "productResource"]);
}());

//this is services.js
(function () {
    "use strict";
    angular
        .module("services",
                ["$http"])
}());
 

//this is my productResource.js
(function () {
    "use strict";
    angular
        .module("services")
        .factory("productResource",
                ["$http",
                 productResource]);

    function productResource($http) {
        //url could be external or internal
        return $http("/api/products/:productId")
    }
}());

So every javascript file just has few lines. And it separate the angular project to three modules, the main moudule is the “productManagement” and it has two dependants are “services” and “productResource”.

I came from C# background, so I like write code also follow the rule  single responsibility and dependency inversion.

It is much easy to read and extensible.

The common javascript partterns used in AngualrJS — Get start with AnuglarJS — part1

Before you study to use angualr.js, there are two important javascript patterns using in angular.js, if you are already javascript then probably already get use to those patterns.

(function(){}()) called : IIFE:immediately-invoked function expression

The first one is using functions as abstractions that is very common the angular.js. Example like below:

(function() {
  // turn it to javascript Strict mode //Strict mode changes previously accepted "bad syntax" into real errors.
"use strict";
var myFunction = function(){
  console.log("my function working here");
}
var starMyFuntion = function(functionPassHere){
   console.log("start now");
   try{
     functionPassHere();//invoke the function
   }
   catch(ex)
   {
      console.log(ex);
   } 
   console.log("end here");
}
starMyFuntion(myFunction);

}());

The second one is using functions as ModelExample like below:

(function() {
  "use strict";
  var myfirstModel = function() {
    var person = fuction() {
      //code goes here 
      //return a person object
    }
    var task = function() {
      //code goes here 
      //return all the tasks
    }
    return {
      person: person,
      task: task
    }
  }

  var instance = new myfirstModel();
  instance.person();
  instance.task();

}());

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();
        }

Customize a validation attribute working both client side and server side in asp.net MVC

In asp.net MVC the model is using for holding the data and for validation. There are a lot build in validation for you to use, how? just simply by put “using System.ComponentModel.DataAnnotations;” on top of the your model file then you could like this

using System.ComponentModel.DataAnnotations;

namespace youprojectName.Model
{
    public class Account
    {

       [StringLength(26)]//this is the validate
        public string BusinessName { get; set; }

        ...
       }
}

Those build in validation is very useful and they are both client side and server side validation.

But in real projects we need more validation to suit for our business logic. So in that scenario there is a way if your boss happen just the validation is server side,then simply let your model inherit from :IValidatableObject

then you could override the IEnumerable Validate(ValidationContext validationContext) Member.

Sample like this

       
        //those validation only for server side
        public IEnumerable Validate(ValidationContext validationContext)
        {
            if (Name.ToLower().StartsWith("xxxx"))
            {
                yield return new ValidationResult("Sorry, xxxx, you do not have permisstion to do this");
            }
             .....
        }

But this is not the way supports to write your validation, in MVC validation is a attribute just put on top of your class property.
So how to achieve that?
We could create a custom remote attribute and override IsValid() method.

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

namespace CustomizeValidation.Validation
{
    public class RemoteClientServerAttribute : RemoteAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            // Get the controller using reflection
            Type controller = Assembly.GetExecutingAssembly().GetTypes()
                .FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller",
                    this.RouteData["controller"].ToString()).ToLower());
            if (controller != null)
            {
                // Get the action method that has validation logic
                MethodInfo action = controller.GetMethods()
                    .FirstOrDefault(method => method.Name.ToLower() ==
                        this.RouteData["action"].ToString().ToLower());
                if (action != null)
                {
                    // Create an instance of the controller class
                    object instance = Activator.CreateInstance(controller);
                    // Invoke the action method that has validation logic
                    object response = action.Invoke(instance, new object[] { value });
                    if (response is JsonResult)
                    {
                        object jsonData = ((JsonResult)response).Data;
                        if (jsonData is bool)
                        {
                            return (bool)jsonData ? ValidationResult.Success :
                                new ValidationResult(this.ErrorMessage);
                        }
                    }
                }
            }

           
            return new ValidationResult(base.ErrorMessageString);
        }
        //below is several over load for your to use   
        public RemoteClientServerAttribute(string routeName)
            : base(routeName)
        {
        }

        public RemoteClientServerAttribute(string action, string controller)
            : base(action, controller)
        {
        }

        public RemoteClientServerAttribute(string action, string controller,
            string areaName)
            : base(action, controller, areaName)
        {
        }
    }
}

then you could simply use it like this:

public class Customer
    {
       ....
        [StringLength(100)]
        [RemoteClientServer("IsValid", "Account",
        ErrorMessage="Email already in use")] 
//"IsValid" is the method should return Json data at your "Account" controller
        public string Email { get; set; }
       ...
   }

Here is one of solution for write customize both server side and client side validation,but I have another solution also could working in client and server side validation(for those solution is write your server side validation in the model first, then write some more jQuery to the View), this will another post, when I back from my job.

Have Fun!

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(){....}

Overlay screen with transparency achieve by using position: relative and absolute

New trick learned by doing build this layout, have transparent under my two foundation columns. The looking is like this:

transparent wrap under two columns

The div layout is like this:

<div class=”clearfix blueWrap”>
<div class =”orangeWrap”></div>
<!– below two columns is the purple wrap in the picture –>
<div class=”medium-6 columns”></div>
<div class=”medium-6 columns”></div>
</div>

 just few line of css:
  .blueWrap{position:relative;}
  .orangeWrap{
        background-color: rgba(68, 68, 68, 0.47);
	position:absolute;
	top:0;
	left:0;
	width:100%;
	height:100%;
       }
 

then just use the foundation media query to make sure when it was in the big screen don’t display that transparent overlay screeen.

@media only screen and (min-width: 64.063em) {
.orangeWrap {
width:70%;
}

How make your background image full size of the screen and cross mobile,table and desktop in Foundation

Recently a task is using the existing foundation basic page to rewrite it to a new design. It is my first time working in Foundation Framework, previous I always using bootstrap.

And from doing this get understand how foundation works. Wow, take a day to achieve it.

And for make the background image full size of the screen and cross the mobile,table and desktop that took me few hours to fix it.

I just like to put my piece of code over there, hope that could help my fans.

.main-background{    
	background:#f38f04 url('/images/bg-img.png') no-repeat center center fixed; 
        background-size: cover;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
	width: 100% !important;
	z-index: 0;
}

the fixed and width:100% !important that is very important to make it happens.

Best Web Design, web developer, php developer,designers,freelance

Follow

Get every new post delivered to your Inbox.

Join 116 other followers