Thursday, 30 June 2016

Signin directly without login with Owin SignInManager

No comments
UserManager :-

public SearchUserManager(IUserStore<ApplicationUser, int> store) : base(store)
        {
            this.UserValidator = new UserValidator<ApplicationUser, int>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };
            // Configure validation logic for passwords
            this.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
         
            this.EmailService = new EmailService();

            var dataProtectionProvider = Startup.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
        }


Controller

private readonly SearchUserManager _userManager;

public async Task<ActionResult> Check(string id)
        {
            if (id != null)
            {
                    var user = _userManager.FindById(id);
                    if (user != null)
                    {
                        await SignInAsync(user, false);                      
                    }
                    return RedirectToAction("Home");
             }
            return View();
        }

 private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {            SignInManager.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            SignInManager.AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }


read more

Thursday, 23 June 2016

URL routing the Querystring - mvc

No comments
Enum :-

  public enum Section
    {
        PersonalDetails =1,
        Goals=2

    }

RouteConfig.cs


 routes.MapRoute(
               name: "Personal Details",
               url: "{controller}/{tabName}",
               defaults: new { controller = "Details", action = "Details" },
               constraints: new { tabName = "PersonalDetails" }
           );

            routes.MapRoute(
               name: "Goals",
               url: "{controller}/{tabName}",
               defaults: new { controller = "Details", action = "Details" },
               constraints: new { tabName = "Goals" }
           );


Controller

  public async Task<ActionResult> Details(string tabName)
        {
             int  TabId = (int)Enum.Parse(typeof(Section), tabName);//Get Id from enum
             Section section = (Section)System.Enum.Parse(typeof(Section), tabName.ToString());//Get in enum

            return View();
         }

View

@Html.DropDownListFor(x => x.SectionName, Model.lstSection, "Select My Type", new { @class = "form-control", onchange = "document.location.href='/Investor/'+this.options[this.selectedIndex].value;''" })


//Check route name in view

@if (HttpContext.Current.Request.RequestContext.RouteData.Values != null)
        {
            if (@HttpContext.Current.Request.RequestContext.RouteData.Values.ContainsKey("tabName"))
            {

                var actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["tabName"].ToString();
                if (actionName == Section.PersonalDetails .ToString())
                {
                    <div id="PersonalDetails">
                        <div class="field">
                            @Html.Raw(Model.Content.Content)
                        </div>
                    </div>
                    <div class="clearfix">&nbsp;</div>
                }
            }

        }      
read more

Friday, 17 June 2016

Multiple if else statement - short by reflection

No comments
Multiple if-else statement

bool chkStatus = true;
            if (DetailsData != null)
            {
                if (DetailsData.Approved != null)
                {
                    if (DetailsData.Approved == false)
                    {
                        chkStatus = false;
                    }
                }
            }
            else
            {
                chkStatus = false;
            }

            if (AspirationData != null)
            {
                if (AspirationData.Approved != null)
                {
                    if (AspirationData.Approved == false)
                    {
                        chkStatus = false;
                    }
                }
            }
            else
            {
                chkStatus = false;
            }


//Short this if else by reflection

 private bool IsWizardApproved<T>(T t)
        {
            if (t == null) return false;
            foreach (PropertyInfo info in t.GetType().GetProperties())
            {
                if (info.Name.ToLower() == "approved")
                {
                    PropertyInfo propertyInfos = t.GetType().GetProperty(info.Name);
                    if (info.GetValue(t, null) != null)
                        return (bool)info.GetValue(t, null);
                }
            }
            return false;

        }

//Call IsWizardApproved for class

   model.Approved = (IsWizardApproved<DetailsData>(detailsData) &&
                && IsWizardApproved<AspirationData>(aspirationData);
read more

Fill dictionary with Table (model) column name and its value - with reflection

No comments
//Dictionary

 public Dictionary<string, string> BindModelDictioanry<T>(T t) where T : class
        {
            Dictionary<string, string> dictModel = new Dictionary<string, string>();
            foreach (PropertyInfo info in t.GetType().GetProperties())
            {
                PropertyInfo propertyInfos = t.GetType().GetProperty(info.Name);
                if (propertyInfos.PropertyType == typeof(ListItemValue))
                {
                    var value = (your column datatype)info.GetValue(t, null);
                    var key = info.Name; //This will be column name
                    dictModel.Add(key, value.ToString()); //This will be column value
                }          
            }
            return dictModel;

        }

//Using reflection

ViewModel model = new ViewModel();
model.DicFormaData = BindModelDictioanry<PersonalDetails>(personalDetailsData);

//model.DicFormaData 

public Dictionary<string, string> DicFormaData { get; set; }

read more

Switch through Enum mvc

No comments
  public enum Section
    {
        PersonalDetails = 1,
        GoalsAspirations,
        PersonalProfile,
        BusinessExpectations,
        PersonalityAttitude,
        RoleSelection,
        FinancialProfile
    }


//Controller

  Section section = (Section)System.Enum.Parse(typeof(Section), 5);
  switch (section)
            {
                case Section.PersonalityAttitude:
                    break;
                case Section.RoleSelection:
                    break;
                case Section.FinancialProfile:
                    break;
                default:
                    break;
            }

//To get in int
Model.SectionId = (int)section;
read more

Saturday, 11 June 2016

Check if queystring is not null globally

No comments
public class TestController : Controller
    {
   
        int _TabId;

   #region Declaration
        private int TabId
        {
            get
            {
                if (Request.QueryString["tabId"] == null)
                    return 0;
                if (Request.QueryString["tabId"] != null)
                {
                    int.TryParse(Request.QueryString["tabId"], out _TabId);
                    return _TabId;
                }
                return _TabId;
            }
        }
        #endregion

public async Task<ActionResult> Test()
        {          
            Model model = new Model();
            int id=TabId;
            return View(model);
        }
}
read more

Validate Model manually

No comments
public void ValidateModel<T>(T model)
        {
            var validate = new ValidationContext(model, null, null);
            var result = new List<ValidationResult>();
            var isValid = Validator.TryValidateObject(model, validate, result);
            if (!isValid)
            {
                foreach (var error in result.Select(s => s.ErrorMessage))
                {
                    ModelState.AddModelError("Error", error);
                }
            }
        }

//Validating

             ValidateModel<InvestmentReasonViewModel>(investmentReasonViewModel);
            if (!ModelState.IsValid)
            {
                return questionViewModel;

            }     
read more

Thursday, 9 June 2016

Reflection to fill class from another class through Request.Form

No comments
Relection 


 public T ParseObject<T>() where T : new()
        {
            var classObj = new T();
            for (int iForm = 0; iForm < Request.Form.Count; iForm++)
            {
                foreach (PropertyInfo info in classObj.GetType().GetProperties())
                {                
                        PropertyInfo propertyInfos = classObj.GetType().GetProperty(info.Name);
                        Type propertyType = info.PropertyType;
                        if (propertyInfos.PropertyType == typeof(Nullable<Int32>))
                        {
                            info.SetValue(classObj, (ReflectionConversion.ConvertToInt(Request.Form[iForm])), null);
                        }
                        else if (propertyInfos.PropertyType == typeof(Int32))
                        {
                            info.SetValue(classObj, (ReflectionConversion.ConvertToInt(Request.Form[iForm])), null);
                        }
                        else {
                            info.SetValue(classObj, Request.Form[iForm], null);
                        }                  
                }
            }
            return classObj;

        }

Consuming Reflector in controller

var personalDetails = ParseObject<PersonalDetails>();

Validating (conversion) Reflector Data


 public static class ReflectionConversion
    {
        public static string ConvertToDateString(object date)
        {
            if (date == null)
                return string.Empty;

            return date == null ? string.Empty : Convert.ToDateTime(date).ConvertDate();
        }

        public static string ConvertToString(object value)
        {
            return Convert.ToString(ReturnEmptyIfNull(value));
        }

        public static int ConvertToInt(object value)
        {
            return Convert.ToInt32(ReturnZeroIfNull(value));
        }

        public static long ConvertToLong(object value)
        {
            return Convert.ToInt64(ReturnZeroIfNull(value));
        }

        public static decimal ConvertToDecimal(object value)
        {
            return Convert.ToDecimal(ReturnZeroIfNull(value));
        }

        public static DateTime convertToDateTime(object date)
        {
            return Convert.ToDateTime(ReturnDateTimeMinIfNull(date));
        }

        public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
        {
            if (datetTime != DateTime.MinValue)
            {
                if (excludeHoursAndMinutes)
                    return datetTime.ToString("yyyy-MM-dd");
                return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }
            return null;
        }
        public static object ReturnEmptyIfNull(this object value)
        {
            if (value == DBNull.Value)
                return string.Empty;
            if (value == null)
                return string.Empty;
            return value;
        }
        public static object ReturnZeroIfNull(this object value)
        {
            if (value == DBNull.Value)
                return 0;
            if (value == null)
                return 0;
            return value;
        }
        public static object ReturnDateTimeMinIfNull(this object value)
        {
            if (value == DBNull.Value)
                return DateTime.MinValue;
            if (value == null)
                return DateTime.MinValue;
            return value;
        }

    }


read more

Validate webapi model with ModelState

No comments
Our model -- > Customer.cs

validating in controller 

                Validate<Consumer>(consumer);
                if (!ModelState.IsValid)
                {
                    var message = string.Join(" \n ", ModelState.Values
                              .SelectMany(v => v.Errors)
                              .Select(e => e.ErrorMessage));
                    return ResponseMessage(HttpStatusCode.NonAuthoritativeInformation, message);
                }
read more

Tuesday, 7 June 2016

Factory in Angular JS

No comments

Service.js

app.factory('Availability', ['$rootScope', '$http', function ($rootScope, $http) {
    return {
        Update: function () {
     
        }
    }
}]);


Controller.js

//calling Availability factory in controller

    var Controller = function ($scope, $location, $http, Availability) {
          Availability. Update();
   }

//calling factory from js


        var injectorAvailable = angular.element(document.querySelector('[ng-app]')).injector();
        var availabilityStatus = injectorAvailable.get('Availability ');
        Availability. Update();
read more

Monday, 6 June 2016

Post Form data and list with ajax in mvc

No comments
.js


var lstMultiModels = [];

 lstMultiModels.push({ inid: $(this).find('.txtOutInId').val(), price: $(this).find('.price').val(), qty: $(this).find('.Qty').val() });      
var lstModel = JSON.stringify({ date: $('#date').val(), id: $('#id').val(), 'lstMultiModels': lstMultiModels});

$.ajax({
        type: "POST",
        url: "/Drugs/Out",
        data: lstModel,
        async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (responseData) {
        },
        error: function () { }
    })

lstMultiModels.cs

public int inid{ get; set; }
public int price{ get; set; }
public int qty{ get; set; }

Models.CS

public DateTime date  {get; set; }
public int id {get; set; }
public List<lstMultiModels> lstMultiModels{get; set; }

Controller.cs

        [HttpPost]
        public ActionResult Out(Models Models)
        {

        }

read more

Friday, 3 June 2016

Validate controller with session and redirect again to left page mvc

No comments
HTML

<body>

    <section class="content" style="width: 50%;margin-left: 25%;margin-top: 50px;">
        <div class="row">          
            @if (TempData["Signup"] == "success")
            {
                <div class="alert alert-success  alert-dismissible" style="margin-top: 5px">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>                            
                    Signup success , please login to continue..
                </div>
            }
            else
            {
                <div class="alert alert-success  alert-dismissible" style="margin-top: 5px;visibility:hidden">                  
                    &nbsp;
                </div>
            }
        </div>
    </section>

    <div class="login-card">
        <h1>Log-in</h1><br>
        <form action="@Url.Action("Login","Home")@(Request.QueryString["ReturnUrl"] != null ? "?"+Request.QueryString : "")" method="post">
            @Html.TextBoxFor(x => x.emailid, new { placeholder = "Email", maxlength = "50", tabindex = "1", @class = "form-control" })
            @Html.TextBoxFor(x => x.password, new { placeholder = "Password", type="password",maxlength = "50", tabindex = "2", @class = "form-control" })          
            <button name="login" class="login login-submit">Login</button>
        </form>
        <div class="login-help">
            <a href="@Url.Action("UserRegistration","Home")">Register</a> • <a href="#">Forgot Password</a>
        </div>
        @if (ViewContext.ViewData.ModelState.ContainsKey("Error") || ViewContext.ViewData.ModelState.ContainsKey("Login"))
        {
            <div class="alert alert-danger alert-dismissible" style="margin-top: 5px">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                @Html.ValidationSummary(false)
            </div>
        }
     
    </div>

</body>



Controller

SessionFactory.cs 

to store session

   public class SessionFactory
    {
        private static SessionFactory _SessionFactory = new SessionFactory();

        public SessionFactory()
        {

        }

        public static SessionFactory Instance
        {
            get
            {
                return _SessionFactory;
            }
        }

        public Users CurrentUsers
        {
            get
            {
                if (HttpContext.Current.Session["Users"] == null)
                {
                    return null;
                }
                return (Users)HttpContext.Current.Session["Users"];
            }

            set
            {
                HttpContext.Current.Session["Users"] = value;
            }
        }
    }


ValidateUserAttribute.cs

attribute to validate

 public class ValidateUserAttribute: ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {          
            if (SessionFactory.Instance.CurrentUsers == null)
                filterContext.Result = new RedirectResult(string.Format("/Home/Login?ReturnUrl={0}",HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath)));          
        }
    }


Property

to check querystring

 private string ReturnUrl
        {
            get
            {
                if (Request.QueryString["ReturnUrl"] != null)
                {
                    return Request.QueryString["ReturnUrl"];
                }
                return string.Empty;
            }
        }

When Login

if querystring found than redirect to that url

      [HttpPost]
        public ActionResult Login(Users users)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("Error", "");
                return View(users);
            }
         
            SessionFactory.Instance.CurrentUsers = userData;
            if (!string.IsNullOrEmpty(ReturnUrl))
            {
                return RedirectPermanent(ReturnUrl);
            }
            else
                return RedirectToAction("Dashboard", "Dashboard");
        }


Validate controller


  [ValidateUser]
    public class MyController : Controller
    {
    }
read more

Thursday, 2 June 2016

Create keystore and SHA-1 signing-certificate for android app in cordova

No comments
open https://console.developers.google.com

go to credential ---> create credential -->OauthCLientId --> android

enter package name from androidmenifest.xml

for getting SHA-1 signing-certificate

open cmd and type

keytool -genkey -v -keystore C:/CaribeanTaxi/CaribeanTaxi.keystore -alias [CaribeanTaxi] -keyalg RSA -keysize 2048 -validity 10000

here C:/CaribeanTaxi/CaribeanTaxi.keystore is keystore path which ever you pass
RSA is algorithm

now enter password and all fields which it asks for

now open build.json in your cordova project  and add

{
     "android": {
         "release": {
             "keystore": "C:/CaribeanTaxi/CaribeanTaxi.keystore",
             "storePassword": "caribean",
             "alias": "CaribeanTaxi",
             "password" : "caribean",
             "keystoreType": ""
         }
     }
 }

here password is same which asked while creating keystore

no type in cmd

keytool -exportcert -keystore C:\CaribeanTaxi\CaribeanTaxi.keystore -list -v

this will ask you to enter same password 



To Create Release

add new buid.json  in root folder outside of www

build.json


{
     "android": {
         "release": {
              "keystore""C:\\app\\app.keystore",
             "storePassword""app",
             "alias""app",
             "password" : "app",
             "keystoreType"""
         }
     }
 }
 
 
read more