Beispiel #1
0
        public void createStoreAndOwnerMannegerFromeManegerWioutPremition()
        {
            User aviad = new User("aviad", "123456");

            aviad.register("aviad", "123456");
            User zahi = new User("zahi", "123456");

            zahi.register("zahi", "123456");
            User niv = new User("niv", "123456");

            niv.register("niv", "123456");
            aviad.login("aviad", "123456");
            int   storeId = aviad.createStore("bro burger");
            Store s       = StoreManagement.getInstance().getStore(storeId);

            Assert.AreEqual(s.getStoreName(), "bro burger");
            Assert.AreEqual(s.getOwners().Count, 1);
            StoreRole sr = new StoreOwner(aviad, s);

            sr.addStoreManager(aviad, s, "niv");
            Assert.AreEqual(s.getManagers().Count, 1);
            sr.addManagerPermission(aviad, "removeStoreManager", s, "niv");
            niv.login("niv", "123456");
            sr.addStoreManager(niv, s, "zahi");
            Assert.AreEqual(s.getManagers().Count, 2);
        }
Beispiel #2
0
        private string GenerateAuthenticationTokenForStoreOwner(StoreOwner storeOwner)
        {
            var claims = new[]
            {
                new Claim("FirstName", storeOwner.FirstName),
                new Claim("LastName", storeOwner.LastName),
                new Claim("Email", storeOwner.EmailAddress),
                new Claim("PhoneNumber", storeOwner.PhoneNumber),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.Secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                _jwtSettings.Issuer,
                _jwtSettings.Issuer,
                claims,
                expires: DateTime.UtcNow.AddMinutes(10),
                notBefore: DateTime.UtcNow,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Beispiel #3
0
        public void createStoreAndOwnerMannegerNotOwner()
        {
            User aviad = new User("aviad", "123456");

            aviad.register("aviad", "123456");
            User zahi = new User("zahi", "123456");

            zahi.register("zahi", "123456");
            User niv = new User("niv", "123456");

            niv.register("niv", "123456");
            aviad.login("aviad", "123456");
            zahi.login("zahi", "123456");
            int   storeId = aviad.createStore("bro burger");
            Store s       = StoreManagement.getInstance().getStore(storeId);

            Assert.AreEqual(s.getStoreName(), "bro burger");
            Assert.AreEqual(s.getOwners().Count, 1);
            StoreRole sr = new StoreOwner(aviad, s);

            sr.addStoreOwner(zahi, s, "niv");
            Assert.AreEqual(s.getOwners().Count, 2);
            sr.addStoreManager(zahi, s, "niv");
            Assert.AreEqual(s.getManagers().Count, 0);
        }
Beispiel #4
0
        public void RemoveStoreOwnerHimself()
        {
            zahiOwner.addStoreOwner(zahi, store, "shay");
            StoreRole shayOwner = new StoreOwner(shay, store);

            Assert.IsFalse(shayOwner.removeStoreOwner(shay, store, "shay") > -1);
            Assert.AreEqual(store.getOwners().Count, 2);
        }
Beispiel #5
0
 /// <summary>
 /// Создет элемент записи хранилища.
 /// </summary>
 /// <param name="id">Строковый идентификатор элемента в базе данных.</param>
 /// <param name="saved">Дата сохраненной информации в базу данных.</param>
 public StorageItemInfo(StoreOwner owner, StoreType type, string id, DateTime?saved, bool?isSuccessful, XElement xContent)
 {
     this.Owner        = owner;
     this.Type         = type;
     this.ID           = id;
     this.Saved        = saved;
     this.IsSuccessful = isSuccessful;
     this.XContent     = xContent;
 }
Beispiel #6
0
        public void RemoveStoreOwnerTwice()
        {
            zahiOwner.addStoreOwner(zahi, store, "shay");
            StoreRole shayOwner = new StoreOwner(shay, store);

            zahiOwner.addStoreOwner(zahi, store, "aviad");
            Assert.AreEqual(store.getOwners().Count, 3);
            Assert.IsTrue(shayOwner.removeStoreOwner(zahi, store, "aviad") > -1);
            Assert.AreEqual(store.getOwners().Count, 2);
        }
Beispiel #7
0
        private bool AddEntry(String userType, JObject userInformation)
        {
            Boolean save = false;

            if (userType.Equals(UserContract.TABLE_ADMIN) || userType.Equals(UserContract.TABLE_NORMAL_USER) || userType.Equals(UserContract.TABLE_STORE_OWNER))
            {
                using (var store = new onlineStorePlatformEntities())
                {
                    User userEntry = new User();
                    userEntry.Serialize(userInformation);
                    userEntry.role = userType;
                    store.Users.Add(userEntry);

                    if (userType.Equals(UserContract.TABLE_NORMAL_USER))
                    {
                        NormalUser normalUserEntry = new NormalUser();
                        normalUserEntry.Serialize(userInformation);

                        store.NormalUsers.Add(normalUserEntry);
                        save = true;
                    }
                    else if (userType.Equals(UserContract.TABLE_STORE_OWNER))
                    {
                        StoreOwner storeOwnerEntry = new StoreOwner();
                        storeOwnerEntry.Serialize(userInformation);
                        store.StoreOwners.Add(storeOwnerEntry);
                        save = true;
                    }
                    else if (userType.Equals(UserContract.TABLE_ADMIN) && User.IsInRole(UserContract.TABLE_ADMIN))
                    {
                        Admin adminEntry = new Admin();
                        adminEntry.Serialize(userInformation);
                        store.Admins.Add(adminEntry);
                        save = true;
                    }
                    try
                    {
                        if (save)
                        {
                            store.SaveChanges();
                            return(true);
                        }
                    }
                    catch (DbUpdateException)
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Beispiel #8
0
        /// <summary>
        /// Получает отрибут перечисления владельца данных StoreOwner.
        /// </summary>
        /// <param name="owner">Владелец данных.</param>
        /// <returns></returns>
        private static OwnerAttribute GetStoreOwnerTextAttribute(StoreOwner owner)
        {
            // Получение текстового атрибута.
            OwnerAttribute[] attributes = typeof(StoreOwner).GetField(owner.ToString())
                                          .GetCustomAttributes(typeof(OwnerAttribute), false)
                                          .Where(o => o is OwnerAttribute)
                                          .Select(t => (OwnerAttribute)t).ToArray();

            if (attributes.Length == 1)
            {
                return(attributes[0]);
            }

            return(null);
        }
Beispiel #9
0
        public void UserAddProductAndViewItNotExist()
        {
            User aviad = new User("aviad", "123456");

            aviad.register("aviad", "123456");
            aviad.login("aviad", "123456");
            int            storeId = aviad.createStore("bro burger");
            Store          s       = StoreManagement.getInstance().getStore(storeId);
            StoreRole      sr      = new StoreOwner(aviad, s);
            int            pisId   = sr.addProductInStore(aviad, s, "cola", -5, 10, "Driks");
            ProductInStore pis     = ProductManager.getInstance().getProductInStore(pisId);
            LinkedList <ProductInStore> pisList = s.getProductsInStore();

            Assert.IsFalse(pisList.Contains(pis));
            Assert.AreEqual(pisList.Count, 0);
        }
Beispiel #10
0
        public void UserAddProductAndViewItFewProducts()
        {
            User aviad = new User("aviad", "123456");

            aviad.register("aviad", "123456");
            aviad.login("aviad", "123456");
            int       storeId = aviad.createStore("bro burger");
            Store     s       = StoreManagement.getInstance().getStore(storeId);
            StoreRole sr      = new StoreOwner(aviad, s);
            int       pisId   = sr.addProductInStore(aviad, s, "cola", 3.2, 10, "Driks");

            sr.addProductInStore(aviad, s, "sprite", 3.2, 10, "Driks");
            LinkedList <ProductInStore> pisList = s.getProductsInStore();

            Assert.AreEqual(pisList.Count, 2);
        }
Beispiel #11
0
        public void BuyHistoryStoreViewByAdmin()
        {
            niv.login("niv", "123456");
            StoreOwner        itamarOwner = new StoreOwner(itamar, store);
            int               colaId      = itamarOwner.addProductInStore(itamar, store, "cola", 3.2, 10, "Drinks");
            ProductInStore    cola        = ProductManager.getInstance().getProductInStore(colaId);
            int               saleId      = itamarOwner.addSaleToStore(itamar, store, cola.getProductInStoreId(), 1, 5, DateTime.Now.AddMonths(1).ToString());
            LinkedList <Sale> sales       = User.viewSalesByProductInStoreId(cola.getProductInStoreId());

            Assert.IsTrue(sales.Count == 1);
            Sale sale = sales.First.Value;

            niv.login("niv", "123456");
            Assert.IsTrue(niv.addToCart(sale.SaleId, 1) > -1);
            LinkedList <UserCart> sc = niv.getShoppingCart();

            Assert.IsTrue(sc.Count == 1);
            Assert.IsTrue(sc.First.Value.getSaleId() == saleId);
            Assert.IsTrue(niv.buyProducts("1234", ""));
            Assert.AreEqual(admin.viewStoreHistory(store).Count, 1);
        }
Beispiel #12
0
        public async Task <AuthenticationResponse> FacebookLoginStoreOwnerAsync(string accessToken)
        {
            if (string.IsNullOrWhiteSpace(accessToken))
            {
                return new AuthenticationResponse {
                           Errors = new[] { "AccessToken cannot be empty." }
                }
            }
            ;

            var validateTokenResult = await _facebookAuthService.ValidateAccessTokenAsync(accessToken);

            if (validateTokenResult.Data != null)
            {
                if (!validateTokenResult.Data.IsValid)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Invalid Facebook Token." }
                    }
                }
                ;

                var fbUserInfo = await _facebookAuthService.GetUserInfoAsync(accessToken);

                if (fbUserInfo.Id == "Failed")
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Failed to Get Facebook User. " }
                    }
                }
                ;

                var storeOwnerExist = await _dataContext.StoreOwners.FirstOrDefaultAsync(s => s.EmailAddress == fbUserInfo.Email);

                if (storeOwnerExist == null) //Register StoreOwner
                {
                    var newStoreOwner = new StoreOwner()
                    {
                        EmailAddress         = fbUserInfo.Email,
                        FirstName            = fbUserInfo.FirstName,
                        MiddleName           = fbUserInfo.MiddleName,
                        LastName             = fbUserInfo.LastName,
                        PhoneNumber          = string.Empty,
                        ProfilePicUrl        = fbUserInfo.Picture.FacebookPictureData.Url.ToString(),
                        IsVerified           = true,
                        DateRegistered       = DateTime.Now,
                        IsFacebookRegistered = true
                    };

                    await _dataContext.StoreOwners.AddAsync(newStoreOwner);

                    var created = await _dataContext.SaveChangesAsync();

                    if (created <= 0)
                    {
                        return new AuthenticationResponse {
                                   Errors = new[] { "Failed to create customer" }
                        }
                    }
                    ;

                    var token = GenerateAuthenticationTokenForStoreOwner(newStoreOwner);
                    return(new AuthenticationResponse {
                        Success = true, Token = token
                    });
                }
                else //Signin StoreOwner
                {
                    storeOwnerExist.LastLoginDate             = DateTime.Now;
                    _dataContext.Entry(storeOwnerExist).State = EntityState.Modified;
                    var updated = await _dataContext.SaveChangesAsync();

                    if (updated <= 0)
                    {
                        return new AuthenticationResponse {
                                   Errors = new[] { "Failed to signin." }
                        }
                    }
                    ;

                    var token = GenerateAuthenticationTokenForStoreOwner(storeOwnerExist);
                    return(new AuthenticationResponse {
                        Success = true, Token = token
                    });
                }
            }
            else
            {
                return(new AuthenticationResponse {
                    Errors = new[] { "Failed to Validate Facebook." }
                });
            }
        }
Beispiel #13
0
        public Tuple <bool, string> ApproveAppoitment(string owner, string Appointed, int storeID, bool approval)
        {
            Logger.logEvent(this, System.Reflection.MethodBase.GetCurrentMethod());
            if (owner == null || Appointed == null)
            {
                Logger.logError(CommonStr.ArgsTypes.None, this, System.Reflection.MethodBase.GetCurrentMethod());
                return(new Tuple <bool, string>(false, "Null Arguments"));
            }

            if (owner == "" || Appointed == "")
            {
                Logger.logError(CommonStr.ArgsTypes.Empty, this, System.Reflection.MethodBase.GetCurrentMethod());
                return(new Tuple <bool, string>(false, "Blank Arguemtns\n"));
            }
            Store store = storeManagment.getStore(storeID);

            if (store is null)
            {
                return(new Tuple <bool, string>(false, "Store Does not Exist"));
            }
            User appointer = UM.GetAtiveUser(owner);
            User appointed = UM.GetUser(Appointed);

            if (appointer is null || appointed is null)
            {
                return(new Tuple <bool, string>(false, "One of the users is not logged Exist\n"));
            }
            if (appointer.isguest() || appointed.isguest())
            {
                return(new Tuple <bool, string>(false, "One of the users is a Guest\n"));
            }
            //Remove this approvalRequest
            if (appointer.INeedToApproveRemove(storeID, Appointed))
            {
                //Remove The Pending for the user
                if (appointed.RemoveOtherApprovalRequest(storeID, owner))
                {
                    //Remove Need to Approve From DB
                    try
                    {
                        NeedToApprove ndap = DbManager.Instance.GetNeedToApprove(owner, Appointed, storeID);
                        DbManager.Instance.DeleteSingleApproval(ndap);
                    }
                    catch (Exception ex)
                    {
                        Logger.logError("DeleteSingleApproval error : " + ex.Message, this, System.Reflection.MethodBase.GetCurrentMethod());
                        return(new Tuple <bool, string>(false, "Delete Operation from DB Failed cannot proceed"));
                    }
                }
            }
            //Set to false if False and the operation will fail.
            if (!approval)
            {
                RemoveCnadidate(owner, Appointed, storeID);
                appointed.SetApprovalStatus(storeID, approval);
                //Update The Approval Status in the DB
                //Remove MasterAppointer - Candidtae Table from DB
                string masterNmae = appointed.MasterAppointer[storeID];
                appointed.RemoveMasterAppointer(storeID);
                try
                {
                    StoreOwnertshipApprovalStatus status = DbManager.Instance.getApprovalStat(Appointed, storeID);
                    CandidateToOwnership          cand   = DbManager.Instance.GetCandidateToOwnership(Appointed, masterNmae, storeID);
                    Publisher.Instance.Notify(Appointed, new NotifyData("Your request to be an Owner to Store - " + storeID + " Didn't Approved"));
                    DbManager.Instance.DeApprovalTransaction(status, approval, cand, true);
                    //DbManager.Instance.DeleteSingleCandidate(cand);
                    //DbManager.Instance.UpdateApprovalStatus(status, approval);
                }
                catch (Exception ex)
                {
                    Logger.logError("De-Approval db error : " + ex.Message, this, System.Reflection.MethodBase.GetCurrentMethod());
                    return(new Tuple <bool, string>(false, "De-Approval Operation from DB Failed cannot proceed"));
                }
                return(new Tuple <bool, string>(true, "User failed to become an owner"));
            }
            if (appointed.CheckSApprovalStatus(storeID))
            {
                RemoveCnadidate(owner, Appointed, storeID);
                //User can be assigned to Store owner
                appointed.RemoveApprovalStatus(storeID);
                string Mappointer = appointed.MasterAppointer[storeID];
                //Add Store Ownership in store Liav is incharge of this
                if (!appointed.addStoreOwnership(storeID, Mappointer).Item1)
                {
                    StoreOwner so = DbManager.Instance.getStoreOwnerbyStore(appointed.getUserName(), store.Id);
                    DbManager.Instance.DeleteStoreOwner(so, true);
                    return(new Tuple <bool, string>(false, "Failed to insert store owner to DB memory"));
                }
                appointed.AppointerMasterAppointer(storeID);
                if (!store.AddStoreOwner(appointed))
                {
                    return(new Tuple <bool, string>(false, "Failed to insert store owner to DB memory"));
                }
                insertAppointment(owner, Appointed, storeID);
                if (store.IsStoreManager(appointed))
                {
                    try
                    {
                        StoreManagersAppoint Sma = DbManager.Instance.GetSingleManagerAppoints(appointed.Store_Managment[storeID], appointed.Name, storeID);
                        DbManager.Instance.DeleteSingleManager(Sma);
                    }
                    catch (Exception ex)
                    {
                        Logger.logError("Remove Store Manager db error : " + ex.Message, this, System.Reflection.MethodBase.GetCurrentMethod());
                        return(new Tuple <bool, string>(false, "Could not Remove Manager store from  DB"));
                    }
                    store.RemoveManager(appointed);
                    appointed.RemoveStoreManagment(storeID);
                }
                Publisher.Instance.Notify(Appointed, new NotifyData("Your request to be an Owner to Store - " + storeID + " is Approved"));
                Tuple <bool, string> ans = Publisher.Instance.subscribe(Appointed, storeID);
                try
                {
                    CandidateToOwnership cand = DbManager.Instance.GetCandidateToOwnership(Appointed, Mappointer, storeID);
                    DbManager.Instance.DeleteSingleCandidate(cand);
                    //Delete Approval Status from DB
                    StoreOwnertshipApprovalStatus status = DbManager.Instance.getApprovalStat(Appointed, storeID);
                    DbManager.Instance.DeleteSingleApprovalStatus(status);
                    DbManager.Instance.SaveChanges();
                }
                catch (Exception ex)
                {
                    Logger.logError("Inser Store Owner db error : " + ex.Message, this, System.Reflection.MethodBase.GetCurrentMethod());
                    return(new Tuple <bool, string>(false, "Inser Store Owner Operation from DB Failed cannot proceed"));
                }
                return(ans);
            }
            DbManager.Instance.SaveChanges();
            return(new Tuple <bool, string>(true, "User Still has some Work to do before he can become an Owner of this Store."));
        }
Beispiel #14
0
        /* ======================================================================================== */
        #endregion

        #region [ PUBLIC METHODS ]
        /* ======================================================================================== */
        /// <summary>
        /// Сохраняет данные *.xml в хранилище.
        /// </summary>
        /// <param name="owner">Владелец данных. Обычно приложение или сервис.</param>
        /// <param name="type">Тип данных.</param>
        /// <param name="id">Иденификатор данных.</param>
        /// <param name="xelem">Фрагмент *.xml данных.</param>
        /// <returns></returns>
        public bool Put(StoreOwner owner, StoreType type, string id, XElement xelem)
        {
            string header = "PutData";

            // Получаем атрибуты элементов перечислений.
            OwnerAttribute ownerAttribute = GetStoreOwnerTextAttribute(owner);
            TypeAttribute  typeAttribute  = GetStoreTypeTextAttribute(type);
            string         curr_id        = "";

            if (id != null && id.Trim() != "")
            {
                curr_id = id;
            }

            // Проверяем входные параметры.
            if (xelem == null || ownerAttribute == null || typeAttribute == null)
            {
                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Incorrect input parameters."));
                return(false);
            }

            // Получаем специальное имя файла.
            string filename = GetFileName(type, curr_id);

            // Формируем корневые xml элементы
            XElement xstore = new XElement("storage");

            xstore.Add(new XAttribute("Owner", ownerAttribute.Name));
            xstore.Add(new XAttribute("Type", typeAttribute.Name));
            xstore.Add(new XAttribute("ID", curr_id));
            xstore.Add(new XAttribute("Saved", DateTime.Now.Ticks.ToString()));

            XElement xdata = new XElement("data");

            xstore.Add(xdata);
            xdata.Add(xelem);

            // Проверяем создана ли специфическая директория для файла, если нет то создаем ее.
            DirectoryInfo di = new DirectoryInfo(StorageDirectory + "\\" + ownerAttribute.Name);

            if (!di.Exists)
            {
                try
                {
                    di.Create();
                    Event_Message(new MessageEventArgs(this, MessageEventArgsType.Info, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Folder was created: " + di.FullName + "."));
                }
                catch
                {
                    Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Imposible to create folder: " + di.FullName + "."));
                    return(false);
                }
            }

            // Сохраняем данные в xml файл.
            string fileName = di.FullName + "\\" + filename;

            try
            {
                XDocument xdoc = new XDocument();
                xdoc.Add(xstore);
                xdoc.Save(fileName);

                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Info, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". XML file was created: " + fileName + "."));
                return(true);
            }
            catch
            {
                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Imposible to create XML file: " + fileName + "."));
                return(false);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Получает все данные из хранилища касаемые данного владельца с заданным типом.
        /// </summary>
        /// <param name="owner">Владелец данных. Обычно приложение или сервис.</param>
        /// <param name="type">Тип данных.</param>
        /// <param name="infos">Полученная информация из хранилища.</param>
        public void Get(StoreOwner owner, StoreType type, out List <StorageItemInfo> infos)
        {
            string header = "GetData";

            // Получаем атрибуты элементов перечислений.
            OwnerAttribute ownerAttribute = GetStoreOwnerTextAttribute(owner);
            TypeAttribute  typeAttribute  = GetStoreTypeTextAttribute(type);

            infos = new List <StorageItemInfo>();

            // Проверяем входные параметры.
            if (ownerAttribute == null || typeAttribute == null)
            {
                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Incorrect input parameters."));
                return;
            }

            // Получаем специальное имя каталога и входящие в него файлы.
            DirectoryInfo di = new DirectoryInfo(StorageDirectory + "\\" + ownerAttribute.Name);

            if (di.Exists)
            {
                foreach (FileInfo fi in di.GetFiles("*.xml"))
                {
                    bool   result   = true;
                    string filename = fi.FullName;

                    try
                    {
                        XDocument xdoc = XDocument.Load(fi.FullName);
                        if (xdoc.Root.ExistAs("storage") && xdoc.Root.Element("data") != null)
                        {
                            string readedId    = xdoc.Root.Attribute("ID").GetXValue(null);
                            string readedTicks = xdoc.Root.Attribute("Saved").GetXValue(null);
                            string readedOwner = xdoc.Root.Attribute("Owner").GetXValue(null);
                            string readedType  = xdoc.Root.Attribute("Type").GetXValue(null);

                            if (readedOwner != ownerAttribute.Name)
                            {
                                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + ". Incorrect file structure: " + fi.FullName + ". Requested Owner = " + ownerAttribute.Name + "<> Readed Owner = " + readedOwner));
                                result = false;
                            }

                            if (readedType != typeAttribute.Name)
                            {
                                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + ". Incorrect file structure: " + fi.FullName + ". Requested Type = " + typeAttribute.Name + "<> Readed Type = " + readedType));
                                result = false;
                            }

                            if (readedTicks == null || !readedTicks.All(c => Char.IsDigit(c)))
                            {
                                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + ". Incorrect file structure: " + fi.FullName + ". Readed DateTime Stamp is not correct."));
                                result = false;
                            }

                            if (result)
                            {
                                StorageItemInfo info = new StorageItemInfo(owner, type, readedId, new DateTime(Convert.ToInt64(readedTicks)), true, xdoc.Root.Element("data"));
                                infos.Add(info);
                            }
                        }
                    }
                    catch
                    {
                        Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + ". Can not to read file: " + fi.FullName + "."));
                    }
                }
            }
            else
            {
                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Warning, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + ". Folder not found: " + di.FullName + "."));
            }
        }
Beispiel #16
0
        /// <summary>
        /// Получает данные из хранилища по конкретному идентификатору.
        /// </summary>
        /// <param name="owner">Владелец данных. Обычно приложение или сервис.</param>
        /// <param name="type">>Тип данных.</param>
        /// <param name="curr_id">Иденификатор данных.</param>
        /// <param name="info">Полученная информация из хранилища.</param>
        /// <returns></returns>
        public bool Get(StoreOwner owner, StoreType type, string id, out StorageItemInfo info)
        {
            string header  = "GetData";
            string curr_id = "";

            if (id != null && id.Trim() != "")
            {
                curr_id = id;
            }

            info = new StorageItemInfo(owner, type, curr_id, null, null, null);

            // Получаем атрибуты элементов перечислений.
            OwnerAttribute ownerAttribute = GetStoreOwnerTextAttribute(owner);
            TypeAttribute  typeAttribute  = GetStoreTypeTextAttribute(type);


            // Проверяем входные параметры.
            if (ownerAttribute == null || typeAttribute == null)
            {
                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Incorrect input parameters."));
                return(false);
            }

            // Получаем специальное имя файла.
            string filename = GetFileName(type, curr_id);

            // Проверяем существует ли данный файл и проверяем его содержимое.
            FileInfo fi = new FileInfo(StorageDirectory + "\\" + ownerAttribute.Name + "\\" + filename);

            if (fi.Exists)
            {
                try
                {
                    XDocument xdoc = XDocument.Load(fi.FullName);
                    if (xdoc.Root.ExistAs("storage") && xdoc.Root.Element("data") != null)
                    {
                        string readedId    = xdoc.Root.Attribute("ID").GetXValue(null);
                        string readedTicks = xdoc.Root.Attribute("Saved").GetXValue(null);
                        string readedOwner = xdoc.Root.Attribute("Owner").GetXValue(null);
                        string readedType  = xdoc.Root.Attribute("Type").GetXValue(null);

                        if (readedOwner != ownerAttribute.Name)
                        {
                            Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Incorrect file structure: " + fi.FullName + ". Requested Owner = " + ownerAttribute.Name + "<> Readed Owner = " + readedOwner));
                            return(false);
                        }

                        if (readedType != typeAttribute.Name)
                        {
                            Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Incorrect file structure: " + fi.FullName + ". Requested Type = " + typeAttribute.Name + "<> Readed Type = " + readedType));
                            return(false);
                        }

                        if (readedTicks == null || !readedTicks.All(c => Char.IsDigit(c)))
                        {
                            Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Incorrect file structure: " + fi.FullName + ". Readed DateTime Stamp is not correct."));
                            return(false);
                        }

                        if (curr_id != readedId)
                        {
                            Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Incorrect file structure: " + fi.FullName + ". Requested ID = " + curr_id + "<> Readed ID = " + readedId));
                            return(false);
                        }

                        info = new StorageItemInfo(owner, type, curr_id, new DateTime(Convert.ToInt64(readedTicks)), true, xdoc.Root.Element("data"));
                        return(true);
                    }
                    else
                    {
                        Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Incorrect file structure: " + fi.FullName + "."));
                        return(false);
                    }
                }
                catch
                {
                    Event_Message(new MessageEventArgs(this, MessageEventArgsType.Error, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". Can not to read file: " + fi.FullName + "."));
                    return(false);
                }
            }
            else
            {
                Event_Message(new MessageEventArgs(this, MessageEventArgsType.Warning, header, "Object:" + ownerAttribute.Name + "::" + typeAttribute.Name + "::" + curr_id + ". File not found: " + fi.FullName + "."));
                return(false);
            }
        }
Beispiel #17
0
        public async Task <AuthenticationResponse> GoogleLoginStoreOwnerAsync(GoogleAuthRequest request)
        {
            if (string.IsNullOrWhiteSpace(request.FirstName) || string.IsNullOrWhiteSpace(request.LastName) || string.IsNullOrWhiteSpace(request.Email))
            {
                return new AuthenticationResponse {
                           Errors = new[] { "FirstName, LastName and Email cannot be empty." }
                }
            }
            ;
            var storeOwnerExist = await _dataContext.StoreOwners.FirstOrDefaultAsync(s => s.EmailAddress == request.Email);

            if (storeOwnerExist != null) // Sign Store Owner in
            {
                storeOwnerExist.LastLoginDate = DateTime.Now;

                _dataContext.Entry(storeOwnerExist).State = EntityState.Modified;
                var updated = await _dataContext.SaveChangesAsync();

                if (updated <= 0)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Failed to signin." }
                    }
                }
                ;

                var token = GenerateAuthenticationTokenForStoreOwner(storeOwnerExist);
                return(new AuthenticationResponse {
                    Success = true, Token = token
                });
            }
            else // Register Store Owner
            {
                var newStoreOwner = new StoreOwner()
                {
                    EmailAddress       = request.Email,
                    FirstName          = request.FirstName,
                    MiddleName         = request.MiddleName,
                    LastName           = request.LastName,
                    PhoneNumber        = request.PhoneNumber,
                    ProfilePicUrl      = request.ImageUrl,
                    IsVerified         = true,
                    DateRegistered     = DateTime.Now,
                    IsGoogleRegistered = true
                };
                await _dataContext.StoreOwners.AddAsync(newStoreOwner);

                var created = await _dataContext.SaveChangesAsync();

                if (created <= 0)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Failed to register customer." }
                    }
                }
                ;

                var token = GenerateAuthenticationTokenForStoreOwner(newStoreOwner);
                return(new AuthenticationResponse {
                    Success = true, Token = token
                });
            }
        }
Beispiel #18
0
        public async Task <AuthenticationResponse> CreateStoreOwnerAsync(StoreOwner storeOwner, string password)
        {
            if (string.IsNullOrWhiteSpace(storeOwner.FirstName) || string.IsNullOrWhiteSpace(storeOwner.LastName) || string.IsNullOrWhiteSpace(storeOwner.EmailAddress))
            {
                return new AuthenticationResponse {
                           Errors = new[] { "FirstName, LastName and Email cannot be empty" }
                }
            }
            ;

            var storeOwnerExist = await _dataContext.StoreOwners.FirstOrDefaultAsync(s => s.EmailAddress == storeOwner.EmailAddress || s.PhoneNumber == storeOwner.PhoneNumber);

            if (storeOwnerExist != null)
            {
                if (!storeOwnerExist.IsVerified)
                {
                    return new AuthenticationResponse {
                               Errors = new[] { "Store Owner already exist but not verified." }
                    }
                }
                ;

                return(new AuthenticationResponse {
                    Errors = new[] { "Store Owner with this email and phonenumber already exists." }
                });
            }

            byte[] passwordHash, passwordSalt;
            try
            {
                Security.CreatePasswordHash(password, out passwordHash, out passwordSalt);
            }
            catch (Exception)
            {
                return(new AuthenticationResponse {
                    Errors = new[] { "Error Occurred." }
                });
            }

            storeOwner.PasswordHash               = passwordHash;
            storeOwner.PasswordSalt               = passwordSalt;
            storeOwner.DateRegistered             = DateTime.Now;
            storeOwner.IsOneKioskContractAccepted = true;

            await _dataContext.StoreOwners.AddAsync(storeOwner);

            var created = await _dataContext.SaveChangesAsync();

            if (created <= 0)
            {
                return new AuthenticationResponse {
                           Errors = new[] { "Failed to register store owner." }
                }
            }
            ;

            var token = GenerateAuthenticationTokenForStoreOwner(storeOwner);

            return(new AuthenticationResponse {
                Success = true, Token = token
            });
        }
Beispiel #19
0
        // Attributes


        public OnlineStore(string storeName, string storeAddress, StoreOwner owner) : base(storeName, storeAddress, owner)
        {
        }
Beispiel #20
0
 public Store(string storeName, string storeAddress, StoreOwner storeOwner)
 {
     this.storeName    = storeName;
     this.storeAddress = storeAddress;
     this.storeOwner   = storeOwner;
 }