コード例 #1
0
        public void FileOrganizerPauseTest()
        {
            string inFolder  = $"{nameof(FileOrganizerPauseTest)}\\in";
            string outFolder = $"{nameof(FileOrganizerPauseTest)}\\out";

            System.Collections.Generic.IEnumerable <string> files = Directory.EnumerateFiles(inFolder);
            int originalCount = files.Count();

            //// process test
            TaskManager mgr         = new TaskManager();
            int         count       = 0;
            var         processTask = Task.Run(() =>
            {
                count = mgr.StartWork(2, inFolder, outFolder, s => { });
            });

            mgr.PauseWork();
            Assert.AreNotEqual(originalCount, count);
            mgr.ResumeWork();
            processTask.Wait();
            Assert.AreEqual(originalCount, count);
            Assert.IsTrue(Directory.Exists($"{outFolder}\\{DateTime.Today.Year.ToString()}\\April"));
            files = Directory.EnumerateFiles($"{outFolder}\\{DateTime.Today.Year.ToString()}\\April");
            Assert.IsTrue(files.Count(x => x.Contains("duplicate")) == 6);

            //// ensure original is intact
            files = Directory.EnumerateFiles(inFolder);
            Assert.IsTrue(files.Count() == originalCount);
        }
コード例 #2
0
        public void FileOrganizerStopTest()
        {
            string inFolder  = $"{nameof(FileOrganizerStopTest)}\\in";
            string outFolder = $"{nameof(FileOrganizerStopTest)}\\out";

            System.Collections.Generic.IEnumerable <string> files = Directory.EnumerateFiles(inFolder);
            int originalCount = files.Count();

            //// process test
            TaskManager mgr         = new TaskManager();
            int         count       = 0;
            var         processTask = Task.Run(() =>
            {
                count = mgr.StartWork(2, inFolder, outFolder, s => { });
            });

            Thread.Sleep(10);
            mgr.StopWork();
            Assert.AreNotEqual(originalCount, count);

            processTask.Wait();
            Assert.IsTrue(Directory.Exists($"{outFolder}\\{DateTime.Today.Year.ToString()}\\April"));

            //// revert test
            count = mgr.RevertWork(s => { });
            Assert.IsTrue(count > 0);
            Assert.IsTrue(!Directory.Exists($"{outFolder}\\{DateTime.Today.Year.ToString()}"));

            //// ensure original is intact
            files = Directory.EnumerateFiles(inFolder);
            Assert.IsTrue(files.Count() == originalCount);
        }
コード例 #3
0
        private void TypeBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            saveButton.IsEnabled = true;
            if (e.AddedItems.Count == 0)
            {
                return;
            }

            Type      type         = (typeBox.SelectedItem as ComboBoxItem).Tag as Type;
            Condition newCondition = (Condition)Activator.CreateInstance(type);

            _CurrentConditionType = type;
            ClearParameters();
            variablesGrid.DataContext = newCondition;
            System.Collections.Generic.IEnumerable <FrameworkElement> controls = newCondition.GetControls();
            int mult = controls.Count();

            foreach (FrameworkElement c in controls)
            {
                variablesGrid.Children.Add(c);
            }

            double newHeight = (baseHeight + (heightDelta * (mult + (mult > 1 ? 1 : 0))));

            if (AppConfig.Instance.animateControls)
            {
                DoubleAnimation anim = new DoubleAnimation(Height, newHeight, new Duration(new TimeSpan(0, 0, 0, 0, 500)));
                BeginAnimation(HeightProperty, anim);
            }
            else
            {
                Height = newHeight;
            }
        }
コード例 #4
0
        public void Update(DuelMastersModels.Duel duel, Zone zone)
        {
            foreach (Card cardToAdd in zone.Cards.Where(handCard => Cards.All(viewModelCard => viewModelCard.GameId != handCard.GameId)))
            {
                if (cardToAdd is Creature creature)
                {
                    Cards.Add(new CreatureViewModel(creature, duel));
                }
                else if (cardToAdd is Spell spell)
                {
                    Cards.Add(new SpellViewModel(spell));
                }
                else
                {
                    throw new System.NotImplementedException();
                }
            }
            System.Collections.Generic.IEnumerable <CardViewModel> cardsToRemove = Cards.Where(viewModelCard => zone.Cards.All(handCard => handCard.GameId != viewModelCard.GameId));
            while (cardsToRemove.Count() > 0)
            {
                Cards.Remove(cardsToRemove.First());
            }

            for (int i = 0; i < Cards.Count; ++i)
            {
                Cards[i].Update(zone.Cards[i], duel);
            }
        }
コード例 #5
0
        public void test_ToEnumerable()
        {
            Runtime rt = TestingHelpers.LoadSmallRuntime <TitanicDataRow>("titanic_train.csv", 0, 5);

            System.Collections.Generic.IEnumerable <PmlInstance> instances = rt.Impl.ToEnumerable();
            Assert.AreEqual(5, instances.Count());
        }
コード例 #6
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            string pid = Request.QueryString["pid"];

            if (!string.IsNullOrEmpty(pid))
            {
                NetRadio.Assistant.Web.Controls.TabViewItem item;
                System.Collections.Generic.IEnumerable <NetRadio.Model.Menu> menus = Business.BusSystemMenu.GetSystemMenuFromCache(NetRadio.Common.LocatingMonitor.ContextUser.Current, pid, true);
                ObjectView.Items.Clear();
                string _url = "";
                for (int i = 0; i < menus.Count(); i++)
                {
                    item = new NetRadio.Assistant.Web.Controls.TabViewItem();
                    _url = menus.ElementAt(i).MenuUrl;
                    if (_url.IndexOf("pid=") == -1)
                    {
                        _url = _url.IndexOf("?") == -1 ? (_url + "?pid=" + pid) : (_url + "&pid=" + pid);
                    }
                    item.Href  = "/" + _url;
                    item.Label = menus.ElementAt(i).MenuText;
                    ObjectView.Items.Add(item);
                }
            }
        }
コード例 #7
0
        public static int?ExtractYear(System.Collections.Generic.IEnumerable <string> words)
        {
            if (words is null)
            {
                return(null);
            }

            System.Collections.Generic.List <int> parsedYears = new System.Collections.Generic.List <int>();

            foreach (string word in words)
            {
                int  year;
                bool successfullyParsed = int.TryParse(word, out year);

                if (successfullyParsed)
                {
                    parsedYears.Add(year);
                }
            }

            System.Collections.Generic.IEnumerable <int> yearsWithValidPriorities = parsedYears.Where(year => GetPriority(year) != 0);

            if (yearsWithValidPriorities.Count() == 0)
            {
                return(null);
            }

            return(yearsWithValidPriorities.OrderByDescending(year => GetPriority(year)).First());
        }
コード例 #8
0
ファイル: Class_Db_Excel.cs プロジェクト: andremoraes/Tracker
        public static System.Array setData(System.Collections.Generic.IEnumerable <System.Data.DataRow> Data, bool expHeader = true)
        {
            int rStart = 1;

            if (!expHeader)
            {
                rStart = 0;
            }
            var data = new object[Data.Count() + rStart, Data.First().Table.Columns.Count];
            int iR   = 0;

            if (expHeader)
            {
                for (int iC = 0; iC < Data.First().Table.Columns.Count; iC++)
                {
                    data[iR, iC] = Data.First().Table.Columns[iC].Caption;
                }
                iR++;
            }
            foreach (DataRow dr in Data)
            {
                for (int iC = 0; iC < Data.First().Table.Columns.Count; iC++)
                {
                    data[iR, iC] = dr.Field <dynamic>(iC);
                }
                iR++;
            }
            return(data);
        }
コード例 #9
0
        static void Main(string[] args)
        {
            int total;
            var repo = new UnitOfWork();

            System.Collections.Generic.IEnumerable <DBEntity.Enviroment> enviroments = repo.Enviroment.All();
            total = enviroments.Count();

            Console.WriteLine($"-- {total} de Ambientes -----------");
            foreach (DBEntity.Enviroment env in enviroments)
            {
                Console.WriteLine($"ID = {env.Id.Value} - Name = {env.Name} - Description = {env.Description}");
            }
            Console.WriteLine("------------------------------------\n");


            System.Collections.Generic.IEnumerable <DBEntity.Level> levels = repo.Level.All();
            total = levels.Count();
            Console.WriteLine($"-- {total} de Níveis --------------");
            foreach (DBEntity.Level level in levels)
            {
                Console.WriteLine($"ID = {level.Id.Value} - Name = {level.Name} - Description = {level.Description}");
            }
            Console.WriteLine("------------------------------------");
            Console.ReadKey();
        }
コード例 #10
0
ファイル: contents.aspx.cs プロジェクト: omeryesil/awapicms
        void PopulateCustomFields(Int64 contentId, Int64?parentContentId)
        {
            System.Collections.Generic.IEnumerable <AWAPI_Data.CustomEntities.ContentCustomField> cstFlds = _customLib.GetFieldList(contentId, true);
            _valueList = null;
            customFieldsList.DataSource = null;

            if (cstFlds != null && cstFlds.Count() > 0)
            {
                var result = from r in cstFlds
                             where r.applyToSubContents == false && r.fieldContentId.Equals(contentId) ||
                             r.applyToSubContents && r.fieldContentId.Equals(parentContentId)
                             orderby r.sortOrder
                             select r;
                customFieldsList.DataSource = result;

                string cultureCode = _culture.SelectedValue.ToLower();
                if (String.IsNullOrEmpty(cultureCode) && !String.IsNullOrEmpty(App_Code.SessionInfo.CurrentSite.cultureCode))
                {
                    cultureCode = App_Code.SessionInfo.CurrentSite.cultureCode.ToLower();
                }

                _valueList = _customLib.GetFieldValueList(contentId, cultureCode);
            }
            customFieldsList.DataBind();
        }
コード例 #11
0
        /// <summary>
        ///		No Metadata Documentation available.
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="imageTypes"></param>
        /// <returns></returns>
        public static Helpers.ActionResult Delete(Helpers.ApiContext apiContext, System.Collections.Generic.IEnumerable <Entities.ImageType> imageTypes)
        {
            // API doesn't allow null parameters. This method requires at least 1 item in the collection.
            if (apiContext == null)
            {
                throw new System.ArgumentNullException("apiContext");
            }
            if (imageTypes == null)
            {
                throw new System.ArgumentNullException("imageTypes");
            }
            if (imageTypes.Count() == 0)
            {
                throw new System.ArgumentOutOfRangeException("imageTypes");
            }

            // Verify user is authorized to perform action, otherwise throw exception.
            Security.SecurityHandler.SetApiContext(apiContext);
            Helpers.ActionResult result = Helpers.ActionResult.Factory(true);
            try
            {
                Model.OrmsContext context = (Model.OrmsContext)apiContext.CurrentContext;
                foreach (Entities.ImageType imageType in imageTypes)
                {
                    OnDeleting(apiContext, imageType);

                    // ATTACH object
                    AttachObject(apiContext, "ImageTypes", imageType);

                    // SET system level properties
                    SetSystemProperties(apiContext, imageType);
                    SetSystemPropertiesModified(apiContext, imageType);

                    // SET SoftDeleted
                    SetDeleted(apiContext, imageType);
                }

                context.SaveChanges();                 // Save Changes
                DetachObjects(apiContext, imageTypes); // Clean ObjectState cache

                foreach (Entities.ImageType imageType in imageTypes)
                {
                    OnDeleted(apiContext, imageType);
                }
            }
            catch (System.Data.OptimisticConcurrencyException ex)
            {
                object forDebugging = ex;
                HandleOptimisticConcurrencyException(apiContext, imageTypes, ex, ref result);
                //throw Helpers.Exceptions.OptimisticConcurrencyException.Factory(ex);
            }
            catch (System.Exception ex)
            {
                object forDebugging = ex;
                throw;    // Helpers.Exceptions.DeleteEntityException.Factory(ex);
            }

            return(result);
        }
コード例 #12
0
 public static string Display <T>(this System.Collections.Generic.IEnumerable <T> o)
 {
     if (o.Count() <= 0)
     {
         return("");
     }
     return(o.Aggregate(" ", (a, b) => a + ", " + b).Substring(2));
 }
コード例 #13
0
        public void GetallRatesReturnsAllRates()
        {
            // Act
            System.Collections.Generic.IEnumerable <Contracts.Models.IRateApplication> result = Data.GetAll($"{StaticStrings.Rates}error").Result;

            // Assert
            result.Count().Should().Be(4);
        }
コード例 #14
0
 public override object GetIndex(Func <object> proceed, object self, System.Collections.Generic.IEnumerable <object> keys)
 {
     if (keys.Count() == 1)
     {
         return(GetMember(proceed, null, System.Convert.ToString(keys.Single())));
     }
     return(proceed());
 }
コード例 #15
0
        static void PerformSubMenu_Evaluation()
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            ConsoleHelper.Print_CenteredTitle("VUI LÒNG CHỌN CHỨC NĂNG DƯỚI ĐÂY:", 100);
            Console.WriteLine("\n" + new string('=', 100));
            Console.WriteLine("1. Đánh giá tất cả các mô hình đã được huấn luyện với kích thước tùy chỉnh");
            Console.WriteLine("    Chương trình sẽ tự động tìm và sử dụng các mô hình đã huấn luyện có định dạng tập tin *.zip:");
            Console.WriteLine("2. Tự chọn một kiến trúc và kích thước tập đánh giá");
            ConsoleHelper.Print_WarningText("Lưu ý: Hình ảnh đã được học nếu đem đi đánh giá sẽ không khách quan, do đó phải sử dụng \nkích thước tập đánh giá = 1 - kích thước tập huấn luyện");
            Console.WriteLine(new string('=', 100));
            Console.ResetColor();
            int function = SelectMenu(2);

            Console.Clear();
            Print_FolderPathPrompt(out string fullImagesetFolderPath, "Nhập đường dẫn đến thư mục có chứa các thư mục tập hình ảnh: ");
            Print_FolderPathPrompt(out string consoleOutputPath, "Nhập đường dẫn đến thư mục sẽ lưu (các) kết quả cửa sổ Console: ");
            Print_FractionPrompt(out float frac, "Nhập số thập phân kích thước tập đánh giá so với tập huấn luyện (= 1 - kích thước tập huấn luyện): ");
            string consoleFileName;

            switch (function)
            {
            case 1:
                Print_FolderPathPrompt(out string outputModelPath, "Nhập đường dẫn đến thư mục đã lưu (các) mô hình đã được huấn luyện: ");
                Console.Clear();
                System.Collections.Generic.IEnumerable <string> foundTrainedModels = Directory.GetFiles(outputModelPath, "*", SearchOption.TopDirectoryOnly).
                                                                                     Where(file => Path.GetExtension(file).Contains("zip", StringComparison.OrdinalIgnoreCase));
                if (foundTrainedModels.Count() == 0)
                {
                    ConsoleHelper.Print_WarningText("Không tìm thấy bất kỳ tập tin *.zip nào trong thư mục này cả");
                    return;
                }
                foreach (string filePath in foundTrainedModels)
                {
                    consoleFileName = $"EvaluationResult_{Path.GetFileName(filePath)}_{DateTime.Now.ToString("HH-mm-ss")}";
                    OutputHelper capturing_1 = new OutputHelper(Path.Combine(consoleOutputPath, consoleFileName + ".txt"));
                    Console.WriteLine($"==================== {Path.GetFileName(filePath)} architecture, {frac} ratio of test set with train set====================");
                    MLTraining mlTraining_1 = new MLTraining(filePath, fullImagesetFolderPath, null, null, frac);
                    mlTraining_1.EvaluateModel();
                    capturing_1.Dispose();
                }
                break;

            case 2:
                Print_FilePathPrompt(out string modelPath, "Nhập đường dẫn đến tập tin mô hình đã được huấn luyện trước: ");
                consoleFileName = $"EvaluationResult_{Path.GetFileName(modelPath)}_{DateTime.Now.ToString("HH-mm-ss")}";
                OutputHelper capturing_2 = new OutputHelper(Path.Combine(consoleOutputPath, consoleFileName + ".txt"));
                Console.WriteLine($"==================== {modelPath} architecture, {frac} ratio of test set with train set====================");
                MLTraining mlTraining_2 = new MLTraining(modelPath, fullImagesetFolderPath, null, null, 1 - frac);
                mlTraining_2.EvaluateModel();
                capturing_2.Dispose();
                break;

            default:
                ConsoleHelper.Print_WarningText("Nhập sai menu, vui lòng nhập lại!");
                break;
            }
            Console.WriteLine("Nhấn phím bất kỳ để quay trở lại...");
        }
コード例 #16
0
ファイル: Repository.cs プロジェクト: dovanduy/CountryTrain
 public virtual System.Collections.Generic.IEnumerable <TEntity> PopulateEntitiesByEntityIds <T>(System.Collections.Generic.IEnumerable <T> entityIds)
 {
     TEntity[] array = new TEntity[entityIds.Count <T>()];
     System.Collections.Generic.Dictionary <object, int> dictionary = new System.Collections.Generic.Dictionary <object, int>();
     for (int i = 0; i < entityIds.Count <T>(); i++)
     {
         TEntity tEntity = this.cacheService.Get <TEntity>(Repository <TEntity> .RealTimeCacheHelper.GetCacheKeyOfEntity(entityIds.ElementAt(i)));
         if (tEntity != null)
         {
             array[i] = tEntity;
         }
         else
         {
             array[i] = default(TEntity);
             dictionary[entityIds.ElementAt(i)] = i;
         }
     }
     if (dictionary.Count > 0)
     {
         System.Collections.Generic.IEnumerable <TEntity> enumerable = this.CreateDAO().FetchByPrimaryKeys <TEntity>(dictionary.Keys);
         foreach (TEntity current in enumerable)
         {
             array[dictionary[current.EntityId]] = current;
             if (Repository <TEntity> .RealTimeCacheHelper.EnableCache && current != null)
             {
                 if (Repository <TEntity> .RealTimeCacheHelper.PropertyNameOfBody != null && Repository <TEntity> .RealTimeCacheHelper.PropertyNameOfBody != null)
                 {
                     Repository <TEntity> .RealTimeCacheHelper.PropertyNameOfBody.SetValue(current, null, null);
                 }
                 this.cacheService.Set(Repository <TEntity> .RealTimeCacheHelper.GetCacheKeyOfEntity(current.EntityId), current, Repository <TEntity> .RealTimeCacheHelper.CachingExpirationType);
             }
         }
     }
     System.Collections.Generic.List <TEntity> list = new System.Collections.Generic.List <TEntity>();
     TEntity[] array2 = array;
     for (int j = 0; j < array2.Length; j++)
     {
         TEntity tEntity2 = array2[j];
         if (tEntity2 != null && !tEntity2.IsDeletedInDatabase)
         {
             list.Add(tEntity2);
         }
     }
     return(list);
 }
コード例 #17
0
ファイル: XMLDocuentAnalyse.cs プロジェクト: daonidedie/-
        /// <summary>
        /// 得到有效的XPath表达式
        /// </summary>
        /// <param name="paths">原始表达式集合</param>
        /// <returns></returns>
        protected string GetValidaXpath(System.Collections.Generic.IEnumerable <Skybot.Collections.Analyse.ExpressionEntity> xPathEntitys)
        {
            //开始对数据进行分析
            if (xPathEntitys.Count() > 0)
            {
                //路径
                List <PathEneity> paths = new List <PathEneity>();
                #region 开始对xpath表达式进行分析

                //循环深度
                for (int Lay = 1; Lay <= xPathEntitys.OrderByDescending(p => p.NodeLayIndex).First().NodeLayIndex; Lay++)
                {
                    //分析当前 节点表达式的值所出现的位置与次数
                    var res = from x in xPathEntitys
                              select new
                    {
                        entity = x,
                        //字符串
                        str = (x.NodeLayIndex >= Lay ? x.NodeArr.ElementAt(Lay) : string.Empty),
                        Lay = Lay
                    };
                    //分组找出最大的那个 做为有效参数
                    var grores = res.Where(p => p.str != string.Empty).
                                 GroupBy(p => p.str).OrderByDescending(p => p.Key.Count());

                    //组总数如果小于0则放弃
                    if (grores.Count() > 0)
                    {
                        if (!(grores.First().Key.Contains("&") || grores.First().Key.Contains("\"")))
                        {
                            //添加到对像中
                            paths.Add(new PathEneity()
                            {
                                Count   = grores.First().Count(),
                                PathStr = grores.First().Key
                            });
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }



                #endregion

                string str = "/" + string.Join("/", paths.Select(p => p.PathStr));
                return(str);
            }
            return(string.Empty);
        }
コード例 #18
0
        public void ListOfExistingVegetablesToSetMinimumQuantityTest()
        {
            refrigerator = new Refrigerator();
            refrigerator.vegetableManager.AddVegetables("Tomato", 2);
            refrigerator.vegetableManager.AddVegetables("Cauliflower", 0);

            System.Collections.Generic.IEnumerable <VegetableQuantity> listOfVegetablesToSetMinimumQuantity = this.refrigerator.vegetableManager.ListOfExistingVegetablesToSetMinimumQuantity();
            Assert.AreEqual(1, listOfVegetablesToSetMinimumQuantity.Count());
        }
コード例 #19
0
ファイル: Guard.cs プロジェクト: triozillion/MyBlog
        /// <summary>
        /// Ensures that the enumerable collection is not null or empty.
        /// </summary>
        /// <param name="object">The enumerable collection to check.</param>
        /// <param name="paramName">The parameter name.</param>
        /// <exception cref="ArgumentNullException">Thrown if the object is null.</exception>
        /// <exception cref="ArgumentException">Thrown if the object is empty.</exception>
        public static void NotNullOrEmpty <T>(System.Collections.Generic.IEnumerable <T> @object, string paramName)
        {
            NotNull(@object, paramName);

            if (@object.Count() == 0)
            {
                throw new System.ArgumentException("Parameter cannot be empty.", paramName);
            }
        }
コード例 #20
0
ファイル: Create.cs プロジェクト: shabi9/CosmosDB
            /// <summary>
            ///     Check uniqueness
            /// </summary>
            /// <param name="title"></param>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public async Task <bool> HasUniqueTitle(string title, CancellationToken cancellationToken)
            {
                ToDoItemSearchSpecification specification = new ToDoItemSearchSpecification(title,
                                                                                            exactSearch: true);

                System.Collections.Generic.IEnumerable <Core.Entities.ToDoItem> entities = await _repo.GetItemsAsync(specification);

                return(entities == null || entities.Count() == 0);
            }
コード例 #21
0
ファイル: ConoHaOperator.cs プロジェクト: krowin24/backuptool
            public System.Collections.Generic.IEnumerable <MyApplication.Objects.ContainerObject> GetContainerObjects(string ContainerName, int?limit = null)
            {
                System.Collections.Generic.IEnumerable <ConoHaNet.Objects.ContainerObject> ObjectList = ConoHa.ListObjects(ContainerName, limit);

                List <MyApplication.Objects.ContainerObject> Result = null;

                if ((ObjectList != null) && ObjectList.Count() > 0)
                {
                    Result = new List <MyApplication.Objects.ContainerObject>(ObjectList.Count());

                    foreach (var entry in ObjectList)
                    {
                        Result.Add(new Objects.ContainerObject(entry.Name, entry.Bytes, entry.Hash, entry.ContentType, entry.LastModified));
                    }
                }

                return(Result);
            }
コード例 #22
0
        private void BeforeQueryStatus(object sender, EventArgs e)
        {
            var button = (OleMenuCommand)sender;

            System.Collections.Generic.IEnumerable <string> files = ProjectHelpers.GetSelectedItemPaths();

            bool isSprite = files.Count() == 1 && Path.GetExtension(files.First()).Equals(Constants.FileExtension, StringComparison.OrdinalIgnoreCase);

            button.Enabled = button.Visible = isSprite;
        }
コード例 #23
0
        /// <summary>
        ///		No Metadata Documentation available.
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="users"></param>
        /// <returns></returns>
        public static Helpers.ActionResult UpdateStatus(Helpers.ApiContext apiContext, System.Collections.Generic.IEnumerable <Entities.User> users)
        {
            // API doesn't allow null parameters. This method requires at least 1 item in the collection.
            if (apiContext == null)
            {
                throw new System.ArgumentNullException("apiContext");
            }
            if (users == null)
            {
                throw new System.ArgumentNullException("users");
            }
            if (users.Count() == 0)
            {
                throw new System.ArgumentOutOfRangeException("users");
            }

            // Verify user is authorized to perform action, otherwise throw exception.
            Security.SecurityHandler.SetApiContext(apiContext);
            Helpers.ActionResult result = Helpers.ActionResult.Factory(true);
            try
            {
                Model.OrmsContext context = (Model.OrmsContext)apiContext.CurrentContext;

                foreach (Entities.User user in users)
                {
                    // ATTACH object
                    AttachObject(apiContext, "Users", user);

                    // SET system level properties
                    SetSystemProperties(apiContext, user);
                    SetSystemPropertiesModified(apiContext, user);

                    // SET IsActive property modified
                    System.Data.Objects.ObjectStateEntry ose = apiContext.CurrentContext.ObjectStateManager.GetObjectStateEntry(user);
                    ose.SetModifiedProperty("IsActive");
                }

                context.SaveChanges();                 // Save Changes
                DetachObjects(apiContext, users);      // Clean ObjectState cache
            }
            catch (System.Data.OptimisticConcurrencyException ex)
            {
                object forDebugging = ex;
                //HandleOptimisticConcurrencyException(apiContext, users, ex, ref result);
                //throw Helpers.Exceptions.OptimisticConcurrencyException.Factory(ex);
                throw;
            }
            catch (System.Exception ex)
            {
                object forDebugging = ex;
                throw;    // Helpers.Exceptions.UpdateEntityException.Factory(ex);
            }

            return(result);
        }
        /// <summary>
        ///		No Metadata Documentation available.
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="product_Service_SubCategoriesList"></param>
        /// <returns></returns>
        public static Helpers.ActionResult Purge(Helpers.ApiContext apiContext, System.Collections.Generic.IEnumerable <Entities.Product_Service_SubCategories> product_Service_SubCategoriesList)
        {
            // API doesn't allow null parameters. This method requires at least 1 item in the collection.
            if (apiContext == null)
            {
                throw new System.ArgumentNullException("apiContext");
            }
            if (product_Service_SubCategoriesList == null)
            {
                throw new System.ArgumentNullException("product_Service_SubCategoriesList");
            }
            if (product_Service_SubCategoriesList.Count() == 0)
            {
                throw new System.ArgumentOutOfRangeException("product_Service_SubCategoriesList");
            }

            // Verify user is authorized to perform action, otherwise throw exception.
            Security.SecurityHandler.SetApiContext(apiContext);
            Helpers.ActionResult result = Helpers.ActionResult.Factory(true);
            try
            {
                Model.OrmsContext context = (Model.OrmsContext)apiContext.CurrentContext;
                foreach (Entities.Product_Service_SubCategories product_Service_SubCategories in product_Service_SubCategoriesList)
                {
                    OnPurging(apiContext, product_Service_SubCategories);

                    // ATTACH object
                    AttachObject(apiContext, "Product_Service_SubCategories", product_Service_SubCategories);

                    // DELETE object
                    context.DeleteObject(product_Service_SubCategories);
                }

                context.SaveChanges();                 // Save Changes

                foreach (Entities.Product_Service_SubCategories product_Service_SubCategories in product_Service_SubCategoriesList)
                {
                    OnPurged(apiContext, product_Service_SubCategories);
                }
            }
            catch (System.Data.OptimisticConcurrencyException ex)
            {
                object forDebugging = ex;
                HandleOptimisticConcurrencyException(apiContext, product_Service_SubCategoriesList, ex, ref result);
                //throw Helpers.Exceptions.OptimisticConcurrencyException.Factory(ex);
            }
            catch (System.Exception ex)
            {
                object forDebugging = ex;
                throw;    // Helpers.Exceptions.DeleteEntityException.Factory(ex);
            }

            return(result);
        }
コード例 #25
0
        private System.String GetLastedDateTime(System.Collections.Generic.IEnumerable <System.String> DirectoryNames, string Format)
        {
            if (DirectoryNames is null)
            {
                return(null);
            }
            if (string.IsNullOrEmpty(Format))
            {
                return(null);
            }

            // 最新日付(最小値で初期化)
            System.DateTime First = DateTime.MinValue;

            // コレクションの中身が1個もなければ、なにもしない。
            if (DirectoryNames.Count() > 0)
            {
                // 比較用の日付リスト
                List <System.DateTime> DateList = new List <DateTime>(DirectoryNames.Count());

                // 文字列を日付に変換して格納
                foreach (var entry in DirectoryNames)
                {
                    DateList.Add(System.DateTime.ParseExact(entry, Format, null));
                }

                // 最初は適当に代入。
                First = DateList[0];

                // 日付比較と最新日付の代入。
                foreach (var entry in DateList)
                {
                    if (First < entry)
                    {
                        First = entry;
                    }
                }
            }

            return((First == DateTime.MinValue) ? null : First.ToString(Options.SavedataFormat));
        }
コード例 #26
0
        /// <summary>
        ///	No Metadata Documentation available.
        /// </summary>
        /// <param name="apiContext"></param>
        /// <param name="imageTypes"></param>
        /// <param name="clientWins">if true system properties will not be overwritten by Api</param>
        /// <returns></returns>
        public static Helpers.ActionResult Add(Helpers.ApiContext apiContext, System.Collections.Generic.IEnumerable <Entities.ImageType> imageTypes, System.Boolean clientWins)
        {
            // API doesn't allow null parameters. This method requires at least 1 item in the collection.
            if (apiContext == null)
            {
                throw new System.ArgumentNullException("apiContext");
            }
            if (imageTypes == null)
            {
                throw new System.ArgumentNullException("imageTypes");
            }
            if (imageTypes.Count() == 0)
            {
                throw new System.ArgumentOutOfRangeException("imageTypes");
            }

            // Verify user is authorized to perform action, otherwise throw exception.
            Security.SecurityHandler.SetApiContext(apiContext);

            Helpers.ActionResult result = Helpers.ActionResult.Factory(true);

            try
            {
                Model.OrmsContext context = (Model.OrmsContext)apiContext.CurrentContext;
                foreach (Entities.ImageType imageType in imageTypes)
                {
                    if (!clientWins)
                    {
                        // SET system level properties
                        SetSystemProperties(apiContext, imageType, false);
                    }

                    // ADD to context
                    OnAdding(apiContext, imageType);
                    context.AddObject("ImageTypes", imageType);
                }

                context.SaveChanges();                 // Save Changes
                DetachObjects(apiContext, imageTypes); // Clean ObjectState cache

                foreach (Entities.ImageType imageType in imageTypes)
                {
                    OnAdded(apiContext, imageType);
                }
            }
            catch (System.Exception ex)
            {
                object forDebugging = ex;
                throw;                // Helpers.Exceptions.AddEntityException.Factory(ex);
            }

            return(result);
        }
コード例 #27
0
        internal T[] ToFactoryObjectItems <T>(System.Collections.Generic.IEnumerable <InspectableAdapter> items)
        {
            T[] adapterItems = new T[items.Count()];
            int index        = 0;

            foreach (var item in items)
            {
                adapterItems[index] = ToFactoryObject(item).AssertCast <T>();
                ++index;
            }
            return(adapterItems);
        }
コード例 #28
0
        public ActionResult Index(string[] includedTags, string monthYearPair = "")
        {
            System.Collections.Generic.IEnumerable <IJournalEntry> validEntries    = Enumerable.Empty <IJournalEntry>();
            System.Collections.Generic.IEnumerable <IJournalEntry> filteredEntries = Enumerable.Empty <IJournalEntry>();
            ApplicationUser user = null;

            if (User.Identity.IsAuthenticated)
            {
                user = UserManager.FindById(User.Identity.GetUserId());
                StaffRank userRank = user.GetStaffRank(User);
                validEntries = TemplateCache.GetAll <IJournalEntry>().Where(blog => blog.IsPublished() && (blog.Public || blog.MinimumReadLevel <= userRank));
            }
            else
            {
                validEntries = TemplateCache.GetAll <IJournalEntry>().Where(blog => blog.IsPublished() && blog.Public);
            }

            System.Collections.Generic.IEnumerable <string> allTags = validEntries.SelectMany(blog => blog.Tags).Distinct();
            if (includedTags != null && includedTags.Count() > 0)
            {
                validEntries = validEntries.Where(blog => blog.Tags.Any(tag => includedTags.Contains(tag)));
            }

            if (!string.IsNullOrWhiteSpace(monthYearPair))
            {
                string[] pair  = monthYearPair.Split("|||", StringSplitOptions.RemoveEmptyEntries);
                string   month = pair[0];
                int      year  = -1;

                if (!string.IsNullOrWhiteSpace(month) && int.TryParse(pair[1], out year))
                {
                    filteredEntries = validEntries.Where(blog =>
                                                         month.Equals(blog.PublishDate.ToString("MMMM", CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase) &&
                                                         blog.PublishDate.Year.Equals(year));
                }
            }

            if (filteredEntries.Count() == 0)
            {
                filteredEntries = validEntries;
            }

            BlogViewModel vModel = new BlogViewModel(filteredEntries.OrderByDescending(obj => obj.PublishDate))
            {
                AuthedUser     = user,
                MonthYearPairs = validEntries.Select(blog => new Tuple <string, int>(blog.PublishDate.ToString("MMMM", CultureInfo.InvariantCulture), blog.PublishDate.Year)).Distinct(),
                IncludeTags    = includedTags?.Where(tag => tag != "false").ToArray() ?? (new string[0]),
                AllTags        = allTags.ToArray()
            };

            return(View(vModel));
        }
コード例 #29
0
        public override string FormatCondition(Simulation simulation)
        {
            string text = Localization;

            if (string.IsNullOrEmpty(text))
            {
                text = LocalizationManager.Current.Simulation["Quest"].Translate("Default_Condition_Item");
            }

            System.Collections.Generic.IEnumerable <Simulation.Item> found = simulation.Items.Where(d => d.ID == ID);

            return(string.Format(text, found.Count(), Amount, ID));
        }
コード例 #30
0
 public void LoadData()
 {
     System.Collections.Generic.IEnumerable <CMS.Article> it = ListArticle.Take(Number);
     if (it.Count() > 0)
     {
         CMS.Article article = it.Take(1).Single();
         ArticleId              = article.Id.ToString();
         ArticleName            = article.Name;
         ArticleDescription     = article.GetDescription();
         rptTabTopic.DataSource = it.Skip(1);
         rptTabTopic.DataBind();
     }
 }