Wednesday, 6 September 2017

Reset password using entity framework

In this case you will be treating ChangePassword as Reset Password. You can achieve this by using reset password by generating token and using that token straightaway to validate it with new password.



var userId = User.Identity.GetUserId();

var token = await UserManager.GeneratePasswordResetTokenAsync(userId);

var result = await UserManager.ResetPasswordAsync(userId, token, newPassword);

Thursday, 24 August 2017

Email or Phone number for Form Auth register


//Create custom RegularExpressionAttribute

public class EmailOrPhoneAttribute : RegularExpressionAttribute
    {
        public EmailOrPhoneAttribute()
            : base(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$|^\d{10}$")
        {
            ErrorMessage = "Please provide a valid email address or phone number";
        }
    }


//Model
 public class LoginViewModel
    {
        [Required]
        [Display(Name = "Email")]
        // [EmailAddress]
        [EmailOrPhone]
        public string Email { get; set; }

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

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }
//Set Email required as false in identity config

 public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = false,
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }



Set Data type for Entity field

Question:
[StringLength(128)]    
public string FirstName { get; set; }
Also i have disable unicode for all string properties this way:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Properties<string>().Configure(p => p.IsUnicode(false));            
}
The problem is that all string properties decorated with the mentioned attribute are ignoring this setting when generating the database schema, producing nvarchar datatype for the corresponding database columns. What is the correct way to disable unicode in this cases?


 Answer:
Seems to be a bug (or omission) in the new PropertyConventionConfiguration API. The following configuration does work, so it can serve as a work-around:



modelBuilder.Properties<string>().Configure(x => x.HasColumnType("VARCHAR"));


Thursday, 27 July 2017

Custom filter in Web API

Based on device id check request from valid device or not

Authorize Custom filter:

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (SkipAuthorization(actionContext))
            {
                return;
            }
            if (!IsUserAuthorized(actionContext))
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    StatusCode = System.Net.HttpStatusCode.Unauthorized
                };
            }
            //base.OnAuthorization(actionContext);
        }
        private static bool SkipAuthorization(HttpActionContext actionContext)
        {
            Contract.Assert(actionContext != null);

            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
                   || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
        }
        public bool IsUserAuthorized(HttpActionContext context)
        {
            using (Entities db = new Entities())
            {
                IEnumerable<string> deviceId;
                context.Request.Headers.TryGetValues("deviceId", out deviceId);
                if (deviceId == null)
                {
                    return false;
                }
                bool result = db.Users.Any(r => r.DeviceId == deviceId.FirstOrDefault() && r.Email == HttpContext.Current.User.Identity.Name);
                return result;
            }
        }
    }
------------------------------------------------------------------------------------------------------------------------
In ontroller
[CustomAuthorize]
    [RoutePrefix("api/document")]
    public class DocumentController : ApiController
    {
    }


Validate MIME Filter:

public class ValidateMimeFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
        }

    }
---------------------------------------------------------------------------------------------------------------------
In your controller
 [ValidateMimeFilter]
 [HttpPost]
        [Route("upload")]
        [SwaggerResponse(HttpStatusCode.OK, Type = typeof(ApiResponseModel))]
        [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(ModelState))]
        [SwaggerResponse(HttpStatusCode.InternalServerError, Type = typeof(Exception))]

        public async Task<IHttpActionResult> UploadDocuments()
        {
         }

Form authentication using cookies C# MVC .Net

Steps:

1.Solution explorer -> App start ->Startup.Auth.cs

after open this file:


// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Authentication/Login")
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/login"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }



--------------------------------------Authentication controller----------------------------------------------------
 public class AuthenticationController : Controller
    {
        public AuthenticationController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {
        }

        public AuthenticationController(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }
        public UserManager<ApplicationUser> UserManager { get; private set; }
        private Entities db = new Entities();
        // GET: Authentication
        public ActionResult Login()
        {
            return View();
        }

        // GET: Authentication/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Authentication/Create
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, ActionName("Login")]
        public async Task<ActionResult> LoginPost(LoginModel model)
        {
            if(!ModelState.IsValid)
            {
                return View(model);
            }
            try {
            var user = await UserManager.FindAsync(model.UserName, model.Password);
            if ((user != null) && (UserManager.IsInRole(user.Id, Enum.GetName(typeof(Enums.Role), 1))))
            {
                 
                    await SignInAsync(user,true);
                 
                    return RedirectToAction("Index", "Home");
            }
            else if ((user != null))
            {
                //ViewBag.ErrorMessage = ErrorMessage.AccessDenied; //ErrorMessage.AccessDenied;
                ModelState.AddModelError("Authentication", ErrorMessage.AccessDenied);
            }
            else
            {
                ModelState.AddModelError("Authentication", ErrorMessage.InvalidCredentials);
                //ViewBag.ErrorMessage = ErrorMessage.InvalidCredentials; //"Incorrect password";
            }
            return View(model);
            }
            catch (Exception ex)
            {
                ErrorLog.HandleException(ex);
                return RedirectToAction("Index", "Error");
            }

        }

        public ActionResult Logout()
        {
            try
            {
                AuthenticationManager.SignOut();
                HttpCookieCollection cookieCollection = Request.Cookies;
             
             
            }
            catch(Exception ex)
            {
                ErrorLog.HandleException(ex);
            }
            return RedirectToAction("Login", "Authentication");
        }

        [HttpGet]
        public ActionResult ResetPassword(string userId, string code)
        {
            ResetPasswordModel model = new ResetPasswordModel();
            model.UserId = userId;
            model.Code = code;
            if( string.IsNullOrWhiteSpace(userId) && string.IsNullOrWhiteSpace(code) )
            {
                //ModelState.AddModelError(ErrorMessage.ErrorCode, ErrorMessage.InvalidUser);
                return RedirectToAction("PageNotFound", "Error");
            }
            var user = UserManager.FindById(userId);
            if (user == null)
            {
                return RedirectToAction("PageNotFound", "Error");
            }
            var codeReplace = code.Replace(" ", "+");
            if (! db.Users.Any(x => x.Email ==user.Email  && x.ResetToken== codeReplace))
            {
                ViewBag.ErrorMessage = ErrorMessage.AlreadyPasswordReset;
                return View(model);
            }
            return View(model);
        }

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }
        private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
           AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            //// Add more custom claims here if you want. Eg HomeTown can be a claim for the User
            ////var homeclaim = new Claim(ClaimTypes.Country, user.HomeTown);
            ////identity.AddClaim(homeclaim);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }
        // POST: Authentication/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Authentication/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Authentication/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Authentication/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Authentication/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
------------------------------Helper class for getting current user details   --------------

 public static class AuthenticationHelper
    {
        public static async Task<LoggedinUser> GetLoggedinUserDetails(HttpContext context)
        {
            try
            {
var db=new YourDbEntity()
 var userrights = await db.tbl_userrights.FirstOrDefaultAsync(x => x.Userid == HttpContext.Current.User.Identity.Name && x.Delmark == null);
                var user = new LoggedinUser();
                if (userrights != null)
                {
                    user.Userid = userrights.Userid;
                    user.AddConfig = userrights.AddConfig;
                    user.DeleteConfig = userrights.DeleteConfig;
                    user.EditConfig = userrights.EditConfig;
                    user.Email = userrights.Email;
                    user.Category = userrights.Category;
                    user.MenuConfig = userrights.MenuConfig;
                    user.Name = userrights.Name;
                }
                string loggedUser = JsonConvert.SerializeObject(user);
                context.Response.Cookies["CurrentUser"].Value = loggedUser;
                return user;
            }
            catch
            {
                throw;
            }
        }

---------------------------------------------------------home controller----------------------------------------------



// [Authorize(Roles = GlobalVariable.ADMIN)]
[Authorize]
    public class HomeController : Controller
    {
 var user = AuthenticationHelper.GetLoggedinUserDetails(HttpContext.Current).GetAwaiter().GetResult();

}

Wednesday, 21 June 2017

Google map convert as a image or byte in C#

C# - Class file:

public class GoogleMapHelper
    {
        public static byte[] GetGoogleMapLocationAsByte(double lattitude,double longititude)
        {
         
            byte[] mapa;
            try
            {
           
         
                string url = @"http://maps.googleapis.com/maps/api/staticmap?center=" + lattitude + "," + longititude +
                    "&zoom=15&size=504x400&maptype=roadmap&markers=color:red%7Clabel:%7C" + lattitude + "," + longititude + "&sensor=false";

                using (WebClient wc = new WebClient())
                {
                   return mapa = wc.DownloadData(url);
                }
            }
            catch
            {
                return  new byte[]{};
            }
        }
    }


Cshtml

@{
    var base64 = Convert.ToBase64String(
GoogleMapHelper.GetGoogleMapLocationAsByte(11.0420371356699,77.0446100099899) );
    var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
}


<img src="@imgSrc" />