click here
Monday 25 December 2017
Tuesday 19 September 2017
QR code generation in C# and CShtml
Libraries Required.
Install these packages into project file or service file using NuGet Package manager.
using System;using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using ZXing;
using ZXing.Common;
//Helper class file for generate QR code
namespace QRHelper
{
public static class QRHelper
{
public static IHtmlString GenerateQrCode(this HtmlHelper html, string Content, string alt = "QR code", int height = 150, int width = 150, int margin = 0)
{
var qrWriter = new BarcodeWriter();
qrWriter.Format = BarcodeFormat.QR_CODE;
qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };
using (var q = qrWriter.Write(Content))
{
using (var ms = new MemoryStream())
{
q.Save(ms, ImageFormat.Png);
var img = new TagBuilder("img");
img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
img.Attributes.Add("alt", alt);
return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
}
}
}
public static IHtmlString GenerateQrCode(string Content, string alt = "QR code", int height = 150, int width = 150, int margin = 0)
{
var qrWriter = new BarcodeWriter();
qrWriter.Format = BarcodeFormat.QR_CODE;
qrWriter.Options = new EncodingOptions() { Height = height, Width = width, Margin = margin };
using (var q = qrWriter.Write(Content))
{
using (var ms = new MemoryStream())
{
q.Save(ms, ImageFormat.Png);
var img = new TagBuilder("img");
img.Attributes.Add("src", String.Format("data:image/png;base64,{0}", Convert.ToBase64String(ms.ToArray())));
img.Attributes.Add("alt", alt);
return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
}
}
}
}
}
----------------------------------------------View Part(CShtml page)--------------------------------------------
@using QRHelper
<!--Directly call from Html elements it will call first function-->
@Html.GenerateQrCode("{\"BookingID\":\"2541-12454-0154-545121855\"}", "QR code", 150, 150)<span>QR Code</span>
---------------------------------------------Call from controller--------------------------------------------
using System.Web;
public class HomeController : Controller
{
public ActionResult Index()
{
//It will second method in helper class
IHtmlString _qrCode=
GenerateQrCode("Your text here", "QR code", 150, 150);
}
}
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();
}
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string Address, string LatLong)
{
ViewBag.Message = "Address: " + Address+ " Lat Long: " + LatLong;
return View();
}
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
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 }
});
error: function (errorcode, textStatus, errorThrown) {
// alert("Error '" + errorcode.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
},
complete: function () {
// do your stuff after complete }
});
</script>
Friday 15 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;
}
}
}
{
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;
}
}
Wednesday 23 August 2017
Set Data type for Entity field
Question:
Answer:
[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"));
Friday 11 August 2017
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()
{
}
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();
}
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" />
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" />
Wednesday 17 May 2017
Ajax error handler custom function based on error code
Ajax call:
$.ajax(
{
url: "Service URL here",
method: "POST",
data: {params here},
contentType: "application/json",
processData: false,
success: function (response) {
//success code here
},
error: function (jqXhr, textStatus, errorThrown) {
errorHandler(jqXhr);
},
complete: function () {
//complete action
}
});
Common JavaScript function:
function errorHandler(jqXhr)
{
switch(jqXhr.status)
{
//here added
case 0:
toastr.error("Please check your internet connection");
//alert("Please check your internet connection");
break;
case 401:
toastr.error("Unauthorized access");
//alert("Unauthorized access");
break;
case 404:
toastr.error("Page not found");
//alert("Page not found");
break;
case 500:
toastr.error("Internal server error");
//alert("Internal server error");
break;
default:
toastr.error("Oops something went wrong, Try again latter.");
//alert("Oops something went wrong, Try again latter.");
break;
}
}
$.ajax(
{
url: "Service URL here",
method: "POST",
data: {params here},
contentType: "application/json",
processData: false,
success: function (response) {
//success code here
},
error: function (jqXhr, textStatus, errorThrown) {
errorHandler(jqXhr);
},
complete: function () {
//complete action
}
});
Common JavaScript function:
function errorHandler(jqXhr)
{
switch(jqXhr.status)
{
//here added
case 0:
toastr.error("Please check your internet connection");
//alert("Please check your internet connection");
break;
case 401:
toastr.error("Unauthorized access");
//alert("Unauthorized access");
break;
case 404:
toastr.error("Page not found");
//alert("Page not found");
break;
case 500:
toastr.error("Internal server error");
//alert("Internal server error");
break;
default:
toastr.error("Oops something went wrong, Try again latter.");
//alert("Oops something went wrong, Try again latter.");
break;
}
}
Monday 24 April 2017
Class implementing two interfaces having same method c#
Example Here
When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type. You can implement one or both of those interfaces explicitly.
When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type. You can implement one or both of those interfaces explicitly.
interface IControl { void Paint(); } interface ISurface { void Paint(); } class SampleClass : IControl, ISurface { // Both ISurface.Paint and IControl.Paint call this method. public void Paint() { Console.WriteLine("Paint method in SampleClass"); } }
class Test { static void Main() { SampleClass sc = new SampleClass(); IControl ctrl = (IControl)sc; ISurface srfc = (ISurface)sc; // The following lines all call the same method. sc.Paint(); ctrl.Paint(); srfc.Paint(); } }// Output: // Paint method in SampleClass // Paint method in SampleClass // Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period. For example:
public class SampleClass : IControl, ISurface { void IControl.Paint() { System.Console.WriteLine("IControl.Paint"); } void ISurface.Paint() { System.Console.WriteLine("ISurface.Paint"); } }// Call the Paint methods from Main. SampleClass obj = new SampleClass(); //obj.Paint(); // Compiler error. IControl c = (IControl)obj; c.Paint(); // Calls IControl.Paint on SampleClass. ISurface s = (ISurface)obj; s.Paint(); // Calls ISurface.Paint on SampleClass. // Output: // IControl.Paint // ISurface.Paint
----------------------------end----------------------------------------------------
Source Reference
I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.What I don't understand is when you create a variable that is of one of your Interface types:IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.So now, using your example, you could have:MyNiftyClass : IMyInterface { public void CallSomeMethod() { //Do something nifty } } MyOddClass : IMyInterface { public void CallSomeMethod() { //Do something odd } }
And now you have:IMyInterface nifty = new MyNiftyClass() IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.public void ThisMethodShowsHowItWorks(IMyInterface someObject) { someObject.CallSomeMethod(); }
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.public void AnotherClass() { IMyInterface nifty = new MyNiftyClass() IMyInterface odd = new MyOddClass() // Pass in the nifty class to do something nifty this.ThisMethodShowsHowItWorks(nifty); // Pass in the odd class to do something odd this.ThisMethodShowsHowItWorks(odd); }
EDITThis addresses what I think your intended question is - Why would you declare a variable to be of an interface type?That is, why use:IMyInterface foo = new MyConcreteClass();
in preference to:MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:public void AMethod() { // Why use this? IMyInterface foo = new MyConcreteClass(); // Why not use this? MyConcreteClass bar = new MyConcreteClass(); }
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
- I typically inject dependencies so the polymorphism is needed
- Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.Borrowing an example from itowlson, using concrete declaration you could not do this:public void AMethod(string input) { IMyInterface foo; if (input == "nifty") { foo = new MyNiftyClass(); } else { foo = new MyOddClass(); } foo.CallSomeMethod(); }
Subscribe to:
Posts (Atom)