Inheritance: MonoBehaviour
Exemplo n.º 1
1
        /// <summary>
        /// This method will validate a property value in a <see cref="BaseModel"/> object asyncronously.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="value">The value to validate.</param>
        /// <param name="propertyName">The name of the property to validate.</param>
        /// <param name="callback">A <see cref="AsyncCallback"/> that will be called when the operation completes.</param>
        /// <param name="state">A user defined object providing state to the asycronous operation.</param>
        /// <returns>A <see cref="IAsyncResult"/> object representing the asyncronous operation.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static IAsyncResult BeginValidateProperty(BaseModel model, object value, string propertyName, AsyncCallback callback, object state)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            return new ValidatePropertyAsyncResult(CurrentValidator, model, value, propertyName, callback, state);
        }
Exemplo n.º 2
0
        /// <summary>
        /// This method will validate a <see cref="BaseModel"/> asyncronously.  Also, if the children of the given
        /// model need to be validated at the same time, it can do that as well.
        /// </summary>
        /// <param name="target">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="validateChildren">If the chilren of the given model should be validated as well, supply true.</param>
        /// <param name="callback">A <see cref="AsyncCallback"/> that will be called when the operation completes.</param>
        /// <param name="state">A user defined object providing state to the asycronous operation.</param>
        /// <returns>A <see cref="IAsyncResult"/> object representing the asyncronous operation.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static IAsyncResult BeginValidateModel(BaseModel target, bool validateChildren, AsyncCallback callback, object state)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            return new ValidateModelAsyncResult(CurrentValidator, target, validateChildren, callback, state);
        }
Exemplo n.º 3
0
 public StaticPageBaseModel(BaseModel baseModel)
     : base(baseModel)
 {
     CurrentLanguage = LanguageType.Default;
     StaticPageTransport = new StaticPageTransport();
     SubNavigationType = SubNavigationType.None;
 }
Exemplo n.º 4
0
 public static void RegisterModel(BaseModel model)
 {
     var timer = new DispatcherTimer();
     timer.Interval = model.Interval;
     timer.Tick += model.TimerTick;
     timer.Start();
 }
 public BaseModel.OperationResult<int> CreateSolution(BaseModel.SolutionConfiguration solution)
 {
     return FunctionResultProxy.GetResult<OperationResult<int>>(delegate (OperationResult<int> r)
     {
         r.Data = SolutionConfigurationDal.Create(solution);
         r.ActionResult = (r.Data > 0);
         return r;
     });
 }
 public BaseModel.OperationResult<int> CreateComponentConfig(BaseModel.ComponentConfiguration componentConfig)
 {
     return FunctionResultProxy.GetResult<OperationResult<int>>(delegate (OperationResult<int> r)
     {
         r.Data = ComponentConfigurationDal.Create(componentConfig);
         r.ActionResult = (r.Data > 0);
         return r;
     });
 }
Exemplo n.º 7
0
        public static BaseModel CreateBaseModel(Guid sID)
        {
            

            BaseModel model = new BaseModel();
            model.Initialize(sID);
            model.Action = TabModelHelper.DefaultAction(sID);
            model.Controller = TabModelHelper.DefaultController(sID);            

            return model;
        }
        /// <summary>
        /// Controller which returns the home index page. 
        /// No data calls or parameters are needed for this
        /// 
        /// Accessed via /Home/index
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            BaseModel model = new BaseModel();
            List<Breadcrumb> trail = new List<Breadcrumb>();

            trail.Add(new Breadcrumb() { LinkText = "Home", Action = "Index", Controller = "Home", isCurrent = true });

            model.Breadcrumbs = trail;

            return View(model);
        }
Exemplo n.º 9
0
        public BaseModel Create(BaseModel model)
        {
            Category entity = (Category) model;
            if (entity.IsValid)
            {
                _db.Categories.Add(entity);
                _db.SaveChanges();
            }

            return entity;
        }
Exemplo n.º 10
0
        public BaseModel Create(BaseModel model)
        {
            Book entity = (Book) model;
            if (entity.IsValid)
            {
                _db.Books.Add(entity);
                _db.SaveChanges();
            }

            return entity;
        }
Exemplo n.º 11
0
        public BaseModel Create(BaseModel model)
        {
            Author entity = (Author)model;
            if (entity.IsValid)
            {
                _db.Authors.Add(entity);
                _db.SaveChanges();
            }

            return entity;
        }
Exemplo n.º 12
0
        public BaseModel Update(BaseModel model)
        {
            Book entity = _db.Books.Find(((Book) model).Id);

            if (entity == null)
                throw new NotImplementedException("Something needs to be done...");

            if (entity.IsValid)
            {
                _db.Entry(model).CurrentValues.SetValues(model);
                _db.SaveChanges();
            }

            return entity;
        }
Exemplo n.º 13
0
        public JsonResult SetProductToSocet(string productId, string socetId, int count)
        {
            var model = new BaseModel();

            if ((productId != string.Empty) && (socetId != string.Empty) && (count > 0))
            {
                var result = SocetProductsService.AddProductIdToSocetId(productId, socetId, count);
                model = Mapper.Map<BaseModel>(result);
            }
            else
            {
                model.SetError(ResError.DataEmpty);
            }

            return Json(model, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 14
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            BaseModel model = new BaseModel();
            model.HtmlTitle = _pageInfos[PageInfoType.HtmlTitle];
            model.HtmlMetaDescription = _pageInfos[PageInfoType.HtmlMetaDescription];
            model.TagModel = new TagModel { PageName = _pageInfos[PageInfoType.TagModel]};
            model.CssContainerId = _pageInfos[PageInfoType.CssContainerId];
            model.CssContainerClass = _pageInfos[PageInfoType.CssContainerClass];
            filterContext.Controller.ViewBag.OmnitureUrl = WebConfigurationManager.AppSettings["OmnitureSrc"];
            filterContext.Controller.ViewData.Model = model;

            // Default value for special omniture tags
            filterContext.Controller.ViewBag.OmnitureEvent = "";
            filterContext.Controller.ViewBag.OmnitureVar25 = "";

            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 15
0
        /// <summary>
        /// This method will validate a property value in a <see cref="BaseModel"/> object.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="value">The value to validate.</param>
        /// <param name="propertyName">The name of the property to validate.</param>
        /// <returns>A boolean value indicating whether the validation was successful or not.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static bool ValidateProperty(BaseModel model, object value, string propertyName)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            IEnumerable<object> validationErrors = CurrentValidator.ValidateProperty(model, value, propertyName);
            ValidationErrorCollection errorCollection = (model as IValidationInteraction).ValidationErrors;

            CurrentManager.SetMemberErrors(errorCollection, validationErrors, propertyName);

            return validationErrors.Count() == 0;
        }
Exemplo n.º 16
0
        /// <summary>
        /// 整版复制
        /// </summary>
        /// <param name="plate"></param>
        /// <returns></returns>
        public PlateModel CopyPlate(PlateModel plate)
        {
            PlateModel copyPlate   = new PlateModel();
            BaseModel  newOutModel = new BaseModel();

            for (int i = 0; i < plate.OutModel.ListShape.Count; i++)
            {
                newOutModel.ListShape.Add(copy(plate.OutModel.ListShape[i]));
            }
            for (int i = 0; i < plate.OutModel.ExpandShape.Count; i++)
            {
                newOutModel.ExpandShape.Add(copy(plate.OutModel.ExpandShape[i]));
            }
            newOutModel.ListPoint.AddRange(plate.OutModel.ListPoint);
            newOutModel.ExpandPoint.AddRange(plate.OutModel.ExpandPoint);
            newOutModel.IsArc          = plate.OutModel.IsArc;
            newOutModel.IsInner        = plate.OutModel.IsInner;
            newOutModel.Area           = plate.OutModel.Area;
            newOutModel.Bound          = plate.OutModel.Bound;
            newOutModel.ModelId        = CADInterface.globalModelID;
            CADInterface.globalModelID = CADInterface.globalModelID + 1;
            //CADInterface .currentPlates .Add(newOutModel);
            //newOutModel.Draw(CADInterface.bGrp.Graphics);
            copyPlate.OutModel = newOutModel;

            if (plate.InnerModel.Count > 0)
            {
                for (int i = 0; i < plate.InnerModel.Count; i++)
                {
                    BaseModel newInnerModel = new BaseModel();
                    for (int j = 0; j < plate.InnerModel[i].ListShape.Count; j++)
                    {
                        newInnerModel.ListShape.Add(copy(plate.InnerModel[i].ListShape[i]));
                    }
                    newInnerModel.ListPoint.AddRange(plate.InnerModel[i].ListPoint);
                    newInnerModel.IsArc   = plate.InnerModel[i].IsArc;
                    newInnerModel.IsInner = plate.InnerModel[i].IsInner;
                    newInnerModel.Area    = plate.InnerModel[i].Area;
                    newInnerModel.Bound   = plate.InnerModel[i].Bound;
                    //newInnerModel.Draw(CADInterface.bGrp.Graphics);
                    newInnerModel.ModelId      = CADInterface.globalModelID;
                    CADInterface.globalModelID = CADInterface.globalModelID + 1;
                    //CADInterface .currentPlates .Add(newInnerModel);
                    copyPlate.InnerModel.Add(newInnerModel);
                }
            }

            copyPlate.RotateCenter = plate.RotateCenter;
            copyPlate.PowCenter    = plate.PowCenter;
            copyPlate.IsArc        = plate.IsArc;
            copyPlate.PlateCode    = plate.PlateCode;
            copyPlate.PlateName    = plate.PlateName;
            copyPlate.PlateNum     = plate.PlateNum;
            copyPlate.Area         = plate.Area;
            copyPlate.Bound        = plate.Bound;
            copyPlate.Rect         = plate.Rect;

            copyPlate.GridValue  = plate.GridValue == null ? null : plate.GridValue.ToList();
            copyPlate.id         = plate.id;
            copyPlate.GridLen    = plate.GridLen;
            copyPlate.GridWid    = plate.GridWid;
            copyPlate.Rect       = plate.Rect;
            copyPlate.Combine    = plate.Combine;
            copyPlate.PlateCount = plate.PlateCount;

            return(copyPlate);
        }
Exemplo n.º 17
0
        public static bool Update(this IDbConnection connection, BaseModel entity)
        {
            var query = $"UPDATE [{entity.GetTableName()}] SET {entity.GetUpdateColumnList()} WHERE [{entity.GetIDColumnName()}] = @{entity.GetIDColumnName()}";

            return(ExecuteWithEffectedRowsCount(connection, entity, query) > 0);
        }
Exemplo n.º 18
0
 public QuotationTemplateController()
 {
     _context           = new ErpEntities(Constants.ConnectionString);
     _quotationTemplate = new BaseModel <iffsQuotationTemplate>(_context);
 }
Exemplo n.º 19
0
 public void ApplyChangesIfModified(BaseModel model)
 {
     HandleUpdate(model);
 }
Exemplo n.º 20
0
        public BaseModel <object> Items_ListbyType(QueryParams _query)
        {
            BaseModel <object> _baseModel     = new BaseModel <object>();
            PageModel          _pageModel     = new PageModel();
            ErrorModel         _error         = new ErrorModel();
            string             _keywordSearch = "";
            bool _orderBy_ASC = false;

            string Token = _account.GetHeader(Request);

            try
            {
                Func <ItemsModel, object> _orderByExpression = x => x.IdItem;
                Dictionary <string, Func <ItemsModel, object> > _sortableFields = new Dictionary <string, Func <ItemsModel, object> >
                {
                    { "IdItem", x => x.IdItem }
                };

                if (!string.IsNullOrEmpty(_query.sortField) && _sortableFields.ContainsKey(_query.sortField))
                {
                    _orderBy_ASC       = ("desc".Equals(_query.sortOrder) ? false : true);
                    _orderByExpression = _sortableFields[_query.sortField];
                }

                List <ItemsModel> _data = new List <ItemsModel>();
                if (!string.IsNullOrEmpty(_query.filter["type"]))
                {
                    _data = (from item in _context.DBItems
                             where item.IdType == (_context.DBTypeItems.Where(type =>
                                                                              type.IdMainMenu == _context.DBMainMenu.Where(menu =>
                                                                                                                           !menu.IsDisabled &&
                                                                                                                           menu.Link.Equals(_query.filter["type"]))
                                                                              .Select(s => s.Id_Main).FirstOrDefault())
                                                   .Select(t => t.IdType).FirstOrDefault())

                             select new ItemsModel
                    {
                        IdItem = item.IdItem,
                        IdType = item.IdType,
                        Name = item.Name,
                        Money = item.Money,
                        Sales = item.Sales,
                        RateAvg = item.RateAvg,
                        LinkImage = item.LinkImage
                    }).ToList();
                }

                int _countRows = _data.Count();
                if (_countRows == 0)
                {
                    _baseModel.status = 0;
                    _error            = new ErrorModel();
                    _error.message    = "Không có dữ liệu hiển thị!";
                    _error.code       = Constant.ERRORCODE_SQL;
                    _baseModel.error  = _error;
                    return(_baseModel);
                }
                _pageModel.TotalCount = _countRows;
                _pageModel.AllPage    = (int)Math.Ceiling(_countRows / (decimal)_query.record);
                _pageModel.Size       = _query.record;
                _pageModel.Page       = _query.page;
                _pageModel.Page       = _query.page;

                if (_query.more)
                {
                    _baseModel.status = 1;
                    _baseModel.error  = null;
                    _baseModel.page   = _pageModel;
                    _baseModel.data   = _data.ToList();
                    return(_baseModel);
                }

                _baseModel.status = 1;
                _baseModel.error  = null;
                _baseModel.page   = _pageModel;

                if (_orderBy_ASC)
                {
                    _baseModel.data = _data
                                      .OrderBy(_orderByExpression)
                                      .Skip((_query.page - 1) * _query.record)
                                      .Take(_query.record)
                                      .ToList();
                }
                else
                {
                    _baseModel.data = _data
                                      .OrderByDescending(_orderByExpression)
                                      .Skip((_query.page - 1) * _query.record)
                                      .Take(_query.record)
                                      .ToList();
                }

                return(_baseModel);
            }
            catch (Exception ex)
            {
                _error         = new ErrorModel();
                _error.message = "Lỗi dữ liệu hoặc bạn phải truyền Token!";
                _error.code    = Constant.ERRORCODE;
                return(new BaseModel <object>
                {
                    status = 0,
                    error = _error,
                    data = null,
                    page = null
                });
            }
        }
Exemplo n.º 21
0
 public override IEnumerator ApplyChanges(BaseModel newJson)
 {
     yield break;
 }
Exemplo n.º 22
0
        void Session_End(object sender, EventArgs e)
        {
            // perform your logic
            BaseModel audit    = new BaseModel();
            string    username = Session["UserName"].ToString();

            try
            {
                if (Application["EditUserSection"] != null)
                {
                    DataTable dt = (DataTable)Application["EditUserSection"];
                    if (dt.Rows.Count > 0)
                    {
                        for (int r = 0; r < dt.Rows.Count; ++r)
                        {
                            DataRow dr = dt.Rows[r];
                            if (dr["UserID"].ToString() == Session["UserID"].ToString())
                            {
                                // do your deed
                                dr.Delete();
                            }
                            //...
                        }
                        dt.AcceptChanges();
                        Application["EditUserSection"] = dt;
                    }
                    else
                    {
                    }
                }
                using (var httpClient = new HttpClient())
                {
                    var url = ConfigurationManager.AppSettings["WEBAPIURL"];

                    httpClient.BaseAddress = new Uri(url);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));



                    var responseTask = httpClient.PutAsJsonAsync("user/UserLogout?userid=" + Session["UserID"].ToString(), "");
                    responseTask.Wait();
                    var result = responseTask.Result;

                    if (result.IsSuccessStatusCode)
                    {
                        using (HttpContent content = result.Content)
                        {
                            Task <string> result1 = content.ReadAsStringAsync();
                            var           rs      = result1.Result;
                            dynamic       data    = JsonConvert.DeserializeObject(rs);
                            string        value   = Convert.ToString(data);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }



            // audit.InsertLogoutAudit("LogOut", "Successfully Logout", "Success", username, Ip);
            Session.Abandon();
        }
 /// <summary>
 /// Inherited from <see cref="IValidator"/>
 /// <remarks>This implementation returns all results at once.  This means that all 
 /// asyncronous operations complete before a result is returned.</remarks>
 /// </summary>
 /// <param name="model">A <see cref="BaseModel"/> that will be validated.</param>
 /// <param name="callback">An <see cref="AsyncCallback"/> reference that will be called when the operation completes.</param>
 /// <param name="state">A user defined object.</param>
 /// <returns>An <see cref="IAsyncResult"/> representing the background operation.</returns>
 public virtual IAsyncResult BeginValidateModel(BaseModel model, AsyncCallback callback, object state)
 {
     return new DefaultValidateModelAsyncResult(model, this, callback, state);
 }
Exemplo n.º 24
0
        public async Task <JsonResult> UploadAsync(FullPath path, IEnumerable <IFormFile> files, bool?overwrite, IEnumerable <FullPath> uploadPaths, IEnumerable <string> renames, string suffix)
        {
            var response = new AddResponseModel();

            if (path.RootVolume.MaxUploadSize.HasValue)
            {
                foreach (var file in files)
                {
                    if (file.Length > path.RootVolume.MaxUploadSize.Value)
                    {
                        return(Error.MaxUploadFileSize());
                    }
                }
            }

            foreach (string rename in renames)
            {
                var    fileInfo    = new FileInfo(Path.Combine(path.Directory.FullName, rename));
                string destination = Path.Combine(path.Directory.FullName, $"{Path.GetFileNameWithoutExtension(rename)}{suffix}{Path.GetExtension(rename)}");
                fileInfo.MoveTo(destination);
                response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(destination), path.RootVolume));
            }

            foreach (var uploadPath in uploadPaths)
            {
                var directory = uploadPath.Directory;
                while (directory.FullName != path.RootVolume.RootDirectory)
                {
                    response.Added.Add(await BaseModel.CreateAsync(new FileSystemDirectory(directory.FullName), path.RootVolume));
                    directory = directory.Parent;
                }
            }

            int i = 0;

            foreach (var file in files)
            {
                string destination = uploadPaths.Count() > i?uploadPaths.ElementAt(i).Directory.FullName : path.Directory.FullName;

                var fileInfo = new FileInfo(Path.Combine(destination, Path.GetFileName(file.FileName)));

                if (fileInfo.Exists)
                {
                    if (overwrite ?? path.RootVolume.UploadOverwrite)
                    {
                        fileInfo.Delete();
                        using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                        }
                        response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(fileInfo.FullName), path.RootVolume));
                    }
                    else
                    {
                        string newName = CreateNameForCopy(fileInfo, suffix);
                        using (var fileStream = new FileStream(Path.Combine(fileInfo.DirectoryName, newName), FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                        }
                        response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(newName), path.RootVolume));
                    }
                }
                else
                {
                    using (var fileStream = new FileStream(fileInfo.FullName, FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                    response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(fileInfo.FullName), path.RootVolume));
                }

                i++;
            }
            return(await Json(response));
        }
        public async Task <JsonResult> UploadAsync(FullPath path, IEnumerable <IFormFile> files)
        {
            int fileCount = files.Count();

            var response = new AddResponseModel();

            if (path.RootVolume.MaxUploadSize.HasValue)
            {
                for (int i = 0; i < fileCount; i++)
                {
                    IFormFile file = files.ElementAt(i);
                    if (file.Length > path.RootVolume.MaxUploadSize.Value)
                    {
                        return(Error.MaxUploadFileSize());
                    }
                }
            }
            foreach (var file in files)
            {
                var p = new FileInfo(Path.Combine(path.Directory.FullName, Path.GetFileName(file.FileName)));

                if (p.Exists)
                {
                    if (path.RootVolume.UploadOverwrite)
                    {
                        //if file already exist we rename the current file,
                        //and if upload is succesfully delete temp file, in otherwise we restore old file
                        string tmpPath  = p.FullName + Guid.NewGuid();
                        bool   uploaded = false;
                        try
                        {
                            using (var fileStream = new FileStream(tmpPath, FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                            }

                            uploaded = true;
                        }
                        catch { }
                        finally
                        {
                            if (uploaded)
                            {
                                File.Delete(p.FullName);
                                File.Move(tmpPath, p.FullName);
                            }
                            else
                            {
                                File.Delete(tmpPath);
                            }
                        }
                    }
                    else
                    {
                        using (var fileStream = new FileStream(Path.Combine(p.DirectoryName, Utils.GetDuplicatedName(p)), FileMode.Create))
                        {
                            await file.CopyToAsync(fileStream);
                        }
                    }
                }
                else
                {
                    using (var fileStream = new FileStream(p.FullName, FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
                response.Added.Add((FileModel)await BaseModel.Create(this, new FileSystemFile(p.FullName), path.RootVolume));
            }
            return(await Json(response));
        }
Exemplo n.º 26
0
        public async Task <JsonResult> InitAsync(FullPath path, IEnumerable <string> mimeTypes)
        {
            if (path == null)
            {
                var root = Roots.FirstOrDefault(r => r.StartDirectory != null);
                if (root == null)
                {
                    root = Roots.First();
                }

                if (Directory.Exists(root.StartDirectory))
                {
                    path = new FullPath(root, new FileSystemDirectory(root.StartDirectory), null);
                }

                if (path == null || path.Directory.GetReadFlag(root) == 0)
                {
                    path = new FullPath(root, new FileSystemDirectory(root.RootDirectory), null);
                }
            }

            var response = new InitResponseModel(await BaseModel.CreateAsync(path.Directory, path.RootVolume), new Options(path));

            foreach (var item in await path.Directory.GetFilesAsync(mimeTypes))
            {
                if (!item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.Files.Add(await BaseModel.CreateAsync(item, path.RootVolume));
                }
            }
            foreach (var item in await path.Directory.GetDirectoriesAsync())
            {
                if (!item.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    response.Files.Add(await BaseModel.CreateAsync(item, path.RootVolume));
                }
            }

            foreach (var item in Roots)
            {
                response.Files.Add(await BaseModel.CreateAsync(new FileSystemDirectory(item.RootDirectory), item));
            }

            if (path.RootVolume.RootDirectory != path.Directory.FullName)
            {
                var dirInfo = new DirectoryInfo(path.RootVolume.RootDirectory);
                foreach (var item in dirInfo.GetDirectories())
                {
                    var attributes = item.Attributes;
                    if (!attributes.HasFlag(FileAttributes.Hidden))
                    {
                        response.Files.Add(await BaseModel.CreateAsync(new FileSystemDirectory(item), path.RootVolume));
                    }
                }
            }

            if (path.RootVolume.MaxUploadSize.HasValue)
            {
                response.Options.UploadMaxSize = $"{path.RootVolume.MaxUploadSizeInKb.Value}K";
            }
            return(await Json(response));
        }
Exemplo n.º 27
0
        public async Task <JsonResult> ExtractAsync(FullPath fullPath, bool newFolder)
        {
            var response = new AddResponseModel();

            if (fullPath.IsDirectory || fullPath.File.Extension.ToLower() != ".zip")
            {
                throw new NotSupportedException("Only .zip files are currently supported.");
            }

            string rootPath = fullPath.File.Directory.FullName;

            if (newFolder)
            {
                rootPath = Path.Combine(rootPath, Path.GetFileNameWithoutExtension(fullPath.File.Name));
                var rootDir = new FileSystemDirectory(rootPath);
                if (!await rootDir.ExistsAsync)
                {
                    await rootDir.CreateAsync();
                }
                response.Added.Add(await BaseModel.CreateAsync(rootDir, fullPath.RootVolume));
            }

            using (var archive = ZipFile.OpenRead(fullPath.File.FullName))
            {
                string separator = Path.DirectorySeparatorChar.ToString();
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    try
                    {
                        //Replce zip entry path separator by system path separator
                        string file = Path.Combine(rootPath, entry.FullName)
                                      .Replace("/", separator).Replace("\\", separator);

                        if (file.EndsWith(separator)) //directory
                        {
                            var dir = new FileSystemDirectory(file);

                            if (!await dir.ExistsAsync)
                            {
                                await dir.CreateAsync();
                            }
                            if (!newFolder)
                            {
                                response.Added.Add(await BaseModel.CreateAsync(dir, fullPath.RootVolume));
                            }
                        }
                        else
                        {
                            entry.ExtractToFile(file, true);
                            if (!newFolder)
                            {
                                response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(file), fullPath.RootVolume));
                            }
                        }
                    }
                    catch //(Exception ex)
                    {
                        //throw new Exception(entry.FullName, ex);
                    }
                }
            }

            return(await Json(response));
        }
Exemplo n.º 28
0
        public async Task <JsonResult> DuplicateAsync(IEnumerable <FullPath> paths)
        {
            var response = new AddResponseModel();

            foreach (var path in paths)
            {
                if (path.IsDirectory)
                {
                    string parentPath = path.Directory.Parent.FullName;
                    string name       = path.Directory.Name;
                    string newName    = $"{parentPath}{Path.DirectorySeparatorChar}{name} copy";

                    if (!Directory.Exists(newName))
                    {
                        DirectoryCopy(path.Directory.FullName, newName, true);
                    }
                    else
                    {
                        bool foundNewName = false;
                        for (int i = 1; i < 100; i++)
                        {
                            newName = $"{parentPath}{Path.DirectorySeparatorChar}{name} copy {i}";
                            if (!Directory.Exists(newName))
                            {
                                DirectoryCopy(path.Directory.FullName, newName, true);
                                foundNewName = true;
                                break;
                            }
                        }

                        if (!foundNewName)
                        {
                            return(Error.NewNameSelectionException($"{name} copy"));
                        }
                    }

                    response.Added.Add(await BaseModel.CreateAsync(new FileSystemDirectory(newName), path.RootVolume));
                }
                else
                {
                    string parentPath = path.File.Directory.FullName;
                    string name       = path.File.Name.Substring(0, path.File.Name.Length - path.File.Extension.Length);
                    string ext        = path.File.Extension;

                    string newName = $"{parentPath}{Path.DirectorySeparatorChar}{name} copy{ext}";

                    if (!File.Exists(newName))
                    {
                        File.Copy(path.File.FullName, newName);
                    }
                    else
                    {
                        bool foundNewName = false;
                        for (int i = 1; i < 100; i++)
                        {
                            newName = $"{parentPath}{Path.DirectorySeparatorChar}{name} copy {i}{ext}";
                            if (!File.Exists(newName))
                            {
                                File.Copy(path.File.FullName, newName);
                                foundNewName = true;
                                break;
                            }
                        }

                        if (!foundNewName)
                        {
                            return(Error.NewNameSelectionException($"{name} copy{ext}"));
                        }
                    }
                    response.Added.Add(await BaseModel.CreateAsync(new FileSystemFile(newName), path.RootVolume));
                }
            }
            return(await Json(response));
        }
Exemplo n.º 29
0
 public static List <object> GetParameters <T>(this BaseModel item) where T : BaseModel, new()
 => GetFieldsFromTable(item.GetType()).Select(x => new SqliteParameter($"@{x.Name}", x.GetValue(item)))
 .OfType <object>()
 .ToList();
Exemplo n.º 30
0
 public PhraseModel(BaseModel baseModel, List<PhraseEntityModel> phraseEntities)
     : base(baseModel)
 {
     PhraseEntities = phraseEntities;
 }
Exemplo n.º 31
0
        public BaseModel <object> Detail(long id)
        {
            BaseModel <object> _baseModel = new BaseModel <object>();
            PageModel          _pageModel = new PageModel();
            ErrorModel         _error     = new ErrorModel();

            string Token = _account.GetHeader(Request);

            try
            {
                Func <ItemsModel, object> _orderByExpression = x => x.IdItem;
                Dictionary <string, Func <ItemsModel, object> > _sortableFields = new Dictionary <string, Func <ItemsModel, object> >
                {
                    { "IdItem", x => x.IdItem }
                };

                ItemsModel _data = (from item in _context.DBItems
                                    where item.IdItem == id
                                    select new ItemsModel
                {
                    IdItem = item.IdItem,
                    IdType = item.IdType,
                    Name = item.Name,
                    Money = item.Money,
                    Sales = item.Sales,
                    RateAvg = _context.DBReview.Where(x => x.IdItem == item.IdItem.Value).Count() <= 0 ? 0 : Decimal.Divide(Decimal.Divide(_context.DBReview.Where(x => x.IdItem == item.IdItem.Value).Select(s => s.Rate).Sum(), _context.DBReview.Where(x => x.IdItem == item.IdItem.Value).Count()), 5) * 100,
                    RateNumber = _context.DBReview.Where(x => x.IdItem == item.IdItem.Value).Count(),
                    LinkImage = item.LinkImage,
                }).ToList().FirstOrDefault();


                _data.UserReview = _context.DBReview.Where(x => x.IdItem == id)
                                   .Join(_context.DBAccount,
                                         re => re.IdAccount,
                                         acc => acc.IdAccount,
                                         (re, acc) => new { re = re, acc = acc })
                                   .Join(_context.DBUser,
                                         acc => acc.acc.IdUser,
                                         user => user.IdUser,
                                         (acc, user) => new { acc = acc, user = user })

                                   .Select(s => new UserReview
                {
                    AccountName = s.user.Fullname,
                    Time        = s.acc.re.Time,
                    Rate        = Decimal.Divide(s.acc.re.Rate, 5) * 100,
                    Text        = s.acc.re.Text
                }).ToList();

                _baseModel.status = 1;
                _baseModel.error  = null;
                _baseModel.data   = _data;
                _baseModel.page   = _pageModel;

                return(_baseModel);
            }
            catch (Exception ex)
            {
                _error         = new ErrorModel();
                _error.message = "Lỗi dữ liệu hoặc bạn phải truyền Token!";
                _error.code    = Constant.ERRORCODE;
                return(new BaseModel <object>
                {
                    status = 0,
                    error = _error,
                    data = null,
                    page = null
                });
            }
        }
Exemplo n.º 32
0
 /// <summary>
 /// Sets the values of its own variables from the given snapshot
 /// </summary>
 /// <param name="snapshot"></param>
 public abstract void ImportValues(BaseModel snapshot);
Exemplo n.º 33
0
        public static bool Delete(this IDbConnection connection, BaseModel entity)
        {
            var affectedrows = connection.Execute($"DELETE FROM [{entity.GetTableName()}] WHERE [{entity.GetIDColumnName()}] = @Id", entity);

            return(affectedrows > 0);
        }
Exemplo n.º 34
0
 public int Login(string email, string password, out BaseModel result)
 {
     return _dao.Login(email, password, out result);   
 }
Exemplo n.º 35
0
 public static bool MustVerUp(Context context, BaseModel baseModel)
 {
     return
         (baseModel.Updator.Id != context.UserId ||
          baseModel.UpdatedTime.DifferentDate(context: context));
 }
Exemplo n.º 36
0
		public int UpdateSetting(string userID, BaseModel model)
		{
			return _dao.UpdateSetting(userID, model);
		}
Exemplo n.º 37
0
        /// <summary>Overriding the base implementation, which always returns true. In this case, a views holder is recyclable only if its <see cref="BaseVH.CanPresentModelType(Type)"/> returns true for the model at index <paramref name="indexOfItemThatWillBecomeVisible"/></summary>
        /// <seealso cref="OSA{TParams, TItemViewsHolder}.IsRecyclable(TItemViewsHolder, int, double)"/>
        protected override bool IsRecyclable(BaseVH potentiallyRecyclable, int indexOfItemThatWillBecomeVisible, double sizeOfItemThatWillBecomeVisible)
        {
            BaseModel model = Data[indexOfItemThatWillBecomeVisible];

            return(potentiallyRecyclable.CanPresentModelType(model.CachedType));
        }
Exemplo n.º 38
0
		public int SelectVocaSetsDataByID(string userID, int vocaSetID, out BaseModel result)
		{
			return _dao.SelectVocaSetsDataByID(userID, vocaSetID, out result);
		}
Exemplo n.º 39
0
        private static async Task <bool> CreateOrUpdateDocument(BaseModel myObject) // true if success
        {
            if (NotInit)
            {
                return(false);
            }

            string id;
            string collectionId;

            if (myObject.GetType() == typeof(LiveEventEntry))
            {
                id           = ((LiveEventEntry)myObject).Id;
                collectionId = CollectionOutputs;
            }
            else if (myObject.GetType() == typeof(LiveEventSettingsInfo))
            {
                id           = ((LiveEventSettingsInfo)myObject).Id;
                collectionId = CollectionSettings;
            }
            else if (myObject.GetType() == typeof(StreamingPolicyInfo))
            {
                id           = ((StreamingPolicyInfo)myObject).Id;
                collectionId = CollectionStreamingPolicies;
            }
            else if (myObject.GetType() == typeof(AssetEntry))
            {
                id           = ((AssetEntry)myObject).Id;
                collectionId = CollectionVODAssets;
            }
            else if (myObject.GetType() == typeof(VodResource))
            {
                id           = ((VodResource)myObject).Id;
                collectionId = CollectionVODResources;
            }
            else
            {
                return(false);
            }

            try
            {
                await _client.ReplaceDocumentAsync(
                    UriFactory.CreateDocumentUri(Database, collectionId, id), myObject);

                return(true);
            }
            catch (DocumentClientException de)
            {
                if (de.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            try // new document
            {
                await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, collectionId), myObject);

                return(true);
            }
            catch (DocumentClientException de)
            {
                if (de.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            try // let create the db, collection, and document
            {
                // we use shared RU for the database (RU are shared among the collections)
                await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = Database }, new RequestOptions { OfferThroughput = OfferThroughput });

                if (!DoNotUsePartitionMode)
                {
                    await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Database), new DocumentCollection { Id = collectionId, PartitionKey = PartitionKeyDef });
                }
                else
                {
                    await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Database), new DocumentCollection { Id = collectionId });
                }

                await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, collectionId), myObject);

                return(true);
            }
            catch
            {
            }

            return(false);
        }
Exemplo n.º 40
0
 public DomainStatsModel(BaseModel baseModel, List<DomainStatsEntityModel> phraseDomains, PhraseEntityModel phrase)
     : base(baseModel)
 {
     Phrase = phrase;
     PhraseDomains = phraseDomains;
 }
Exemplo n.º 41
0
 internal void AddQueue(BaseModel model)
 {
     dataQueue.Enqueue(model);
 }
Exemplo n.º 42
0
 private static int ExecuteWithEffectedRowsCount(IDbConnection connection, BaseModel entity, string query)
 {
     return(connection.Execute(query, entity));
 }
 /// <summary>
 /// Inherited from <see cref="IValidator"/>
 /// <remarks>This implementation returns all results at once.  This means that all 
 /// asyncronous operations complete before a result is returned.</remarks>
 /// </summary>
 /// <param name="model">A <see cref="BaseModel"/> that will be validated.</param>
 /// <param name="value">The value that needs to be validated.</param>
 /// <param name="propertyName">The name of the property who's value has changed and needs to be validated.</param>
 /// <param name="callback">An <see cref="AsyncCallback"/> reference that will be called when the operation completes.</param>
 /// <param name="state">A user defined object.</param>
 /// <returns>An <see cref="IAsyncResult"/> representing the background operation.</returns>
 public virtual IAsyncResult BeginValidateProperty(BaseModel model, object value, string propertyName, AsyncCallback callback, object state)
 {
     return new DefaultValidatePropertyAsyncResult(model, this, value, propertyName, callback, state);
 }
 public FiringPatternShapeObject(double start, double stop, ref GameContent MainContent, BaseModel fromModel)
 {
     this.start       = start;
     this.stop        = stop;
     this.fromModel   = fromModel;
     this.MainContent = MainContent;
 }
Exemplo n.º 45
0
 public StatusModel(BaseModel baseModel, ProgressStatusSummary serverProgress)
     : base(baseModel)
 {
     ServerProgress = serverProgress;
 }
 public FiringPatternTimeObject(ref GameContent MainContent, BaseModel frombModel)
 {
     this.fromModel   = frombModel;
     this.MainContent = MainContent;
 }
Exemplo n.º 47
0
 public int UpdateData(BaseModel model)
 {
     return _dao.InsertData(model);
 }
        public FiringPatternTimeObject From(BaseModel fromModel)
        {
            FiringPatternTimeObject fp = new FiringPatternTimeObject(ref MainContent, fromModel);

            return(fp);
        }
Exemplo n.º 49
0
 public int UpdateUserState(ref BaseModel result)
 {
     return _dao.UpdateUserState(ref result);
 }
Exemplo n.º 50
0
 public BaseModelTests()
 {
     model = Substitute.For <BaseModel>();
 }
Exemplo n.º 51
0
		//public int SelectUserHomePageData(string userID, out BaseModel model)
		//{
		//	return _dao.SelectUserHomePageData(userID, out model);
		//}

        public int SelectData(BaseModel model, out IEnumerable<BaseModel> results)
        {
            return _dao.SelectData(model, out results);
        }
Exemplo n.º 52
0
 public ActorRefreshCommand(BaseModel baseModel)
 {
     BaseModelModel = baseModel;
 }
Exemplo n.º 53
0
 public int SelectDataByID(string id, out BaseModel result)
 {
     return _dao.SelectDataByID(id, out result);
 }
Exemplo n.º 54
0
 public static List <object> GetIdParameter(this BaseModel model) => new List <object>
 {
     new SqliteParameter(model.GetType().Name, model.Id)
 };
Exemplo n.º 55
0
        /// <summary>
        /// This method will validate a <see cref="BaseModel"/>.  Also, if the children of the given
        /// model need to be validated at the same time, it can do that as well.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="validateChildren">If the chilren of the given model should be validated as well, supply true.</param>
        /// <returns>A boolean value indicating whether the validation was successful or not.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static bool ValidateModel(BaseModel model, bool validateChildren = false)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            IEnumerable<object> validationErrors = CurrentValidator.ValidateModel(model);
            ValidationErrorCollection errorCollection = (model as IValidationInteraction).ValidationErrors;

            CurrentManager.SetErrors(errorCollection, validationErrors);

            //If we're validating the children as well.
            if (validateChildren)
            {
                IEnumerable<PropertyInfo> properties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(BaseModel).IsAssignableFrom(a.PropertyType));
                IEnumerable<PropertyInfo> colProperties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(IEnumerable<BaseModel>).IsAssignableFrom(a.PropertyType));

                foreach (PropertyInfo pi in properties)
                    ValidateModel((BaseModel)pi.GetValue(model, null), validateChildren);
                foreach (PropertyInfo pi in colProperties)
                {
                    foreach (BaseModel bm in (IEnumerable<BaseModel>)pi.GetValue(model, null))
                        ValidateModel(bm, validateChildren);
                }
            }

            return validationErrors.Count() == 0;
        }
Exemplo n.º 56
0
 private void OnDestroyEvent(BaseModel destroyedEntity)
 {
     _entities.Remove((EntityModel)destroyedEntity);
 }
Exemplo n.º 57
0
        public override IEnumerator ApplyChanges(BaseModel newModel)
        {
            DisablePassport();

            var model = (AvatarModel)newModel;

            everythingIsLoaded = false;

            bool avatarDone   = false;
            bool avatarFailed = false;

            yield return(null); //NOTE(Brian): just in case we have a Object.Destroy waiting to be resolved.

            avatarRenderer.ApplyModel(model, () => avatarDone = true, () => avatarFailed = true);

            yield return(new WaitUntil(() => avatarDone || avatarFailed));

            onPointerDown.Initialize(
                new OnPointerDown.Model()
            {
                type      = OnPointerDown.NAME,
                button    = WebInterface.ACTION_BUTTON.POINTER.ToString(),
                hoverText = "view profile"
            },
                entity
                );

            CommonScriptableObjects.worldOffset.OnChange -= OnWorldReposition;
            CommonScriptableObjects.worldOffset.OnChange += OnWorldReposition;

            entity.OnTransformChange -= avatarMovementController.OnTransformChanged;
            entity.OnTransformChange += avatarMovementController.OnTransformChanged;

            entity.OnTransformChange -= OnEntityTransformChanged;
            entity.OnTransformChange += OnEntityTransformChanged;

            onPointerDown.OnPointerDownReport -= PlayerClicked;
            onPointerDown.OnPointerDownReport += PlayerClicked;

            // To deal with the cases in which the entity transform was configured before the AvatarShape
            if (!initializedPosition && entity.components.ContainsKey(DCL.Models.CLASS_ID_COMPONENT.TRANSFORM))
            {
                initializedPosition = true;

                avatarMovementController.MoveTo(
                    entity.gameObject.transform.localPosition - Vector3.up * DCLCharacterController.i.characterController.height / 2,
                    entity.gameObject.transform.localRotation, true);
            }

            avatarUserInfo.userId        = model.id;
            avatarUserInfo.userName      = model.name;
            avatarUserInfo.worldPosition = lastAvatarPosition != null ? lastAvatarPosition.Value : entity.gameObject.transform.localPosition;
            MinimapMetadataController.i?.UpdateMinimapUserInformation(avatarUserInfo);

            avatarName.SetName(model.name);
            avatarName.SetTalking(model.talking);

            avatarCollider.gameObject.SetActive(true);

            everythingIsLoaded = true;
            OnAvatarShapeUpdated?.Invoke(entity, this);

            EnablePassport();
        }
Exemplo n.º 58
0
 public static string ToDeleteQuery(this BaseModel model)
 {
     return($"DELETE FROM {model.GetType().Name} WHERE Id = @Id");
 }
Exemplo n.º 59
0
        /// <summary>
        /// Call this method to clear all validation issues with a given model.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to clear validation issues from.</param>
        /// <param name="clearChildIssues">A boolean value indicating whether or not to clear child objects issues as well.</param>
        public static void ClearValidationIssues(BaseModel model, bool clearChildIssues = false)
        {
            if (model == null)
                return;

            (model as IValidationInteraction).ValidationErrors.Clear();

            if (clearChildIssues)
            {
                IEnumerable<PropertyInfo> properties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(BaseModel).IsAssignableFrom(a.PropertyType));
                IEnumerable<PropertyInfo> colProperties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(IEnumerable<BaseModel>).IsAssignableFrom(a.PropertyType));

                foreach (PropertyInfo pi in properties)
                    ClearValidationIssues((BaseModel)pi.GetValue(model, null), clearChildIssues);
                foreach (PropertyInfo pi in colProperties)
                {
                    foreach (BaseModel bm in (IEnumerable<BaseModel>)pi.GetValue(model, null))
                        ClearValidationIssues(bm, clearChildIssues);
                }
            }
        }
Exemplo n.º 60
0
        public async Task <bool> CompleteU2fRegistrationAsync(User user, int id, string name, string deviceResponse)
        {
            if (string.IsNullOrWhiteSpace(deviceResponse))
            {
                return(false);
            }

            var challenges = await _u2fRepository.GetManyByUserIdAsync(user.Id);

            if (!challenges?.Any() ?? true)
            {
                return(false);
            }

            var registerResponse = BaseModel.FromJson <RegisterResponse>(deviceResponse);

            try
            {
                var challenge  = challenges.OrderBy(i => i.Id).Last(i => i.KeyHandle == null);
                var startedReg = new StartedRegistration(challenge.Challenge, challenge.AppId);
                var reg        = U2fLib.FinishRegistration(startedReg, registerResponse);

                await _u2fRepository.DeleteManyByUserIdAsync(user.Id);

                // Add device
                var providers = user.GetTwoFactorProviders();
                if (providers == null)
                {
                    providers = new Dictionary <TwoFactorProviderType, TwoFactorProvider>();
                }
                var provider = user.GetTwoFactorProvider(TwoFactorProviderType.U2f);
                if (provider == null)
                {
                    provider = new TwoFactorProvider();
                }
                if (provider.MetaData == null)
                {
                    provider.MetaData = new Dictionary <string, object>();
                }

                if (provider.MetaData.Count >= 5)
                {
                    // Can only register up to 5 keys
                    return(false);
                }

                var keyId = $"Key{id}";
                if (provider.MetaData.ContainsKey(keyId))
                {
                    provider.MetaData.Remove(keyId);
                }

                provider.Enabled = true;
                provider.MetaData.Add(keyId, new TwoFactorProvider.U2fMetaData
                {
                    Name        = name,
                    KeyHandle   = reg.KeyHandle == null ? null : Utils.ByteArrayToBase64String(reg.KeyHandle),
                    PublicKey   = reg.PublicKey == null ? null : Utils.ByteArrayToBase64String(reg.PublicKey),
                    Certificate = reg.AttestationCert == null ? null : Utils.ByteArrayToBase64String(reg.AttestationCert),
                    Compromised = false,
                    Counter     = reg.Counter
                });

                if (providers.ContainsKey(TwoFactorProviderType.U2f))
                {
                    providers.Remove(TwoFactorProviderType.U2f);
                }

                providers.Add(TwoFactorProviderType.U2f, provider);
                user.SetTwoFactorProviders(providers);
                await UpdateTwoFactorProviderAsync(user, TwoFactorProviderType.U2f);

                return(true);
            }
            catch (U2fException e)
            {
                Logger.LogError(e, "Complete U2F registration error.");
                return(false);
            }
        }