Thursday, November 28, 2013

How to solve problem: Visual Studio cannot recognize name space even already added related project as reference?

Check two projects’ target framework are same.
My case: one target framework is .Net 4.0, another is .Net 4.5

CSS box model and element vertical align issue

http://krugerdavid.com/journal/understanding-blueprintcss/
Many vertical align issues are related to margine and padding value, so understand css box model will be helpful.

Wednesday, November 27, 2013

How to solve "This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "

When deploy a website on IIS Server first time, get following 500 internal server error:
This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

The first thing to do is to run
turn on/off Windows features:

So can check if related features are enabled on the server




Tuesday, November 26, 2013

How to enable html source button on tinyMCE?

Add "code" into plugins list, then add "code" into button array
        tinyMCE.init({
            // General options
            mode: "textareas",
            plugins: "spellchecker,code",
            theme : "advanced",
            theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink,code",
            theme_advanced_buttons2 : "code",
        });

Weinre with Browserstack

http://arafat.azurewebsites.net/2013/11/16/weinre-on-azure-in-combination-with-browserstack/

Wednesday, November 20, 2013

How to implement minimum string length validation by Data annotation in ASP.NET MVC?

Two ways:
Fisrt:
        [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 10)]
 
Second:
Regular expression
[RegularExpression(@"^.{10,}$", ErrorMessage = "Minimum 10 characters required")]

Tuesday, November 19, 2013

How to set base URL in ASP.NET MVC for JavaScript?

In _Layout.cshtml, Add base tag in head, and pass base URL.

<head>
    <base href='@string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))'/>
</head>

Monday, November 18, 2013

How to fix problem: To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider"?

Because you are using SimpleMembership provider.
Either remove any other membership provider setting in web.config
Or
you add following setting in web.config file


    
      
        
        
      
    
    
      
        
        
      
    
  

Reference:
http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx

How to change password format in SimpleMembership?

No. Can't change password format like: SqlMembershipProvider.PasswordFormat

Thursday, November 14, 2013

How to use bundle for Javascript and css in ASP.NET MVC?

1. Define bundle:
    public class BundleConfig
    {
        // For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
 }
     }
2. Register Bundle:
In Global.asax
        protected void Application_Start()
        {
            BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
3. Refer bundle
In Razor view
    @Scripts.Render("~/bundles/jquery")

"display: inline-block" (Items does not display horizontally) not working in IE

Change to:
display: inline;
Reference:
http://stackoverflow.com/questions/5838454/inline-block-doesnt-work-in-internet-explorer-7-6

How to implement multiple [Order by] in LINQ?

Var list = _db.Lists.Orderby(c => c.filed1).ThenBy(n => n.field2)

Wednesday, November 13, 2013

Prevent Duplicate Form Submission

http://shaiekh.com/home/prevent-duplicate-form-submission/

- Disable submit button
- PRG (Post/Redirect/Get)
- Unique token in the session

Tuesday, November 12, 2013

How to store resource into database or xml in ASP.NET MVC ?

http://afana.me/post/aspnet-mvc-internationalization-store-strings-in-database-or-xml.aspx

How to render a ASP.NET MVC view into html string?

        public string RenderRazorViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }
Reference:
http://stackoverflow.com/questions/483091/render-a-view-as-a-string

Monday, November 11, 2013

DataAnnotations regular expression for email address in ASP.NET MVC

[
RegularExpression(@"^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$", ErrorMessage = "Invalid Email Address")]

Thursday, November 7, 2013

How to remove nodes in HTMLAgilityPack? Such as remove all of invisible div?

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            var Divs = doc.DocumentNode.SelectNodes("//div[(contains(@style,'display:none'))]");
            if (noneDivs != null)
            {
                foreach (var one in noneDivs.ToList())
                {
                    one.Remove();
                }
            }

Wednesday, November 6, 2013

How to fix "Cannot insert duplicate key in object . The duplicate key value is" problem while insert a new record in SQL Server?

First all, Run:
dbcc checkident([tablename],noreseed)
to check the latest id

Then run
DBCC CHECKIDENT ([tablename], reseed, latest id)
to correct latest id

How to solve Google OVER_QUERY_LIMIT problem?

Google usage limit:
The Google Geocoding API has the following limits in place:

2,500 requests per day.
Google Maps API for Business customers have higher limits:
100,000 requests per day.
https://developers.google.com/maps/documentation/geocoding/#Limits

Two choices:
1. Buy a business acccount
2. Use Proxy to change your ip address

Tuesday, November 5, 2013

How to get latitude and longitude from address by Google geocode api in C#?

Reference:
http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object

var json = new WebClient().DownloadString(
string.Format("http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false"
, "1600+Amphitheatre+Parkway,+Mountain+View,+CA"));
            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
            dynamic obj = serializer.Deserialize(json, typeof(object));
            if (obj.status == "OK")
            {
                var lat = obj.results[0].geometry.location.lat;
                var lng = obj.results[0].geometry.location.lng;
            }
public sealed class DynamicJsonConverter : JavaScriptConverter
{
    public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

        return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
    }

    public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override IEnumerable SupportedTypes
    {
        get { return new ReadOnlyCollection(new List(new[] { typeof(object) })); }
    }

    #region Nested type: DynamicJsonObject

    private sealed class DynamicJsonObject : DynamicObject
    {
        private readonly IDictionary _dictionary;

        public DynamicJsonObject(IDictionary dictionary)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");
            _dictionary = dictionary;
        }

        public override string ToString()
        {
            var sb = new StringBuilder("{");
            ToString(sb);
            return sb.ToString();
        }

        private void ToString(StringBuilder sb)
        {
            var firstInDictionary = true;
            foreach (var pair in _dictionary)
            {
                if (!firstInDictionary)
                    sb.Append(",");
                firstInDictionary = false;
                var value = pair.Value;
                var name = pair.Key;
                if (value is string)
                {
                    sb.AppendFormat("{0}:\"{1}\"", name, value);
                }
                else if (value is IDictionary)
                {
                    new DynamicJsonObject((IDictionary)value).ToString(sb);
                }
                else if (value is ArrayList)
                {
                    sb.Append(name + ":[");
                    var firstInArray = true;
                    foreach (var arrayValue in (ArrayList)value)
                    {
                        if (!firstInArray)
                            sb.Append(",");
                        firstInArray = false;
                        if (arrayValue is IDictionary)
                            new DynamicJsonObject((IDictionary)arrayValue).ToString(sb);
                        else if (arrayValue is string)
                            sb.AppendFormat("\"{0}\"", arrayValue);
                        else
                            sb.AppendFormat("{0}", arrayValue);

                    }
                    sb.Append("]");
                }
                else
                {
                    sb.AppendFormat("{0}:{1}", name, value);
                }
            }
            sb.Append("}");
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (!_dictionary.TryGetValue(binder.Name, out result))
            {
                // return null to avoid exception.  caller can check for null this way...
                result = null;
                return true;
            }

            result = WrapResultObject(result);
            return true;
        }

        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            if (indexes.Length == 1 && indexes[0] != null)
            {
                if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
                {
                    // return null to avoid exception.  caller can check for null this way...
                    result = null;
                    return true;
                }

                result = WrapResultObject(result);
                return true;
            }

            return base.TryGetIndex(binder, indexes, out result);
        }

        private static object WrapResultObject(object result)
        {
            var dictionary = result as IDictionary;
            if (dictionary != null)
                return new DynamicJsonObject(dictionary);

            var arrayList = result as ArrayList;
            if (arrayList != null && arrayList.Count > 0)
            {
                return arrayList[0] is System.Collections.Generic.IDictionary? new List(arrayList.Cast>().Select(x => new DynamicJsonObject(x))):new List(arrayList.Cast());             }              return result;         }     }      #endregion }   

How to add reference for JavaScriptSerializer class into project?

Add a reference to System.Web.Extensions
Although JavaScriptSerializer namespace is: System.Web.Script.Serialization