Monday, March 31, 2014

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

Step 1: Add DotnetOpenAuth lib from http://www.dotnetopenauth.net/ 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();
        [ValidateInput(false)]
        public ActionResult LoginByGoogle(string returnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                string openidUrl = "https://www.google.com/accounts/o8/id";
                Identifier id;
                if (Identifier.TryParse(openidUrl, out id))
                {
                    try
                    {
                        var req = openid.CreateRequest(openidUrl);
                        var fetch = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                        req.AddExtension(fetch);
                        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?

http://www.wekeroad.com/2014/02/18/i-had-a-choice-php-or-net/

Tuesday, March 25, 2014

How to add log4net into ASP.NET project?

1. Download dll file from
http://logging.apache.org/log4net/download_log4net.cgi
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.

http://blogs.iis.net/webdevelopertips/archive/2009/10/02/tip-98-did-you-know-the-default-application-pool-identity-in-iis-7
-5-windows-7-changed-from-networkservice-to-apppoolidentity.aspx

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

References:
Apache log4net™ Manual - Configuration
http://logging.apache.org/log4net/release/manual/configuration.html
http://ruchirac.blogspot.ca/2012/10/configure-log4net-with-aspnet-logging.html

Monday, March 24, 2014

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

string rootpath = HttpContext.Current.Request.ApplicationPath;
Or
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:

    
        
            
                
                    
                
            
            
                
                    
                
            
            
                
                    
                
            
            
                
                    
                
            
            
                
                    
                
            
        

        
            
        
    


http://msdn.microsoft.com/en-us/library/ms733025.aspx



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
https://github.com/ericmbarnard/Knockout-Validation

    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?

http://knockoutjs.com/documentation/binding-context.html
$parent
$parents
$root
$data
$index (only available within foreach bindings)
$parentContext
$context
$element

How to bind array of string in Knockout?

$data
Example
                    

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
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [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