Beispiel #1
0
        public ActionResult CreateUpdate(tw_User data, HttpPostedFileBase file)
        {
            try
            {
                using (var dbConn = Helpers.OrmliteConnection.openConn())

                {
                    var exist = dbConn.SingleOrDefault <tw_User>("name={0}", currentUser.name);
                    data.imagesPublicId = exist.imagesPublicId;
                    data.imagesSize     = exist.imagesSize;
                    data.updatedAt      = DateTime.Now;
                    data.updatedBy      = currentUser.name;
                    if (file != null && file.ContentLength > 0)
                    {
                        string fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
                        if (fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".gif" || fileExtension == ".jpg")
                        {
                            string publicId = "CRM/User/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_" + file.FileName.Substring(0, file.FileName.Length - fileExtension.Length);
                            //data.imagesPublicId = publicId;
                            string LocalPath = "";
                            data.imagesPublicId = new AzureHelper().UploadImageToAzure(AllConstant.FoldderName_Merchant, file, currentUser.name, ref LocalPath);
                            // imagesSize = new Helpers.CloudinaryAPI().Upload(file, publicId);
                            //data.imagesSize = imagesSize;
                        }
                        else
                        {
                            return(Json(new { success = false, error = "Please select correct file type." }));
                        }
                    }
                    dbConn.UpdateOnly(data,
                                      onlyFields: p =>
                                      new
                    {
                        p.fullName,
                        p.phone,
                        p.address,
                        p.country,
                        p.city,
                        p.district,
                        p.birthday,
                        p.gender,
                        p.imagesPublicId,
                        p.imagesSize,
                        p.updatedAt,
                        p.updatedBy
                    },
                                      where : p => p.id == exist.id);
                }
                return(Json(new { success = true, data = data }));
            }
            catch (Exception e)
            {
                return(Json(new { success = false, error = e.Message }));
            }
        }
        public void RevertImage(tw_User item)
        {
            try
            {
                string imageUrl     = item.imagesSize != null ? item.imagesSize.face : (HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + "/Content/images/user.png");
                string saveLocation = Path.Combine(Server.MapPath("~/Content/Avatar4MobileApp/"), item.name + ".jpg");

                byte[]         imageBytes;
                HttpWebRequest imageRequest  = (HttpWebRequest)WebRequest.Create(imageUrl);
                WebResponse    imageResponse = imageRequest.GetResponse();

                Stream responseStream = imageResponse.GetResponseStream();

                using (BinaryReader br = new BinaryReader(responseStream))
                {
                    imageBytes = br.ReadBytes(500000);
                    br.Close();
                }
                responseStream.Close();
                imageResponse.Close();

                FileStream   fs = new FileStream(saveLocation, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                try
                {
                    bw.Write(imageBytes);
                }
                finally
                {
                    fs.Close();
                    bw.Close();
                }
            }
            catch (Exception)
            {
            }
        }
        public ActionResult CreateUpdate(tw_User data, HttpPostedFileBase file, string password)
        {
            try
            {
                using (var dbConn = MCC.Helpers.OrmliteConnection.openConn())

                {
                    if (data.id > 0)
                    {
                        if (accessDetail != null && (accessDetail.access["all"] || accessDetail.access["update"]))
                        {
                            var exist = dbConn.SingleOrDefault <tw_User>("id={0}", data.id);
                            data.imagesPublicId = exist.imagesPublicId;
                            data.imagesSize     = exist.imagesSize;

                            data.updatedAt = DateTime.Now;
                            data.updatedBy = currentUser.name;
                            if (file != null && file.ContentLength > 0)
                            {
                                string fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
                                if (fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".gif" || fileExtension == ".jpg")
                                {
                                    string publicId = "CRM/User/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_" + file.FileName.Substring(0, file.FileName.Length - fileExtension.Length);
                                    //data.imagesPublicId = publicId;
                                    //var imagesSize = new MCC.Helpers.CloudinaryAPI().Upload(file, publicId);
                                    //data.imagesSize = imagesSize;
                                    string LocalPath = "";
                                    data.imagesPublicId = new AzureHelper().UploadImageToAzure(AllConstant.FoldderName_User, file, currentUser.name, ref LocalPath);
                                }
                                else
                                {
                                    return(Json(new { success = false, error = "Please select correct file type." }));
                                }
                            }

                            RevertImage(data);

                            if (accessDetail != null && (accessDetail.access["all"] || accessDetail.access["update voip"]))
                            {
                                dbConn.UpdateOnly(data,
                                                  onlyFields: p =>
                                                  new
                                {
                                    p.extension
                                },
                                                  where : p => p.id == data.id);
                            }

                            dbConn.UpdateOnly(data,
                                              onlyFields: p =>
                                              new
                            {
                                p.homePage,
                                p.fullName,
                                p.phone,
                                p.address,
                                p.country,
                                p.city,
                                p.district,
                                p.birthday,
                                p.gender,
                                p.imagesPublicId,
                                p.imagesSize,
                                p.active,
                                p.updatedAt,
                                p.updatedBy,
                                p.email
                            },
                                              where : p => p.id == data.id);
                        }
                        else
                        {
                            return(Json(new { success = false, error = "Don't have permission to update" }));
                        }
                    }
                    else
                    {
                        if (accessDetail != null && (accessDetail.access["all"] || accessDetail.access["create"]))
                        {
                            if (!String.IsNullOrEmpty(password))
                            {
                                var exist = dbConn.SingleOrDefault <tw_User>("email={0}", data.email);
                                if (exist == null)
                                {
                                    var user = new ApplicationUser()
                                    {
                                        UserName = Helpers.RemoveVietNameChar.Remove(data.name), PhoneNumber = data.phone, Email = data.email
                                    };
                                    var result = UserManager.Create(user, password);
                                    if (result.Succeeded)
                                    {
                                        data.userKey      = user.Id;
                                        data.registerAt   = DateTime.Now;
                                        data.createdAt    = DateTime.Now;
                                        data.createdBy    = currentUser.name;
                                        data.email        = currentUser.email;
                                        data.ma_gian_hang = currentUser.ma_gian_hang;

                                        data.lastLoginTime = data.updatedAt = DateTime.Parse("01-01-1990");
                                        ///
                                        dbConn.Insert(data);
                                        int Id = (int)dbConn.GetLastInsertId();
                                        data.id = Id;
                                        if (file != null && file.ContentLength > 0)
                                        {
                                            string fileExtension = System.IO.Path.GetExtension(file.FileName).ToLower();
                                            if (fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".gif" || fileExtension == ".jpg")
                                            {
                                                string publicId  = "CRM/User/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "_" + file.FileName.Substring(0, file.FileName.Length - fileExtension.Length);
                                                string LocalPath = "";
                                                data.imagesPublicId = new AzureHelper().UploadImageToAzure(AllConstant.FoldderName_Merchant, file, currentUser.name, ref LocalPath);
                                                //var imagesSize = new Helpers.CloudinaryAPI().Upload(file, publicId);
                                                //data.imagesSize = imagesSize;

                                                dbConn.Update(data);
                                            }
                                            else
                                            {
                                                return(Json(new { success = false, error = "Please select correct file type." }));
                                            }
                                        }

                                        RevertImage(data);
                                    }
                                    else
                                    {
                                        return(Json(new { success = false, error = AddErrors(result) }));
                                    }
                                }
                                else
                                {
                                    return(Json(new { success = false, error = "Email is existed" }));
                                }
                            }
                            else
                            {
                                return(Json(new { success = false, error = "Please input password" }));
                            }
                        }
                        else
                        {
                            return(Json(new { success = false, error = "Don't have permission to create" }));
                        }
                    }

                    if (data.groups != null && data.groups.Count > 0)
                    {
                        foreach (var item in data.groups)
                        {
                            var exist = dbConn.SingleOrDefault <tw_UserInGroup>("userId={0} AND groupId={1}", data.id, item);
                            if (exist == null)
                            {
                                var userInGroup = new tw_UserInGroup();
                                userInGroup.userId    = data.id;
                                userInGroup.groupId   = item;
                                userInGroup.createdAt = DateTime.Now;
                                userInGroup.createdBy = currentUser.name;
                                dbConn.Insert(userInGroup);
                            }
                        }
                        dbConn.Delete <tw_UserInGroup>("userId = {0} AND groupId NOT IN (" + String.Join(",", data.groups.Select(s => s)) + ")", data.id);
                    }
                    else
                    {
                        var userInGroup = new tw_UserInGroup();
                        userInGroup.userId = data.id;
                        long idGroup = dbConn.QueryScalar <long>("select id from tw_UserGroup where name = N'Merchant'");
                        userInGroup.groupId   = idGroup;
                        userInGroup.createdAt = DateTime.Now;
                        userInGroup.createdBy = currentUser.name;

                        //var exist = dbConn.SingleOrDefault<tw_UserInGroup>("userId={0} AND groupId={1}", currentUser.id, 3);
                        //if (exist!=null)
                        //{
                        //        userInGroup.groupId = 4;
                        //}
                        dbConn.Insert(userInGroup);
                    }

                    //if (data.showrooms != null && data.showrooms.Count > 0)
                    //{
                    //    foreach (var item in data.showrooms)
                    //    {
                    //        var exist = dbConn.SingleOrDefault<tw_UserInShowroom>("userId={0} AND showroomId={1}", data.id, item);
                    //        if (exist == null)
                    //        {
                    //            var userInShowroom = new tw_UserInShowroom();
                    //            userInShowroom.userId = data.id;
                    //            userInShowroom.showroomId = item;
                    //            userInShowroom.createdAt = DateTime.Now;
                    //            userInShowroom.createdBy = currentUser.name;
                    //            dbConn.Insert(userInShowroom);
                    //        }
                    //    }
                    //    dbConn.Delete<tw_UserInShowroom>("userId = {0} AND showroomId NOT IN (" + String.Join(",", data.showrooms.Select(s => s)) + ")", data.id);
                    //}
                }
                return(Json(new { success = true, data = data }));
            }
            catch (Exception e)
            {
                return(Json(new { success = false, error = e.Message }));
            }
        }
Beispiel #4
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }

                using (var dbConn = Helpers.OrmliteConnection.openConn())
                {
                    var exist = dbConn.SingleOrDefault <tw_User>("email={0}", model.Email);
                    if (exist == null)
                    {
                        var user = new ApplicationUser()
                        {
                            UserName = Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower(), PhoneNumber = model.PhoneNumber, Email = model.Email
                        };
                        var result = await UserManager.CreateAsync(user);

                        if (result.Succeeded)
                        {
                            var newUser = new tw_User();
                            newUser.name       = Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower();
                            newUser.email      = model.Email;
                            newUser.phone      = model.PhoneNumber;
                            newUser.fullName   = model.FullName;
                            newUser.registerAt = DateTime.Now;
                            newUser.active     = true;
                            newUser.vendorAuth = info.Login.LoginProvider;
                            newUser.userKey    = user.Id;
                            newUser.createdAt  = DateTime.Now;
                            newUser.createdBy  = "administrator";
                            dbConn.Insert(newUser);

                            Int64 userId = (Int64)dbConn.GetLastInsertId();

                            var groupId = dbConn.Scalar <Int64>("select id from tw_UserGroup where name = 'guest'");
                            if (groupId > 0)
                            {
                                var userInGroup = new tw_UserInGroup();
                                userInGroup.userId    = userId;
                                userInGroup.groupId   = groupId;
                                userInGroup.createdAt = DateTime.Now;
                                userInGroup.createdBy = "administrator";
                                dbConn.Insert(userInGroup);
                            }

                            result = await UserManager.AddLoginAsync(user.Id, info.Login);

                            if (result.Succeeded)
                            {
                                string body = string.Empty;
                                using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplate/newUserTemplate.html")))
                                {
                                    body = reader.ReadToEnd();
                                }
                                body = body.Replace("{username}", Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower());
                                body = body.Replace("{fullname}", model.FullName);
                                body = body.Replace("{phone}", model.PhoneNumber);
                                body = body.Replace("{email}", model.Email);

                                BackgroundJob.Enqueue(
                                    () => new Helpers.SendMail().Send(model.Email, "", "Xin hoàn thành thủ tục đăng ký trên Thietbinhanh.com!", body, ""));

                                await SignInAsync(user, isPersistent : false);

                                return(RedirectToLocal(returnUrl));
                            }
                        }

                        AddErrors(result);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Email is existed");
                    }
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Beispiel #5
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var dbConn = Helpers.OrmliteConnection.openConn())
                {
                    int count         = 0;
                    var existEmail    = dbConn.SingleOrDefault <tw_User>("email={0}", model.Email);
                    var existShopName = dbConn.SingleOrDefault <Merchant_Info>("ten_gian_hang={0}", model.ten_gian_hang);
                    var existUrl      = dbConn.SingleOrDefault <Merchant_Info>("website={0}", model.website);
                    if (existEmail != null)
                    {
                        ModelState.AddModelError("", Resources.Global._email_exited);
                        count++;
                    }
                    if (existShopName != null)
                    {
                        ModelState.AddModelError("", Resources.Global._shop_name_exsited);
                        count++;
                    }
                    if (existUrl != null)
                    {
                        ModelState.AddModelError("", Resources.Global._url_is_exsited);
                        count++;
                    }
                    if (count == 0)
                    {
                        var user = new ApplicationUser()
                        {
                            UserName = model.UserName, PhoneNumber = model.PhoneNumber, Email = model.Email
                        };
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            // ADD USER
                            var newUser = new tw_User();
                            newUser.name       = model.UserName;
                            newUser.email      = model.Email;
                            newUser.phone      = model.PhoneNumber;
                            newUser.fullName   = model.FullName;
                            newUser.registerAt = DateTime.Now;
                            newUser.homePage   = "Home";
                            newUser.active     = false;
                            newUser.vendorAuth = "";
                            newUser.userKey    = user.Id;
                            //newUser.ma_gian_hang= dbConn.QueryScalar<string>("select MAX(ma_gian_hang) from Merchant_Info");
                            newUser.createdAt = DateTime.Now;
                            newUser.createdBy = "system";
                            dbConn.Insert(newUser);

                            // ADD MERCHANT_INFO
                            Merchant_Info merchantinfo = new Merchant_Info();
                            merchantinfo.ten_gian_hang = model.ten_gian_hang;
                            merchantinfo.website       = model.website;
                            //List<Merchant_Info> lstMerchant = new List<Merchant_Info>();
                            //lstMerchant.Add(merchantinfo);
                            Merchant_Info_DAO merchantDao = new Merchant_Info_DAO();
                            merchantDao.CreateMerchant(merchantinfo, model.UserName, AppConfigs.MCCConnectionString);



                            // ADD USERGROUP
                            Int64 userId  = (Int64)dbConn.GetLastInsertId();
                            var   groupId = dbConn.Scalar <Int64>("select id from tw_UserGroup where name = 'MerchantAdmin'");
                            if (groupId > 0)
                            {
                                var userInGroup = new tw_UserInGroup();
                                userInGroup.userId    = userId;
                                userInGroup.groupId   = groupId;
                                userInGroup.createdAt = DateTime.Now;
                                userInGroup.createdBy = "system";
                                dbConn.Insert(userInGroup);
                            }

                            // ADD USERACTIVATION
                            string         code      = Guid.NewGuid().ToString();;
                            UserActivation userActiv = new UserActivation();
                            userActiv.UserName       = model.UserName;
                            userActiv.Email          = model.Email;
                            userActiv.MerchantName   = model.ten_gian_hang;
                            userActiv.FullName       = model.FullName;
                            userActiv.Phone          = model.PhoneNumber;
                            userActiv.ActivationCode = code;
                            userActiv.Date           = DateTime.Now;
                            userActiv.DeadTime       = DateTime.Now.AddDays(3);// sau 3 ngay link active vo hieu luc
                            userActiv.ngay_tao       = DateTime.Now;
                            userActiv.nguoi_tao      = "system";
                            userActiv.ngay_cap_nhat  = DateTime.Now;
                            userActiv.nguoi_cap_nhat = "system";
                            dbConn.Insert(userActiv);

                            //SEND MAIL
                            string body = string.Empty;
                            using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplate/newUserTemplate.html")))
                            {
                                body = reader.ReadToEnd();
                            }
                            body = body.Replace("{username}", model.UserName);
                            body = body.Replace("{fullname}", model.FullName);
                            body = body.Replace("{phone}", model.PhoneNumber);
                            body = body.Replace("{email}", model.Email);

                            //xác thực bằng web
                            body = body.Replace("{activation}", AppConfigs.Url + "/Account/Activation?key=" + code + "&email=" + model.Email + "&username="******"&ten_gian_hang=" + model.ten_gian_hang);
                            //xác thực thông qua API
                            //body = body.Replace("{activation}", AllConstant.UrlAPI + "api/ActivationAccount/Activation?key=" + code + "&email=" + model.Email + "&username="******"&ten_gian_hang=" + model.ten_gian_hang);
                            BackgroundJob.Enqueue(() => new Helpers.SendMail().Send(model.Email, "", "Xin hoàn thành thủ tục đăng ký trên Thietbinhanh.com!", body, ""));
                            // new Helpers.SendMail().Send(model.Email, "", "Xin hoàn thành thủ tục đăng ký trên Thietbinhanh.com!", body, "");
                            //await SignInAsync(user, isPersistent: false);
                            return(View("~/Views/Account/Success.cshtml"));
                        }
                        else
                        {
                            AddErrors(result);
                        }
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #6
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (User.Identity.IsAuthenticated)
            {
                using (var dbConn = Helpers.OrmliteConnection.openConn())
                {
                    currentUser = dbConn.FirstOrDefault <tw_User>("name={0}", User.Identity.Name);
                    if (currentUser != null)
                    {
                        if (!currentUser.active)
                        {
                            AuthenticationManager.SignOut();
                        }

                        isAdmin = dbConn.Scalar <bool>("select top 1 1 from tw_UserInGroup WHERE userId = " + currentUser.id + " and groupId = 1");

                        var controller = this.GetType().Name.Substring(0, this.GetType().Name.IndexOf("Controller"));
                        if (controller != "CustomData")
                        {
                            var listAccess = currentUser.listAccess.Where(s => s.controllerName == controller);
                            var access     = new Dictionary <string, bool>();
                            if (listAccess.Count() > 0)
                            {
                                foreach (var item in listAccess.FirstOrDefault().access.Select(s => s.Key))
                                {
                                    access.Add(item, listAccess.Where(s => s.access.ContainsKey(item) && s.access[item] == true).Count() > 0 ? true : false);
                                }
                            }

                            accessDetail = currentUser.listAccess.Where(s => s.controllerName == controller).FirstOrDefault();
                            if (accessDetail != null)
                            {
                                accessDetail.access = access;
                            }
                        }


                        ViewData["menuView"] = currentUser.listAccess.Where(s => s.access != null && ((s.access.ContainsKey("all") && s.access["all"]) || (s.access.ContainsKey("view") && s.access["view"]))).Select(s => s.controllerName).ToList();
                        ViewBag.accessDetail = accessDetail;
                        string image = String.Empty;
                        if (currentUser.imagesPublicId != null)
                        {
                            image = currentUser.imagesPublicId;
                        }
                        else if (currentUser.gender == null || currentUser.gender == "unknown")
                        {
                            image = Url.Content("~/Content/images/unknown.png");
                        }
                        else
                        {
                            image = currentUser.gender == "male" ? Url.Content("~/Content/images/male.png") : Url.Content("~/Content/images/female.png");
                        }
                        ViewBag.userImage      = image;
                        ViewData["userId"]     = currentUser.id.ToString();
                        ViewBag.magh           = currentUser.ma_gian_hang;
                        ViewBag.accountfb      = AppConfigs.ReadConfig("AccountFB");
                        ViewBag.controllerName = controller;
                    }
                }
            }
        }