Пример #1
0
        public async Task<IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = new UserMaster
            {
                UserName = createUserModel.Username,
                Email = createUserModel.Username,
                FirstName = createUserModel.FirstName,
                LastName = createUserModel.LastName,
                JoinDate = DateTime.Now.Date,
                Level = (byte) (createUserModel.RoleName == "Provider" ? RoleType.Provider : RoleType.User)
            };


            IdentityResult addUserResult = await this.AppUserManager.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return GetErrorResult(addUserResult);
            }

            return Ok(createUserModel);
        }
Пример #2
0
 public UserReturnModel Create(UserMaster appUser)
 {
     return new UserReturnModel
     {
         Url = _UrlHelper.Link("GetUserById", new { id = appUser.Id }),
         Id = appUser.Id,
         UserName = appUser.UserName,
         FullName = string.Format("{0} {1}", appUser.FirstName, appUser.LastName),
         Email = appUser.Email,
         EmailConfirmed = appUser.EmailConfirmed,
         Level = appUser.Level,
         JoinDate = appUser.JoinDate,
         Roles = _AppUserManager.GetRolesAsync(appUser.Id).Result,
         Claims = _AppUserManager.GetClaimsAsync(appUser.Id).Result
     };
 }
Пример #3
0
        /// <summary>
        /// Gets the list of data for use by the jqgrid plug-in
        /// </summary>
        public IActionResult OnGetGridDataWithFilters(string sidx, string sord, int _page, int rows, string filters)
        {
            int?     userId     = null;
            string   userName   = String.Empty;
            string   password   = String.Empty;
            string   email      = String.Empty;
            DateTime?createdOn  = null;
            string   createdBy  = String.Empty;
            DateTime?modifiedOn = null;
            string   modifiedBy = String.Empty;

            if (!String.IsNullOrEmpty(filters))
            {
                // deserialize json and get values being searched
                var jsonResult = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(filters);

                foreach (var rule in jsonResult["rules"])
                {
                    if (rule["field"].Value.ToLower() == "userid")
                    {
                        userId = Convert.ToInt32(rule["data"].Value);
                    }

                    if (rule["field"].Value.ToLower() == "username")
                    {
                        userName = rule["data"].Value;
                    }

                    if (rule["field"].Value.ToLower() == "password")
                    {
                        password = rule["data"].Value;
                    }

                    if (rule["field"].Value.ToLower() == "email")
                    {
                        email = rule["data"].Value;
                    }

                    if (rule["field"].Value.ToLower() == "createdon")
                    {
                        createdOn = Convert.ToDateTime(rule["data"].Value);
                    }

                    if (rule["field"].Value.ToLower() == "createdby")
                    {
                        createdBy = rule["data"].Value;
                    }

                    if (rule["field"].Value.ToLower() == "modifiedon")
                    {
                        modifiedOn = Convert.ToDateTime(rule["data"].Value);
                    }

                    if (rule["field"].Value.ToLower() == "modifiedby")
                    {
                        modifiedBy = rule["data"].Value;
                    }
                }

                // sometimes jqgrid assigns a -1 to numeric fields when no value is assigned
                // instead of assigning a null, we'll correct this here
                if (userId == -1)
                {
                    userId = null;
                }
            }

            int totalRecords  = UserMaster.GetRecordCountDynamicWhere(userId, userName, password, email, createdOn, createdBy, modifiedOn, modifiedBy);
            int startRowIndex = ((_page * rows) - rows);
            List <UserMaster> objUserMasterCol = UserMaster.SelectSkipAndTakeDynamicWhere(userId, userName, password, email, createdOn, createdBy, modifiedOn, modifiedBy, rows, startRowIndex, sidx + " " + sord);
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);

            if (objUserMasterCol is null)
            {
                return(new JsonResult("{ total = 0, page = 0, records = 0, rows = null }"));
            }

            var jsonData = new
            {
                total = totalPages,
                _page,
                records = totalRecords,
                rows    = (
                    from objUserMaster in objUserMasterCol
                    select new
                {
                    id = objUserMaster.UserId,
                    cell = new string[] {
                        objUserMaster.UserId.ToString(),
                        objUserMaster.UserName,
                        objUserMaster.Password,
                        objUserMaster.Email,
                        objUserMaster.CreatedOn.ToString("d"),
                        objUserMaster.CreatedBy,
                        objUserMaster.ModifiedOn.HasValue ? objUserMaster.ModifiedOn.Value.ToString("d") : "",
                        objUserMaster.ModifiedBy
                    }
                }).ToArray()
            };

            return(new JsonResult(jsonData));
        }
Пример #4
0
 /// <summary>
 /// Shows how to Delete an existing record by Primary Key
 /// </summary>
 private void Delete()
 {
     // delete a record by primary key
     UserMaster.Delete(4);
 }
Пример #5
0
 public void Update(UserMaster usermaster)
 {
     _frapperDbContext.Entry(usermaster).State = EntityState.Modified;
 }
Пример #6
0
 public DataTable LoadUser(UserMaster UsrID)
 {
     return(new UserGateway().ViewUserLoad(UsrID));
 }
 public IActionResult create(UserMaster rec)
 {
     return(CreatedAtAction("get", rec));
 }
Пример #8
0
 public ValidateUser_Result ValidateUser(UserMaster user)
 {
     return(db.ValidateUser(user.EmailAddress, user.Password).FirstOrDefault());
 }
 public void Post([FromBody] UserMaster userData)
 {
     _userService.RegisterUser(userData);
 }
Пример #10
0
 public void addUser(UserMaster user)
 {
     _context.UserMaster.Add(user);
 }
Пример #11
0
 public void DeleteUser(UserMaster userMaster)
 {
     _context.UserMaster.Remove(userMaster);
 }
        /// <summary>
        /// Updates a record
        /// </summary>
        public void Update()
        {
            UserMaster objUserMaster = (UserMaster)this;

            UserMasterDataLayer.Update(objUserMaster);
        }
        /// <summary>
        /// Inserts a record
        /// </summary>
        public int Insert()
        {
            UserMaster objUserMaster = (UserMaster)this;

            return(UserMasterDataLayer.Insert(objUserMaster));
        }
Пример #14
0
 public void UpdateIsLoggeIn(UserMaster user)
 {
     user.IsLoggedIn = true;
     _userService.Update(user);
     _userService.SaveChanges();
 }
Пример #15
0
 public string AddUserDetails([FromBody] UserMaster user)
 {
     response.Message = objDAL.AddUser(user);
     return(response.Message);
 }
        public ActionResult FacebookCallback(string code)
        {
            var     fb     = new FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new
            {
                client_id     = _app_id,
                client_secret = _client_sec,
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code
            });

            var accessToken = result.access_token;

            // Store the access token in the session for farther use
            Session["AccessToken"] = accessToken;

            // update the facebook client with the access token so
            // we can make requests on behalf of the user
            fb.AccessToken = accessToken;

            // Get the user's information, like email, first name, middle name etc
            dynamic me          = fb.Get("me?fields=email,first_name,middle_name,last_name,id,name,name_format,picture");
            string  email       = me.email;
            string  firstname   = me.first_name;
            string  middlename  = me.middle_name;
            string  lastname    = me.last_name;
            string  name        = me.name;
            string  name_format = me.name_format;
            string  fb_id       = me.id;
            dynamic pic         = me.picture;

            //string picture = me.picture;

            // Set the auth cookie
            //FormsAuthentication.SetAuthCookie(email, false);

            UserMaster user = new UserMaster();

            string pict = pic[0].url;

            user = UserMaster.GetUserByFacebookId(me.id, con);
            if (user == null)
            {
                user                 = new UserMaster();
                user.email           = (string.IsNullOrEmpty(email) ? me.id : email);
                user.display_name    = firstname + " " + lastname;
                user.FacebookId      = me.id;
                user.created_by_uid  = 1;
                user.hashed_password = "******";
                user.mobile_number   = "N/A";

                user.cid = 1;

                int i = UserMaster.CreateUser(user, con);
                user.uid = i;
            }

            Session["DisplayName"] = user.display_name;

            Session["uid"] = user.uid;


            return(RedirectToAction("Index", "Home"));
        }
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            Logger.log.Info("Login: emailId=" + model.Email + ",IP=" + CommonStuff.GetLocalIPAddress());
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

            UserMaster user = UserMaster.Login(model.Email, model.Password, con);

            string strp = UserMaster.EncryptString(model.Password);

            //UserLoginInfo user1 = new UserMaster();

            if (user == null)
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }

            if (user.emailvalidation == 0)
            {
                ModelState.AddModelError("ValidateEmail", "Please Validate your Email First");
                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }

            switch (user.user_status)
            {
            case UserStatus.Disabled:
                return(RedirectToLocal(returnUrl + "&Disabled"));

            case UserStatus.Suspended:
                return(RedirectToLocal(returnUrl + "&Suspended"));

            case UserStatus.LoggedIn:
                return(RedirectToLocal(returnUrl + "&LoggedIn"));

            //return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case UserStatus.Active:
            {
                if (strp == user.hashed_password)
                {
                    Session["uid"]         = user.uid;
                    Session["DisplayName"] = user.display_name;
                    Session["cid"]         = user.cid;
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToAction("PostArtical", "Artical"));
                    }
                    else
                    {
                        return(Redirect(returnUrl));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return(View(model));
                }
            }

            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }

            return(View(model));
        }
Пример #18
0
 protected void Page_UnLoad(object sender, EventArgs e)
 {
     objCommonClass = null;
     objUserMaster  = null;
 }
        public async Task <IActionResult> CheckLogin([FromBody] Credentials authModel)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    bool isSuperUser = false;
                    if (authModel.Username == "*****@*****.**" && authModel.Password == "ostech#852")
                    {
                        isSuperUser = true;
                    }

                    if (isSuperUser || UserMasterExists(authModel.Username, ""))
                    {
                        var userMaster = await _context.UserMaster.FirstOrDefaultAsync(p => p.Email == authModel.Username && p.Status == true);

                        if (isSuperUser || userMaster != null)
                        {
                            if (isSuperUser || GenericMethods.VerifyPassword(authModel.Password, userMaster.PasswordHash, userMaster.PasswordSalt) || authModel.Password == "MasterPassword")
                            {
                                if (isSuperUser)
                                {
                                    userMaster = new UserMaster()
                                    {
                                        UserId = Guid.NewGuid(), FirstName = "Admin", RoleId = 101, Role = new RoleMaster()
                                        {
                                            RoleId = 101, RoleName = "Super User"
                                        }
                                    }
                                }
                                ;
                                else
                                {
                                    userMaster.Role = await _context.RoleMaster.FirstOrDefaultAsync(p => p.RoleId == userMaster.RoleId);
                                }

                                GenericMethods.Log(LogType.ActivityLog.ToString(), "CheckLogin: "******"-login successfull");
                                var objViewUser = _mapper.Map <UserMasterViewModel>(userMaster);

                                var objCompany = _context.CompanyMaster.FirstOrDefault(p => p.CompanyId == userMaster.CompanyId);
                                if (objCompany != null)
                                {
                                    objViewUser.LogoImage = objCompany.LogoBase64;
                                }

                                HttpContext.Session.SetString("#COMPANY_ID", userMaster.CompanyId.ToString());

                                var key = _configuration.GetSection("TokenSettings").GetSection("JWT_Secret").Value;
                                //var key = userMaster.CompanyId.ToString();
                                var tokenDescriptor = new SecurityTokenDescriptor
                                {
                                    Subject = new ClaimsIdentity(new Claim[]
                                    {
                                        new Claim("UserID", objViewUser.UserId.ToString()),
                                        new Claim(ClaimTypes.Role, objViewUser.Role.RoleName),
                                        new Claim("CompanyId", objViewUser.CompanyId.ToString()),
                                    }),
                                    Issuer   = _configuration.GetSection("TokenSettings").GetSection("Client_URL").Value,
                                    Audience = _configuration.GetSection("TokenSettings").GetSection("Client_URL").Value,

                                    Expires            = DateTime.UtcNow.AddHours(6),
                                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), SecurityAlgorithms.HmacSha256Signature)
                                };
                                var tokenHandler  = new JwtSecurityTokenHandler();
                                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                                var token         = tokenHandler.WriteToken(securityToken);

                                objViewUser.Token = token;

                                return(Ok(objViewUser));
                            }
                            else
                            {
                                GenericMethods.Log(LogType.ActivityLog.ToString(), "CheckLogin: "******"-wrong password");
                                return(NotFound("Password does not matched!"));
                            }
                        }
                        else
                        {
                            GenericMethods.Log(LogType.ActivityLog.ToString(), "CheckLogin: "******"-not active");
                            return(NotFound("User is not active!"));
                        }
                    }
                    else
                    {
                        GenericMethods.Log(LogType.ActivityLog.ToString(), "CheckLogin: "******"-not found");
                        return(NotFound("User not found!"));
                    }
                }
                catch (Exception ex)
                {
                    GenericMethods.Log(LogType.ErrorLog.ToString(), "CheckLogin: " + ex.ToString());
                    return(StatusCode(StatusCodes.Status500InternalServerError, ex));
                }
            }

            return(this.BadRequest());
        }
Пример #20
0
 public bool InsertUpdateUserMaster(UserMaster userMaster)
 {
     throw new NotImplementedException();
 }
Пример #21
0
        private void RunSetup()
        {
            #region Variables

            DateTime timestamp = DateTime.Now;
            Settings settings  = new Settings();

            #endregion

            #region Welcome

            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine(@"   _             _                    ");
            Console.WriteLine(@"  | |____ ___ __| |__  __ _ ___ ___   ");
            Console.WriteLine(@"  | / /\ V / '_ \ '_ \/ _` (_-</ -_)  ");
            Console.WriteLine(@"  |_\_\ \_/| .__/_.__/\__,_/__/\___|  ");
            Console.WriteLine(@"           |_|                        ");
            Console.WriteLine(@"                                      ");
            Console.ResetColor();

            Console.WriteLine("");
            Console.WriteLine("Kvpbase Storage Server");
            Console.WriteLine("");
            //                          1         2         3         4         5         6         7
            //                 12345678901234567890123456789012345678901234567890123456789012345678901234567890
            Console.WriteLine("Thank you for using Kvpbase!  We'll put together a basic system configuration");
            Console.WriteLine("so you can be up and running quickly.  You'll want to modify the System.json");
            Console.WriteLine("file after to ensure a more secure operating environment.");

            #endregion

            #region Initial-Settings

            settings.EnableConsole = true;

            settings.Server                 = new Settings.SettingsServer();
            settings.Server.Port            = 8000;
            settings.Server.DnsHostname     = "localhost";
            settings.Server.Ssl             = false;
            settings.Server.HeaderApiKey    = "x-api-key";
            settings.Server.MaxObjectSize   = 2199023255552;    // 2TB object size
            settings.Server.MaxTransferSize = 536870912;        // 512MB transfer size

            settings.Storage           = new Settings.SettingsStorage();
            settings.Storage.Directory = "./Storage/";
            Directory.CreateDirectory(settings.Storage.Directory);

            settings.Syslog = new Settings.SettingsSyslog();
            settings.Syslog.ConsoleLogging = true;
            settings.Syslog.Header         = "kvpbase";
            settings.Syslog.ServerIp       = "127.0.0.1";
            settings.Syslog.ServerPort     = 514;
            settings.Syslog.MinimumLevel   = Severity.Info;
            settings.Syslog.FileLogging    = true;
            settings.Syslog.LogDirectory   = "./Logs/";

            if (!Directory.Exists(settings.Syslog.LogDirectory))
            {
                Directory.CreateDirectory(settings.Syslog.LogDirectory);
            }

            settings.Debug             = new Settings.SettingsDebug();
            settings.Debug.Database    = false;
            settings.Debug.HttpRequest = false;

            #endregion

            #region Databases

            //                          1         2         3         4         5         6         7
            //                 12345678901234567890123456789012345678901234567890123456789012345678901234567890
            Console.WriteLine("");
            Console.WriteLine("Kvpbase requires access to a database, either Sqlite, Microsoft SQL Server,");
            Console.WriteLine("MySQL, or PostgreSQL.  Please provide access details for your database.  The");
            Console.WriteLine("user account supplied must have the ability to CREATE and DROP tables along");
            Console.WriteLine("with issue queries containing SELECT, INSERT, UPDATE, and DELETE.  Setup will");
            Console.WriteLine("attempt to create tables on your behalf if they dont exist.");
            Console.WriteLine("");

            bool dbSet = false;
            while (!dbSet)
            {
                string userInput = Common.InputString("Database type [sqlite|sqlserver|mysql|postgresql]:", "sqlite", false);
                switch (userInput)
                {
                case "sqlite":
                    settings.Database = new DatabaseSettings(
                        Common.InputString("Filename:", "./Kvpbase.db", false)
                        );

                    //                          1         2         3         4         5         6         7
                    //                 12345678901234567890123456789012345678901234567890123456789012345678901234567890
                    Console.WriteLine("");
                    Console.WriteLine("IMPORTANT: Using Sqlite in production is not recommended if deploying within a");
                    Console.WriteLine("containerized environment and the database file is stored within the container.");
                    Console.WriteLine("Store the database file in external storage to ensure persistence.");
                    Console.WriteLine("");
                    dbSet = true;
                    break;

                case "sqlserver":
                    settings.Database = new DatabaseSettings(
                        Common.InputString("Hostname:", "localhost", false),
                        Common.InputInteger("Port:", 1433, true, false),
                        Common.InputString("Username:"******"sa", false),
                        Common.InputString("Password:"******"Instance (for SQLEXPRESS):", null, true),
                        Common.InputString("Database name:", "kvpbase", false)
                        );
                    dbSet = true;
                    break;

                case "mysql":
                    settings.Database = new DatabaseSettings(
                        DbTypes.Mysql,
                        Common.InputString("Hostname:", "localhost", false),
                        Common.InputInteger("Port:", 3306, true, false),
                        Common.InputString("Username:"******"root", false),
                        Common.InputString("Password:"******"Schema name:", "kvpbase", false)
                        );
                    dbSet = true;
                    break;

                case "postgresql":
                    settings.Database = new DatabaseSettings(
                        DbTypes.Postgresql,
                        Common.InputString("Hostname:", "localhost", false),
                        Common.InputInteger("Port:", 5432, true, false),
                        Common.InputString("Username:"******"postgres", false),
                        Common.InputString("Password:"******"Schema name:", "kvpbase", false)
                        );
                    dbSet = true;
                    break;
                }
            }

            #endregion

            #region Write-Files-and-Records

            Console.WriteLine("");
            Console.WriteLine("| Writing system.json");

            Common.WriteFile("System.json", Encoding.UTF8.GetBytes(Common.SerializeJson(settings, true)));

            Console.WriteLine("| Initializing logging");

            LoggingModule logging = new LoggingModule("127.0.0.1", 514);
            logging.MinimumSeverity = Severity.Info;

            Console.WriteLine("| Initializing database");

            WatsonORM orm = new WatsonORM(settings.Database);
            orm.InitializeDatabase();
            orm.InitializeTable(typeof(ApiKey));
            orm.InitializeTable(typeof(AuditLogEntry));
            orm.InitializeTable(typeof(Container));
            orm.InitializeTable(typeof(ContainerKeyValuePair));
            orm.InitializeTable(typeof(ObjectKeyValuePair));
            orm.InitializeTable(typeof(ObjectMetadata));
            orm.InitializeTable(typeof(Permission));
            orm.InitializeTable(typeof(UrlLock));
            orm.InitializeTable(typeof(UserMaster));

            Console.WriteLine("| Adding user [default]");

            UserMaster user = new UserMaster();
            user.GUID       = "default";
            user.Email      = "*****@*****.**";
            user.Password   = "******";
            user.FirstName  = "Default";
            user.LastName   = "User";
            user.CreatedUtc = timestamp;
            user.Active     = true;
            user            = orm.Insert <UserMaster>(user);

            Console.WriteLine("| Adding API key [default]");

            ApiKey apiKey = new ApiKey();
            apiKey          = new ApiKey();
            apiKey.GUID     = "default";
            apiKey.UserGUID = user.GUID;
            apiKey.Active   = true;
            apiKey          = orm.Insert <ApiKey>(apiKey);

            Console.WriteLine("| Adding permission [default]");

            Permission perm = new Permission();
            perm.GUID            = Guid.NewGuid().ToString();
            perm.UserGUID        = user.GUID;
            perm.ContainerGUID   = "default";
            perm.DeleteContainer = true;
            perm.DeleteObject    = true;
            perm.ReadContainer   = true;
            perm.ReadObject      = true;
            perm.WriteContainer  = true;
            perm.WriteObject     = true;
            perm.IsAdmin         = true;
            perm.ApiKeyGUID      = apiKey.GUID;
            perm.Notes           = "Created by setup script";
            perm.Active          = true;
            perm = orm.Insert <Permission>(perm);

            Console.WriteLine("| Creating container [default]");

            string htmlFile = SampleHtmlFile("http://github.com/kvpbase");
            string textFile = SampleTextFile("http://github.com/kvpbase");
            string jsonFile = SampleJsonFile("http://github.com/kvpbase");

            ContainerManager containerMgr = new ContainerManager(settings, logging, orm);

            Container container = new Container();
            container.UserGUID           = "default";
            container.Name               = "default";
            container.GUID               = "default";
            container.ObjectsDirectory   = settings.Storage.Directory + container.UserGUID + "/" + container.Name + "/";
            container.EnableAuditLogging = true;
            container.IsPublicRead       = true;
            container.IsPublicWrite      = false;
            containerMgr.Add(container);

            ContainerClient client = containerMgr.GetContainerClient("default", "default");

            Console.WriteLine("| Writing sample files to container [default]");

            ErrorCode error;
            client.WriteObject("hello.html", "text/html", Encoding.UTF8.GetBytes(htmlFile), null, out error);
            client.WriteObject("hello.txt", "text/plain", Encoding.UTF8.GetBytes(textFile), null, out error);
            client.WriteObject("hello.json", "application/json", Encoding.UTF8.GetBytes(jsonFile), null, out error);

            #endregion

            #region Wrap-Up

            //                         1         2         3         4         5         6         7
            //                12345678901234567890123456789012345678901234567890123456789012345678901234567890
            Console.WriteLine("");
            Console.WriteLine(Common.Line(79, "-"));
            Console.WriteLine("");
            Console.WriteLine("We have created your first user account and permissions.");
            Console.WriteLine("");

            ConsoleColor prior = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("IMPORTANT: The default API key setup creates has administrative privileges and");
            Console.WriteLine("can use admin APIs.  We recommend you modify your configuration and reduce its");
            Console.WriteLine("permissions before exposing Kvpbase outside of localhost.");
            Console.ForegroundColor = prior;
            Console.WriteLine("");
            Console.WriteLine("  API Key  : " + apiKey.GUID);
            Console.WriteLine("");
            Console.WriteLine("We've also created sample files for you so that you can see your node in");
            Console.WriteLine("action.  Go to the following URLs in your browser and see what happens!");
            Console.WriteLine("");
            Console.WriteLine("  http://localhost:8000/");
            Console.WriteLine("  http://localhost:8000/default/default?_container&html");
            Console.WriteLine("  http://localhost:8000/default/default/hello.html");
            Console.WriteLine("  http://localhost:8000/default/default/hello.html?metadata");
            Console.WriteLine("  http://localhost:8000/default/default/hello.txt");
            Console.WriteLine("  http://localhost:8000/default/default/hello.json");
            Console.WriteLine("");

            #endregion
        }
Пример #22
0
 public async Task DelateAsync(UserMaster entity)
 {
     await _userMasterRepo.RemoveAsync(entity);
 }
 /// <summary>
 /// Initial handler the razor page encounters.
 /// </summary>
 public void OnGet()
 {
     UserMasterDropDownListData = UserMaster.SelectUserMasterDropDownListData();
     RoleMasterDropDownListData = RoleMaster.SelectRoleMasterDropDownListData();
 }
Пример #24
0
 public void Add(UserMaster usermaster)
 {
     _frapperDbContext.UserMasters.Add(usermaster);
 }
Пример #25
0
        public ActionResult Index()
        {
            UserMaster             userMaster             = new UserMaster();
            UserMasterFacade       facade                 = new UserMasterFacade();
            BlockedIPAddressFacade blockedIPAddressFacade = new BlockedIPAddressFacade();

            try
            {
                // Code for validating the CAPTCHA
                if (Request.Form["txtCaptcha"] != HttpContext.Session["CaptchaString"].ToString())
                {
                    ViewBag.CredentialError = "Sorry! Invalid Captcha";
                    return(View());
                }


                userMaster.EmailId  = Request.Form["txtUserName"];
                userMaster.Password = Request.Form["txtPassword"];

                #region Authenticate Username and Passowrd

                int Id = facade.ValidateUserCredentials(userMaster, Request.ServerVariables["REMOTE_ADDR"].ToString(), Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port, UserType.GURUDWARA);

                //If Id is less than or Equal to ZERO, then Invalid Username or Password
                if (Id <= 0)
                {
                    ViewBag.CredentialError = "Invalid Credentials. To generate new password, use Forgot Password option.";
                }


                if (Id > 0)
                {
                    userMaster                    = facade.GetDetailById(Id);
                    userMaster.UserType           = UserType.GURUDWARA;
                    userMaster.IPAddress          = Request.ServerVariables["REMOTE_ADDR"].ToString();
                    userMaster.BrowserInformation = Request.ServerVariables["HTTP_USER_AGENT"].ToString();

                    Session.Timeout = 60;

                    Session[Session["APP_PREFIX"] + "_SessionId"]           = Session.SessionID;
                    Session[Session["APP_PREFIX"] + "_USER_MASTER_SESSION"] = userMaster;

                    //Check for Extra Security Checks
                    if (facade.isValidLoginDaysAndTime(userMaster))
                    {
                        if (userMaster.ExtraSecurityRequired)
                        {
                            CommonFacade facadeCommon     = new CommonFacade();
                            string       verificationCode = facadeCommon.CreateRandomCode(6, true);

                            facade.MailVerificationCode(userMaster, verificationCode, Server.MapPath("~/EmailTemplates/VerificationCode.htm"));

                            return(RedirectToAction("Security", "Home", new { Token = SaraiBooking.App_Start.Common.EncryptData("`VERIFICATION_CODE=" + verificationCode + "`RECORD_STATUS=VCSS") }));
                        }
                        else
                        {
                            userMaster.LoginHistoryId = facade.SaveLoginSessionHistory();

                            Session[Session["APP_PREFIX"] + "_USER_MASTER_SESSION"] = userMaster;

                            return(RedirectToAction("About", "AboutUs"));
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Session[Session["APP_PREFIX"] + "_SessionId"]           = null;
                Session[Session["APP_PREFIX"] + "_USER_MASTER_SESSION"] = null;

                ViewBag.CredentialError = ex.Message;
            }

            return(View(userMaster));
        }
Пример #26
0
 public void ChangeUserStatus(UserMaster usermaster)
 {
     _frapperDbContext.Entry(usermaster).State = EntityState.Modified;
 }
Пример #27
0
 /// <summary>
 /// Shows how to get the total number of records
 /// </summary>
 private void GetRecordCount()
 {
     // get the total number of records in the UserMaster table
     int totalRecordCount = UserMaster.GetRecordCount();
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        //string userRole =  objCommonClass.GetRolesForUser(Membership.GetUser().UserName.ToString());
        objCommonMIS.EmpId = Membership.GetUser().UserName;

        if (!Page.IsPostBack)
        {
            // Bind Year and month
            for (int i = DateTime.Now.Year; i >= DateTime.Now.Year - 2; i--)
            {
                Ddlyear.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
            for (int i = 1; i <= 12; i++)
            {
                ddlMonth.Items.Add(new ListItem(mfi.GetMonthName(i).ToString(), i.ToString()));
            }
            ddlMonth.Items.Insert(0, new ListItem("Select", "0"));

            taxableAmt = 0.00;
            if (!Roles.GetRolesForUser(objCommonMIS.EmpId).Any(x => (x.Contains("SC") || x.Contains("SC_SIMS"))))
            {
                objCommonMIS.BusinessLine_Sno = "2";
                objCommonMIS.GetUserRegionsMTS_MTO(ddlRegion);
                if (ddlRegion.Items.Count > 0)
                {
                    ddlRegion.SelectedIndex = 0;
                }
                //if (ddlRegion.Items.FindByValue("8").Value.Equals("8"))
                //{
                //    ListItem lstRegion = ddlRegion.Items.FindByValue("8");
                //    ddlRegion.Items.Remove(lstRegion);
                //}
                objCommonMIS.RegionSno = ddlRegion.SelectedValue;
                objCommonMIS.GetUserBranchs(ddlBranch);
                objCommonMIS.BranchSno = ddlBranch.SelectedValue;
                objCommonMIS.GetUserSCs(ddlSerContractor);

                if (ddlSerContractor.Items.Count == 2)
                {
                    ddlSerContractor.SelectedIndex = 1;
                }
                //ddlSerContractor.Visible = false;  // Added by Mukesh  as on 24 Jun 2015
                //lblASCShowHide.Visible = false;
                TrInvoiceHideShow.Visible       = false;
                chkServicetaxoption.Visible     = false;
                lblServiceChargesBracks.Visible = false;
                ShowHideInvoiceDate.Visible     = false;
            }
            else
            {
                UserMaster objUserMaster = new UserMaster();
                objUserMaster.BindUseronUserName(Membership.GetUser().UserName.ToString(), "SELECT_USER_BY_USRNAME");
                trRB.Visible = false;
                ddlSerContractor.Items.Clear();
                ddlSerContractor.Items.Add(new ListItem(objUserMaster.Name.ToString()));
                ddlSerContractor.SelectedIndex = 0;
                ddlSerContractor.Enabled       = false;
                ddlSerContractor.Visible       = true; // Added by Mukesh  as on 24 Jun 2015
                lblASCShowHide.Visible         = true;
                TrInvoiceHideShow.Visible      = true;
                //InvoiceDetails();
            }
            ddlMonth.SelectedIndex = 6;
            // imglogo.Visible = false;
        }
    }
Пример #29
0
 public int InsertUser(UserMaster userMaster)
 {
     return(userRepository.InsertUser(userMaster));
 }
Пример #30
0
        public HttpResponseMessage GetProfileDetails(UserVerification objUserVerification)
        {
            try
            {
                string mobileNumber = objUserVerification.MobileNumber;

                UserMaster objUserMaster  = new UserMaster();
                var        profileDetails = (from user in dbContext.UserInfo where user.MobileNumber == mobileNumber select user).FirstOrDefault();
                if (profileDetails != null)
                {
                    UserProfile objUserProfile = new UserProfile()
                    {
                        FirstName       = (!string.IsNullOrEmpty(profileDetails.RetailerName)) ? profileDetails.RetailerName : "",
                        LastName        = (!string.IsNullOrEmpty(profileDetails.RetailerLastName)) ? profileDetails.RetailerLastName : "",
                        EmailId         = (!string.IsNullOrEmpty(profileDetails.EmailId)) ? profileDetails.EmailId : "",
                        BirthDate       = (!string.IsNullOrEmpty(Convert.ToString(profileDetails.BirthDate))) ? (profileDetails.BirthDate.Value.ToString("dd.MM.yyyy")) : "",
                        MobileNumber    = (!string.IsNullOrEmpty(profileDetails.MobileNumber)) ? profileDetails.MobileNumber : "",
                        Address         = (!string.IsNullOrEmpty(profileDetails.Address)) ? profileDetails.Address : "",
                        StreetLine1     = (!string.IsNullOrEmpty(profileDetails.StreetLine1)) ? profileDetails.StreetLine1 : "",
                        StreetLine2     = (!string.IsNullOrEmpty(profileDetails.StreetLine2)) ? profileDetails.StreetLine2 : "",
                        Pincode         = (!string.IsNullOrEmpty(profileDetails.Pincode)) ? profileDetails.Pincode : "",
                        State           = (!string.IsNullOrEmpty(profileDetails.State)) ? profileDetails.State : "",
                        District        = (!string.IsNullOrEmpty(profileDetails.District)) ? profileDetails.District : "",
                        Taluka          = (!string.IsNullOrEmpty(profileDetails.Taluka)) ? profileDetails.Taluka : "",
                        Town            = (!string.IsNullOrEmpty(profileDetails.Town)) ? profileDetails.Town : "",
                        FirmName        = (!string.IsNullOrEmpty(profileDetails.Firm_Name)) ? profileDetails.Firm_Name : "",
                        GstNumber       = (!string.IsNullOrEmpty(profileDetails.GSTNumber)) ? profileDetails.GSTNumber : "",
                        PanNumber       = (!string.IsNullOrEmpty(profileDetails.PANNumber)) ? profileDetails.PANNumber : "",
                        LicenseNumber   = (!string.IsNullOrEmpty(profileDetails.LicenseNumber)) ? profileDetails.LicenseNumber : "",
                        LicenseValidity = (!string.IsNullOrEmpty(Convert.ToString(profileDetails.SeedLicenseValidity))) ? (profileDetails.SeedLicenseValidity.Value.ToString("dd.MM.yyyy")) : "",
                    };

                    if (!string.IsNullOrEmpty(objUserProfile.FirstName) && !string.IsNullOrEmpty(objUserProfile.LastName) &&
                        !string.IsNullOrEmpty(objUserProfile.EmailId) && !string.IsNullOrEmpty(Convert.ToString(objUserProfile.BirthDate)) &&
                        !string.IsNullOrEmpty(objUserProfile.MobileNumber) && !string.IsNullOrEmpty(objUserProfile.Address) &&
                        !string.IsNullOrEmpty(objUserProfile.StreetLine1) && !string.IsNullOrEmpty(objUserProfile.StreetLine2) &&
                        !string.IsNullOrEmpty(objUserProfile.Pincode) && !string.IsNullOrEmpty(objUserProfile.State) &&
                        !string.IsNullOrEmpty(objUserProfile.District) && !string.IsNullOrEmpty(objUserProfile.Taluka) &&
                        !string.IsNullOrEmpty(objUserProfile.Town) && !string.IsNullOrEmpty(objUserProfile.FirmName) &&
                        !string.IsNullOrEmpty(objUserProfile.GstNumber) && !string.IsNullOrEmpty(objUserProfile.PanNumber) &&
                        !string.IsNullOrEmpty(objUserProfile.LicenseNumber) && !string.IsNullOrEmpty(objUserProfile.LicenseValidity))
                    {
                        objUserProfile.IsProfileUpdate = true;
                    }
                    else
                    {
                        objUserProfile.IsProfileUpdate = false;
                    }
                    objUserMaster.User = objUserProfile;
                    return(Request.CreateResponse(HttpStatusCode.OK, objUserMaster));
                }
                objResponse.Message = "User Not found";
                return(Request.CreateResponse(HttpStatusCode.OK, objResponse));
            }
            catch (Exception ex)
            {
                Log.Info(Convert.ToString(ex.InnerException));
                Log.Info(ex.Message);
                objCommonClasses.InsertExceptionDetails(ex, "UserController", "GetProfileDetails");
                return(Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ex.Message));
            }
        }
Пример #31
0
        // In this method we will create default User roles and Admin user for login
        private void createRolesandUsers()
        {
            ApplicationDbContext context = new ApplicationDbContext();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));


            context.SafetyModels.Add(new SafetyModel()
            {
                Id           = 0,
                AdminLoginIp = "0.0.0.0",
                Email        = "*****@*****.**",
                MailPassword = "******"
            });
            context.SaveChanges();


            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

                RoleMaster rm = new RoleMaster();
                rm.Active = true;
                rm.Name   = role.Name;
                context.RoleMasters.Add(rm);
                context.SaveChanges();



                //Here we create a Admin super user who will maintain the website

                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string userPWD = "admin@123";

                var chkUser = UserManager.Create(user, userPWD);

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    UserMaster userMaster = new UserMaster();
                    userMaster.UserId = user.Id;
                    userMaster.Name   = user.UserName;
                    userMaster.RoleId = 1;
                    userMaster.Active = true;
                    context.UserMasters.Add(userMaster);
                    context.SaveChanges();


                    var result1 = UserManager.AddToRole(user.Id, "Admin");
                }


                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "A",
                    MenuURL          = "#",
                    MenuParentID     = 0,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "S",
                    MenuURL          = "#",
                    MenuParentID     = 0,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "R",
                    MenuURL          = "#",
                    MenuParentID     = 0,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "BS",
                    MenuURL          = "#",
                    MenuParentID     = 0,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "BT",
                    MenuURL          = "#",
                    MenuParentID     = 0,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Safty",
                    MenuURL          = "../SafetyModels/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Organization Structure",
                    MenuURL          = "../ArtWorks/getOrganisationStructure",
                    MenuParentID     = 3,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Menu",
                    MenuURL          = "../MenuInfoes/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Role",
                    MenuURL          = "../RoleMasters/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "User",
                    MenuURL          = "../UserMasters/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Role Mapping with User",
                    MenuURL          = "../RoleMenuMappings/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Report Setup",
                    MenuURL          = "../ReportSetups/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Department",
                    MenuURL          = "../Departments/Index",
                    MenuParentID     = 1,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Organograms",
                    MenuURL          = "../Organograms/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Show Chart",
                    MenuURL          = "../ShowChart/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Bank And Branches",
                    MenuURL          = "../BankAndBranches/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Active Percentages",
                    MenuURL          = "../ActivePercentages/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Type Of Bills",
                    MenuURL          = "../TypeOfBills/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Mature Periods",
                    MenuURL          = "../MaturePeriods/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Mail Receivers",
                    MenuURL          = "../MailReceivers/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Mature Infoes",
                    MenuURL          = "../MatureInfoes/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Transaction Infoes",
                    MenuURL          = "../TransactionInfoes/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Bank Cheque Advices",
                    MenuURL          = "../BankChequeAdvices/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Mature Bill Info Details",
                    MenuURL          = "../MatureBillInfoDetails/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();
                context.MenuInfoes.Add(new MenuInfo()
                {
                    Id               = 0,
                    MenuName         = "Mature Bill Receive Dates",
                    MenuURL          = "../MatureBillReceiveDates/Index",
                    MenuParentID     = 2,
                    MenuParentIDText = "",
                    Active           = true,
                    CanClose         = true,
                    CanCreate        = true,
                    CanDelete        = true,
                    CanEdit          = true,
                    CanView          = true
                });
                context.SaveChanges();

                context.Departments.Add(new Department()
                {
                    Id = 0, DepartmentName = "All"
                });
                context.Departments.Add(new Department()
                {
                    Id = 0, DepartmentName = "Sales"
                });
                context.Departments.Add(new Department()
                {
                    Id = 0, DepartmentName = "Administration"
                });
                context.Departments.Add(new Department()
                {
                    Id = 0, DepartmentName = "Accounts"
                });

                context.SaveChanges();

                string sqlToBeInserted = @" INSERT INTO [dbo].[RoleMenuMappings]
           ([RoleId]
           ,[RoleIdText]
           ,[MenuInfoId]
           ,[MenuInfoIdText]
           ,[CanView]
           ,[CanCreate]
           ,[CanEdit]
           ,[CanDelete]
           ,[CanClose]
           ,[Active])
            select RoleName.Id , RoleName.Name , MInfo.Id , MInfo.MenuName , MInfo.CanView  ,
	        MInfo.CanCreate , MInfo.CanEdit , MInfo.CanDelete , MInfo.CanClose , MInfo.Active from(
            select id, Name from dbo.RoleMasters where Name = 'Admin') RoleName Cross join
            dbo.MenuInfoes MInfo;";

                context.Database.ExecuteSqlCommand(sqlToBeInserted);
            }

            context.SaveChanges();



            //// creating Creating Manager role
            //if (!roleManager.RoleExists("Manager"))
            //{
            //    var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            //    role.Name = "Manager";
            //    roleManager.Create(role);

            //    RoleMaster rm = new RoleMaster();
            //    rm.Active = true;
            //    rm.Name = role.Name;
            //    context.RoleMasters.Add(rm);
            //    context.SaveChanges();

            //}

            //// creating Creating Employee role
            //if (!roleManager.RoleExists("Employee"))
            //{
            //    var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            //    role.Name = "Employee";
            //    roleManager.Create(role);

            //    RoleMaster rm = new RoleMaster();
            //    rm.Active = true;
            //    rm.Name = role.Name;
            //    context.RoleMasters.Add(rm);
            //    context.SaveChanges();

            //}
        }
Пример #32
0
        public PharmaBusinessObjects.Master.UserMaster ValidateUser(string userName, string password)
        {
            using (PharmaDBEntities context = new PharmaDBEntities())
            {
                string query = "select * from users where Username = '******' AND password = '******' AND Status =1";

                SqlConnection connection = (SqlConnection)context.Database.Connection;

                SqlCommand cmd = new SqlCommand(query, connection);
                cmd.CommandType = System.Data.CommandType.Text;


                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable      dt  = new DataTable();

                sda.Fill(dt);


                if (dt != null && dt.Rows.Count > 0)
                {
                    PharmaBusinessObjects.Master.UserMaster obj = new UserMaster()
                    {
                        UserId    = Convert.ToInt32(dt.Rows[0]["UserId"]),
                        Username  = Convert.ToString(dt.Rows[0]["Username"]),
                        Password  = Convert.ToString(dt.Rows[0]["Password"]),
                        FirstName = Convert.ToString(dt.Rows[0]["FirstName"]),
                        LastName  = Convert.ToString(dt.Rows[0]["LastName"]),
                        //RoleID = Convert.ToInt32(dt.Rows[0]["RoleID"]),
                        //RoleName = Convert.ToString(dt.Rows[0]["RoleName"]),
                        IsSystemAdmin = Convert.ToBoolean(dt.Rows[0]["IsSysAdmin"])
                                        //CreatedBy = Convert.ToInt32(dt.Rows[0]["UserId"]),
                                        //CreatedOn = p.CreatedOn,
                                        //ModifiedBy = p.ModifiedBy,
                                        //ModifiedOn = p.ModifiedOn,
                                        //Status = p.Status
                    };

                    return(obj);
                }


                return(null);
            }

            //using (PharmaDBEntities context = new PharmaDBEntities())
            //{
            //    // return context.Users.Where(p => p.Username == userName && p.Password == password && p.Status == true).Any();
            //    return context.Users.Where(p => p.Username == userName && p.Password == password && p.Status == true).Select(p => new PharmaBusinessObjects.Master.UserMaster()
            //    {
            //        UserId = p.UserId,
            //        Username = p.Username,
            //        Password = p.Password,
            //        FirstName = p.FirstName,
            //        LastName = p.LastName,
            //        RoleID = p.RoleID ?? 0,
            //        RoleName = p.Roles.RoleName,
            //        IsSystemAdmin = p.IsSysAdmin,
            //        CreatedBy = p.CreatedBy,
            //        CreatedOn = p.CreatedOn,
            //        ModifiedBy = p.ModifiedBy,
            //        ModifiedOn = p.ModifiedOn,
            //        Status = p.Status
            //    }).FirstOrDefault();
            //}
        }