Monday, March 31, 2014

The simple way to add Google login (OpenID) into ASP.NET MVC project

Step 1: Add DotnetOpenAuth lib from into ASP.NET MVC project reference
Step 2: Add following section into web.config file:


Step 3: Add an action for Authentication
protected static OpenIdRelyingParty openid = new OpenIdRelyingParty();
        public ActionResult LoginByGoogle(string returnUrl)
            var response = openid.GetResponse();
            if (response == null)
                string openidUrl = "";
                Identifier id;
                if (Identifier.TryParse(openidUrl, out id))
                        var req = openid.CreateRequest(openidUrl);
                        var fetch = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                        return req.RedirectingResponse.AsActionResult();
                    catch (ProtocolException ex)
                        ViewData["Message"] = ex.Message;
                        return View("LogOn");

                ViewData["Message"] = "Invalid identifier";
                return View("LogOn");
            switch (response.Status)
                case AuthenticationStatus.Authenticated:
                    Session["FriendlyIdentifier"] = response.ClaimedIdentifier;
                    var sreg = response.GetExtension();
                    if (sreg != null)
                        var model = new RegisterModel()
                            Email = sreg.Email,
                        FormsAuthentication.SetAuthCookie(model.Email, true /* createPersistentCookie */);
                        return RedirectToAction("Home", "Index");
                    return View("LogOn");
                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return View("LogOn");
                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    return View("LogOn");

            return new EmptyResult();

Step 4: Add a link to point to this Action
@Html.ActionLink("Log in using Google", "LoginByGoogle")

PHP or ASP.NET: Did I Do The Right Thing?

Tuesday, March 25, 2014

How to add log4net into ASP.NET project?

1. Download dll file from
2.Add following log4net.config file into project


3. In Global.asax
protected void Application_Start()
            string l4net = Server.MapPath("~/log4net.config");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));

4. Add write permission setting for log file folder
IIS manager -> Application pool -> Get name of application pool
File explorer -> folder property -> Security -> Add IIS AppPool\\app pool name into log file folder write/read permission.

5. Usage:
ILog log = LogManager.GetLogger(typeof(this));

Apache log4net™ Manual - Configuration

Monday, March 24, 2014

How to get application root path in ASP.MVC 3 and 3+

string rootpath = HttpContext.Current.Request.ApplicationPath;
string rootpath = Url.Content("~"),

Thursday, March 20, 2014

How to solve problem, Only WS-ReliableMessaging messages are processed by this endpoint

Remove reliableSession binding from WCF server side setting.

Or Add reliableSession binding setting into client side as well.

Wednesday, March 19, 2014

How to enable WCF tracing to debug weird problem?

Got a weird WCF timeout exception
The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue
The read operation failed, see inner exception.

After tried all of settings related to timeout, decided to enable WCF tracing to see what exactly happened on server side.

Found one serialization exception in the log, solved the problem.

Put following setting to enable WCF tracing:



How to format phone number in C#

String.Format("{0:###-###-####}", double.Parse("1234567890"))

How to valid phone by Knockout Validation plugin ?

Add Knockout Validation reference into project from

    self.Telephone = ko.observable("").extend({
        required: true,
        pattern: {
            message: '*Invalid Phone Number. (Format: 999-999-9999)',
            params: /\d{3}-\d{3}-\d{4}/

Wednesday, March 12, 2014

How to cast base class into derived class by JavaScriptSerializer

                BaseClass b = new BaseClass(){};
                System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
                var json = ser.Serialize(b);
                DerivedClass d = ser.Deserialize(json);

How many data binding context variables in Knockout?
$index (only available within foreach bindings)

How to bind array of string in Knockout?


Thursday, March 6, 2014

How to trigger validation on Data annotation attributes in C#?

Name space: System.ComponentModel.DataAnnotations
var validationResults = new List();
            var myObject = new LoginViewModel();
            var validateContext = new ValidationContext(myObject, null, null);
            var isValid =  Validator.TryValidateObject(myObject, validateContext,validationResults);

    public class LoginViewModel
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }

Wednesday, March 5, 2014

How to get validation errors in ASP.NET MVC model?

foreach (ModelState state in ViewData.ModelState.Values) {
    foreach (ModelError error in state.Errors) {
        var ex = error;

Monday, March 3, 2014