Monday, 18 September 2017

A-Map (china map) with auto complete textbox in web

Controller like: 

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
      [HttpPost]
        public ActionResult Index(string Address, string LatLong)
        {
            ViewBag.Message = "Address: " + Address+ " Lat Long: " + LatLong;
            return View();
        }
 }

CShtml page :

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>

   
    <script>
        $(function () {
            $("#Address").autocomplete({
                source: function (request, response) {
                    var Address = [];
                    $.ajax({
                        url: 'http://restapi.amap.com/v3/place/text',
                        data: { key: "Your API key", keywords: request.term },
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            var results = jQuery.parseJSON(JSON.stringify(data));
                            var i;
                            var items = results.pois;
                             //declare a new object.
                        for (i = 0; i < items.length; i++) {
                                var objectInResponse = items[i];
                                var listobj = { label: objectInResponse.address + "," + objectInResponse.cityname, val: objectInResponse.location }
                              
                            
                                Address.push(listobj)
                            }
                            ///alert(JSON.stringify(Address));
                            response($.map(Address, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("#LatLong").val(i.item.val);
                },
                minLength: 1
            });
        });
    </script>


    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <input type="text" id="Address" name="Address" />
        <input type="hidden" id="LatLong" name="LatLong" />
        <br /><br />
        <input type="submit" id="btnSubmit" value="Submit" />
        <br /><br />
        @ViewBag.Message
    }
  
</body>
</html>

Passing Antiforgery token in Ajax

Controller have function like

[HttpPost]
[ValidateAntiForgeryToken]
 public JsonResult ActionName(int Id)
{
    //do your stuff
}

Cshtml Page 

@Html.AntiForgeryToken()
<!--Include ajax script render section for ajax call--> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

<script>
 $.ajax({
                    url: '../Controllername/ActionName',
                    type: "Post",
                   data: {
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
Id: 1},
                    success: function (response) {
                      //do your stuff
                    },
                    error: function (errorcode, textStatus, errorThrown) {
                        // alert("Error '" + errorcode.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                    },
                    complete: function () {
                        // do your stuff after complete                    }
                });
</script>

Saturday, 16 September 2017

Distance calculation function between lat and long in c#

 public class DistanceCalculationHelper
    {
        public static double GetDistance(decimal lat1, decimal long1, decimal lat2, decimal lon2,char unit='K')
        {
            try
            {
                //const double PI = 3.1415926535897931;
                //double rlat1 = Math.PI * double.Parse(lat1.ToString()) / 180;
                //double rlat2 = Math.PI * double.Parse(lat2.ToString()) / 180;
                //double theta = double.Parse(long1.ToString()) - double.Parse(lon2.ToString());
                //double rtheta = Math.PI * theta / 180;
                //double dist =
                //    Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) *
                //    Math.Cos(rlat2) * Math.Cos(rtheta);
                //dist = Math.Acos(dist);
                //dist = dist * 180 / Math.PI;
                //dist = dist * 60 * 1.1515;

                //switch (unit)
                //{
                //    case 'K': //Kilometers -> default
                //        return dist * 1.609344;
                //    case 'N': //Nautical Miles
                //        return dist * 0.8684;
                //    case 'M': //Miles
                //        return dist;
                //}

                //return dist;

                var sCoord = new GeoCoordinate(double.Parse(lat1.ToString()), double.Parse(long1.ToString()));
                var eCoord = new GeoCoordinate(double.Parse(lat2.ToString()), double.Parse(lon2.ToString()));
                return Math.Round((sCoord.GetDistanceTo(eCoord) / 1000), 2);
                        }
            catch
            {
                return 0;
            }
        }
    }

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"));