public void Enter(Categories category, Layers layer, string className, string methodName, string message, string inArgs)
 {
     if (IsEnabled())
     {
         WriteEvent(EventIds.MethodStart, category, layer, className, methodName, message, inArgs);
     }
 }
Example #2
0
    /// <summary>
    /// AddCategory checks if the category name is not in use, if not in use it adds a new category
    /// </summary>
    /// <param name="category"></param>
    /// <returns></returns>
    public static string AddCategory(Categories category)
    {
        string query = string.Format("SELECT COUNT(*) FROM categories WHERE name = '{0}'", category.Name);
        command.CommandText = query;

        try
        {
            conn.Open();
            int amountOfCategorys = (int)command.ExecuteScalar();

            if (amountOfCategorys < 1)      // Check if category does NOT exist
            {
                // Category does NOT exists, create a new category
                query = string.Format(@"INSERT INTO categories VALUES ('{0}')", category.Name);
                command.CommandText = query;
                command.ExecuteNonQuery();
                return "Categorie toegevoegd!";
            }
            else        // Category exists, return error message
            {
                return "Deze categorie bestaat al, categorie niet toegevoegd.";
            }
        }
        finally
        {
            conn.Close();
            command.Parameters.Clear();
        }
    }
Example #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        dbOps = DBOperations.Instance;
        links = Links.Instance;
        general = General.Instance;
        gui = GUIVariables.Instance;
        categories = Categories.Instance;
        engine = ProcessingEngine.Instance;
        imageEngine = ImageEngine.Instance;
        tagger = Tagger.Instance;
        log = Logger.Instance;

        seperator = gui.Seperator;

        //  QueryString Param Names.
        //  ratingID
        //  value

        string iid = string.Empty;
        string value = string.Empty;

        #region CookieAlreadyExists
        //  START: If a getputsCookie with the Username already exists, do not show the Login Page.

        if (Request.Cookies["getputsCookie"] != null)
        {
            HttpCookie getputsCookie = Request.Cookies["getputsCookie"];
            UID = dbOps.Decrypt(getputsCookie["UID"].ToString().Trim());
        }
        if (string.IsNullOrEmpty(UID))
        {

        }
        else
        {

        }
        //  END: If a getputsCookie with the Username already exists, do not show the Login Page.
        #endregion CookieAlreadyExists

        if (Request.QueryString != null && Request.QueryString.Count > 0)
        {
            //  ratingID is the Item IID.
            if (!string.IsNullOrEmpty(Request.QueryString["ratingID"]))
            {
                iid = Request.QueryString["ratingID"];
            }
            //  Value is the Rating given by the user. Value: [0, 1, 2, 3, 4]. So add +1 so as to convert Value: [1, 2, 3, 4, 5]
            if (!string.IsNullOrEmpty(Request.QueryString["value"]))
            {
                int intValue = -1;
                value = int.TryParse(Request.QueryString["value"], out intValue) ? (intValue + 1).ToString() : "-1";
            }
        }

        if (!string.IsNullOrEmpty(UID) && !string.IsNullOrEmpty(iid) && !string.IsNullOrEmpty(value))
        {
            UpdateRatings(UID, iid, value);
        }
    }
 public TraceCallGraphAspect(Categories category, Layers layer, CallFlowType flowType=CallFlowType.Layer, bool logCallStack=false)
 {
     this.Category = category;
     this.Layer = layer;
     this.FlowType = flowType;
     this.LogCallStack = logCallStack;
 }
 public void Exit(Categories category, Layers layer, string className, string methodName, string message, string outArgs, long? elapsedMiliSeconds)
 {
     if (IsEnabled())
     {
         WriteEvent(EventIds.MethodEnd, category, layer, className, methodName, message, outArgs, elapsedMiliSeconds);
     }
 }
Example #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        links = Links.Instance;
        gui = GUIVariables.Instance;
        dbOps = DBOperations.Instance;
        categories = Categories.Instance;
        log = Logger.Instance;
        engine = ProcessingEngine.Instance;
        general = General.Instance;
        imageEngine = ImageEngine.Instance;

        seperator = gui.Seperator;

        if (string.IsNullOrEmpty(Request.QueryString["UID"]))
        {

        }
        else
        {
            queryStringUID = Request.QueryString["UID"].Trim().ToLower();
        }

        if (string.IsNullOrEmpty(queryStringUID))
        {

        }
        else
        {
            LoadComments(queryStringUID);
        }
    }
        public ActionResult Add(string catTitle = "", int parentID = 0, string image = "", int isLifestyle = 0, string shortDesc = "", string longDesc = "", bool vehicleSpecific = false)
        {
            // Save the category
            List<string> error_messages = new List<string>();
            Categories cat = new Categories();
            try {
                cat = ProductCat.SaveCategory(0, catTitle, parentID, image, isLifestyle, shortDesc, longDesc, vehicleSpecific);
            } catch (Exception e) {
                error_messages.Add(e.Message);
            }

            // Make sure we didn't catch any errors
            if (error_messages.Count == 0 && cat.catID > 0) {
                return RedirectToAction("Index");
            } else {
                ViewBag.catTitle = catTitle;
                ViewBag.parentID = parentID;
                ViewBag.image = image;
                ViewBag.isLifestyle = isLifestyle;
                ViewBag.shortDesc = shortDesc;
                ViewBag.longDesc = longDesc;
                ViewBag.vehicleSpecific = vehicleSpecific;
                ViewBag.error_messages = error_messages;
            }

            // Get the categories so this category can make the new one a subcategory if they choose
            List<DetailedCategories> cats = ProductCat.GetCategories();
            ViewBag.cats = cats;

            return View();
        }
Example #8
0
    /// <summary> 
    /// This function is used to get all the available
    /// categories of possible events
    /// </summary>
    /// <param name="key">Key required to make the API call</param>
    /// <returns>JSON in String Format containing all categories</returns> 
    public string GetCategories(string key)
    {
        String outputString = "";
        int count = 0;
        Category category = null;
        Categories categories = new Categories();
        using (WebClient wc = new WebClient())
        {

            string xml = wc.DownloadString("http://api.evdb.com/rest/categories/list?app_key=" + key);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList root = doc.GetElementsByTagName("category");
            count = root.Count;
            string json = JsonConvert.SerializeXmlNode(doc);
            JObject obj = JObject.Parse(json);
            int temp = 0;
            while (temp < count)
            {
                category = new Category();
                category.categoryID = (string)obj["categories"]["category"][temp]["id"];
                category.categoryName = (string)obj["categories"]["category"][temp]["name"];
                categories.categories.Add(category);
                temp++;
            }
            outputString = JsonConvert.SerializeObject(categories);
        }
        return outputString;
    }
        public void GetWordShouldWorkPropperlyWhenValidInput(Categories category)
        {
            var word = this.wordFactory.GetWord(category);

            Assert.IsNotNull(word);
            Assert.IsNotNull(word.Content);
        }
        public ViewResult Search(string name, Categories? categoty)
        {
            var lista = _business.GetActiveProducts();

            var model = new ProductList();

            if(lista != null)
            {
                if (!String.IsNullOrEmpty(name) && categoty != null)
                    model.Products =
                        lista.Where(
                            x =>
                            ((!String.IsNullOrEmpty(name) && x.Name.ToLower().Contains(name.ToLower())) && (x.Category.Equals(categoty)))).
                            Select(x => new Models.Product.Product().InjectFrom(x)).Cast<Models.Product.Product>().ToList();
                else if (!String.IsNullOrEmpty(name))
                    model.Products =
                        lista.Where(x => !String.IsNullOrEmpty(name) && x.Name.ToLower().Contains(name.ToLower())).Select(
                            x => new Models.Product.Product().InjectFrom(x)).Cast<Models.Product.Product>().ToList();
                else if (categoty != null)
                    model.Products =
                        lista.Where(x => x.Category.Equals(categoty)).Select(x => new Models.Product.Product().InjectFrom(x)).Cast
                            <Models.Product.Product>().ToList();
                else
                    model.Products = lista.Select(x => new Models.Product.Product().InjectFrom(x)).Cast<Models.Product.Product>().ToList();
            }
            else
            {
                model.Products = new List<Models.Product.Product>();
            }

            return View("Index",model);
        }
Example #11
0
 public AllDemoMVCBLL()
 {
     Categories = new Categories();
     Logins = new Logins();
     SubCategories = new SubCategories();
     Receipies = new Receipies();
 }
        public void Track(Categories category, string action, string label = null, int value = 0)
        {
            if (!_disabled)
                _tracker.TrackEventAsync(category.ToString(), action, label, value);

                System.Diagnostics.Debug.WriteLine("Analytics: {0}/{1}/{2}/{3}", category.ToString(), action, label, value);
        }
		public void TimeMethod(decimal elapsedMiliSeconds, Categories category, Layers layer)
		{
			if (IsEnabled())
			{
				WriteEvent(EventIds.TimeMethod, elapsedMiliSeconds, category, layer);
			}
		}
Example #14
0
 public static int ContainsCategory(Categories category, Categories find)
 {
     if ((category & find) == find)
         return 1;
     else
         return 0;
 }
Example #15
0
 public Project()
 {
     _UUID = System.Guid.NewGuid();
     timeline = new List<Play>();
     Categories = new Categories();
     LocalTeamTemplate = new TeamTemplate();
     VisitorTeamTemplate = new TeamTemplate();
 }
        public async Task TrackAsync(Categories category, string action, string label = null, int value = 0) 
        {
            System.Diagnostics.Debug.WriteLine("Analytics: Async: {0}/{1}/{2}/{3}", category.ToString(), action, label, value);
            
            if (!_disabled)
                await _tracker.TrackEventAsync(category.ToString(), action, label, value);

        }
 public Demographic(int turn, Categories category, float value, float average, int rank)
 {
     Turn = turn;
     Category = category;
     Value = value;
     Average = average;
     Rank = rank;
 }
        public void AddCategory(Categories category)
        {
            healthTrackerDB.categories.InsertOnSubmit(category);
            healthTrackerDB.SubmitChanges();

            //update UI
            LoadCategories();
        }
        public void VerifyAddEditFormCreateCategory()
        {
            CategoryFacade facade = new CategoryFacade();
            Categories category = new Categories("Category", "20");

            facade.AddCategory(category);

            facade.AssertCategoryExist(category);
        }
Example #20
0
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            Registry.CurrentUser.CreateSubKey(@"Software\WallpaperChanger");
            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\WallpaperChanger", true);

            object objCategories = key.GetValue(@"Categories");

            if (objCategories == null)
                categories = Categories.General | Categories.Anime | Categories.HDR;
            else
            {
                try
                {
                    categories = (Categories)Convert.ToByte(objCategories.ToString());
                }
                catch (FormatException)
                {
                    categories = Categories.General | Categories.Anime | Categories.HDR;
                }
            }

            object objPurity = key.GetValue(@"Purity");

            if (objPurity == null)
                purity = Purity.Clean;
            else
            {
                try
                {
                    purity = (Purity)Convert.ToByte(objPurity.ToString());
                }
                catch (FormatException)
                {
                    purity = Purity.Clean;
                }
            }

            try
            {
                SetWallpaper();
            }
            catch (Exception e)
            {
                string errorMessage = String.Format("Fatal error: {0}", e.ToString());

                // Пишем в лог...
                if (!EventLog.SourceExists(logSource))
                    EventLog.CreateEventSource(logSource, "Application");

                EventLog.WriteEntry(logSource, errorMessage, EventLogEntryType.Warning);

                // ...и в консоль
                Console.WriteLine(errorMessage);
            }
        }
Example #21
0
 private bool Excluded(ITestMethodInfo testMethod) {
    if(_excludedCategories.IsEmpty) {
       return false;
    }
    var local = new Categories();
    local.Add(testMethod.Categories);
    local.Add(testMethod.InheritedCategories);
    return local.Intersect(_excludedCategories).Count > 0;
 }
Example #22
0
 /// <summary>
 /// This method adds a child to a specific category.
 /// </summary>
 /// <param name="category">MUSIC or IMAGES or VIDEOS or EBOOKS or OTHERS</param>
 /// <param name="childValue">string-value</param>
 public void addChildToCategory(Categories category, String childValue)
 {
     XmlNode node = root.SelectSingleNode(category.ToString());
     int childAmount = node.ChildNodes.Count;
     XmlNode nChild = this.xmldoc.CreateElement("value" + childAmount);
     nChild.InnerText = childValue;
     //nChild.
     node.AppendChild(nChild);
 }
Example #23
0
 static TypeResolver CreateResolverObject(Type orType, Categories cat, Type genericType, params Type[] genericArgs)
 {
     var type = genericType.MakeGenericType(genericArgs);
     var ctor = type.GetConstructor(Type.EmptyTypes);
     var obj = ctor.Invoke(emptyObjects);
     var res=(TypeResolver)obj;
     res.Category = cat;
     res.Type = orType;
     return res;
 }
Example #24
0
        /// <summary>
        /// Creates an instance of this class with the required category and sub category.
        /// </summary>
        /// <param name="category">Selected category</param>
        /// <param name="subCategory">Selected sub category</param>
        /// <history>
        /// [Curtis_Beard]	   10/31/2014	ADD: exclusions update
        /// </history>
        public FilterType(Categories category, SubCategories subCategory)
        {
            cat = category;
             subcat = subCategory;

             switch (subcat)
             {
            case SubCategories.Name:
            case SubCategories.Path:
               valuetype = ValueTypes.String;
               supportedValueOptions = new List<ValueOptions>() { ValueOptions.Equals, ValueOptions.Contains, ValueOptions.StartsWith, ValueOptions.EndsWith };
               supportsIgnoreCase = true;
               supportsMulitpleItems = true;
               break;

            case SubCategories.Hidden:
            case SubCategories.System:
            case SubCategories.ReadOnly:
            case SubCategories.Binary:
               valuetype = ValueTypes.Null;
               supportedValueOptions = new List<ValueOptions>() { ValueOptions.None };
               supportsIgnoreCase = false;
               supportsMulitpleItems = false;
               break;

            case SubCategories.DateModified:
            case SubCategories.DateCreated:
               valuetype = ValueTypes.DateTime;
               supportedValueOptions = new List<ValueOptions>() { ValueOptions.Equals, ValueOptions.NotEquals, ValueOptions.GreaterThan, ValueOptions.GreaterThanEquals, ValueOptions.LessThan, ValueOptions.LessThanEquals };
               supportsIgnoreCase = false;
               supportsMulitpleItems = true;
               break;

            case SubCategories.Extension:
               valuetype = ValueTypes.String;
               supportedValueOptions = new List<ValueOptions>() { ValueOptions.None };
               supportsIgnoreCase = false;
               supportsMulitpleItems = true;
               break;

            case SubCategories.Size:
               valuetype = ValueTypes.Size;
               supportedValueOptions = new List<ValueOptions>() { ValueOptions.Equals, ValueOptions.NotEquals, ValueOptions.GreaterThan, ValueOptions.GreaterThanEquals, ValueOptions.LessThan, ValueOptions.LessThanEquals };
               supportsIgnoreCase = false;
               supportsMulitpleItems = true;
               break;

            case SubCategories.MinimumHitCount:
               valuetype = ValueTypes.Long;
               supportedValueOptions = new List<ValueOptions>() { ValueOptions.None };
               supportsIgnoreCase = false;
               supportsMulitpleItems = false;
               break;
             }
        }
        public GallerySearchOption(string keyword, int? page, Categories category)
        {
            this.Keyword = keyword;
            this.Page = page;
            this.Category = category;

            this.SearchGalleryName = true;
            this.SearchGalleryTags = true;
            this.SearchTorrentFileNames = true;
            this.SearchLowPowerTags = true;
        }
 public void Enter(Categories category, Layers layer, string className, string methodName, string message, string inArgs)
 {
     Trace.WriteLine(string.Format("{0}-{1}: {2}.{3}\n\t{4}", category, layer, className, methodName, message));
     if (!string.IsNullOrEmpty(inArgs))
     {
         Trace.WriteLine(string.Format("\tinput: {0}", inArgs));
     }
     else
     {
         Trace.WriteLine("\tinput: null");
     }
 }
Example #27
0
        public TaggerDialog(Play play,
		                    Categories categoriesTemplate,
		                    TeamTemplate localTeamTemplate,
		                    TeamTemplate visitorTeamTemplate,
		                    bool showAllSubcategories)
        {
            this.Build();

            firstExpose = false;
            tagsnotebook.Visible = false;

            this.localTeamTemplate = localTeamTemplate;
            this.visitorTeamTemplate = visitorTeamTemplate;

            taggerwidget1.SetData(categoriesTemplate, play,
                                  localTeamTemplate.TeamName,
                                  visitorTeamTemplate.TeamName);
            playersnotebook.Visible = false;

            /* Iterate over all subcategories, adding a widget only for the FastTag ones */
            foreach (var subcat in play.Category.SubCategories) {
                if (!subcat.FastTag && !showAllSubcategories)
                    continue;
                if (subcat is TagSubCategory) {
                    var tagcat = subcat as TagSubCategory;
                    AddTagSubcategory(tagcat, play.Tags);
                } else if (subcat is PlayerSubCategory) {
                    playersnotebook.Visible = false;
                    hbox.SetChildPacking(tagsnotebook, false, false, 0, Gtk.PackType.Start);
                    var tagcat = subcat as PlayerSubCategory;
                    AddPlayerSubcategory(tagcat, play.Players);
                } else if (subcat is TeamSubCategory) {
                    var tagcat = subcat as TeamSubCategory;
                    AddTeamSubcategory(tagcat, play.Teams,
                                       localTeamTemplate.TeamName,
                                       visitorTeamTemplate.TeamName);
                }
            }

            if (!play.Category.TagFieldPosition && !play.Category.TagHalfFieldPosition && !play.Category.TagGoalPosition) {
                coordstagger.Visible = false;
                (mainvbox[hbox] as Gtk.Box.BoxChild).Expand = true;
            } else {
                coordstagger.LoadBackgrounds (categoriesTemplate.FieldBackground,
                                              categoriesTemplate.HalfFieldBackground,
                                              categoriesTemplate.GoalBackground);
                coordstagger.LoadPlay (play);
            }

            if (subcategoryAdded || playersnotebook.Visible) {
                tagsnotebook.Visible = true;
            }
        }
Example #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        links = Links.Instance;
        gui = GUIVariables.Instance;
        dbOps = DBOperations.Instance;
        categories = Categories.Instance;
        log = Logger.Instance;
        engine = ProcessingEngine.Instance;

        WriteRSSFile();
        Response.Redirect(links.RssFeedLink, false);
    }
Example #29
0
 //
 public static Categories ReadCategories()
 {
     Categories categories = null;
     try
     {
         categories = UTF8XmlSerializer.Deserialize<Categories>(File.ReadAllText(CATEGORIES_ARCHIVE_FILE));
     }
     catch (Exception ex)
     {
         categories = new Categories();
         Logger.Error("DataAccess ReadCategories Error", ex);
     }
     return categories;
 }
        /// <summary>
        /// If button save is clicked, try to save the new category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            // Create a new category
            Categories category = new Categories(txtName.Text);

            // Save the category and return a result message
            lblResult.Text = ConnectionClass.AddCategory(category);

            // If category is added -> ClearTextFields
            if (lblResult.Text == "Categorie toegevoegd!")
            {
                ClearTextFields();
            }
        }
Example #31
0
        public static void Initial(DBContent content)
        {
            if (!content.Category.Any())
            {
                content.Category.AddRange(Categories.Select(c => c.Value));
            }
            if (!content.Phone.Any())
            {
                content.AddRange(
                    new Phone
                {
                    name        = "Samsung S10",
                    description = "Best phone by Samsung",
                    img         = "/img/samsung_galaxy_s10_6_128_gb_white.jpg",
                    price       = 23000,
                    Category    = Categories["Flagman"]
                },
                    new Phone
                {
                    name        = "Nokia 3310",
                    description = "Old but gold",
                    img         = "/img/nokia3310.jpg",
                    price       = 700,
                    Category    = Categories["Flagman"]
                }
                    );
            }

            if (!content.CategoryMotherboarddd.Any())
            {
                content.CategoryMotherboarddd.AddRange(CategoriesMotherboard.Select(c => c.Value));
            }
            if (!content.Motherboard.Any())
            {
                content.AddRange(
                    new Motherboard
                {
                    name                = "MSI MEG X570 Ace",
                    description         = "(sAM4, AMD X570, PCI-Ex16)",
                    img                 = "/img/MSI MEG X570 Ace.jpg",
                    price               = 11250,
                    CategoryMotherboard = CategoriesMotherboard["Hard and strong"]
                },
                    new Motherboard
                {
                    name                = "Asus Prime H310M-E R2.0",
                    description         = "(s1151, Intel H310, PCI-Ex16)",
                    img                 = "/img/Asus Prime H310M-E R2.0.jpg",
                    price               = 1589,
                    CategoryMotherboard = CategoriesMotherboard["Budget"]
                },
                    new Motherboard
                {
                    name                = "Asus Prime X570-Pro",
                    description         = "(sAM4, AMD X570, PCI-Ex16)",
                    img                 = "/img/Asus Prime X570-Pro.jpg",
                    price               = 6909,
                    CategoryMotherboard = CategoriesMotherboard["Hard and strong"]
                },
                    new Motherboard
                {
                    name                = "Asus Prime A320M-K",
                    description         = "(sAM4, AMD A320, PCI-Ex16)",
                    img                 = "/img/Asus Prime A320M-K.jpg",
                    price               = 1310,
                    CategoryMotherboard = CategoriesMotherboard["Budget"]
                },
                    new Motherboard
                {
                    name                = "MSI MPG X570 Gaming Pro Carbon Wi-Fi",
                    description         = "(sAM4, AMD X570, PCI-Ex16)",
                    img                 = "/img/MSI MPG X570 Gaming Pro Carbon Wi-Fi.jpg",
                    price               = 6996,
                    CategoryMotherboard = CategoriesMotherboard["Hard and strong"]
                }
                    );
            }
            content.SaveChanges();
        }
Example #32
0
        private void Recreate()
        {
            Categories.Clear();
            Categories.Add(new Category(_environment == Map.Environment.Inside ? "General" : "Water",
                                        _environment == Map.Environment.Inside ? "editor/tilemenu/general.png" : "editor/tilemenu/water.png"));
            Categories.Last().Objects.Add(WaterTiles.DeepWaterOrVoid);
            Categories.Last().Objects.Add(WaterTiles.ShallowWater);

            Categories.Add(new Category("Ground", "editor/tilemenu/ground.png"));
            Categories.Last().Objects.Add(GroundTiles.Grass);
            Categories.Last().Objects.Add(GroundTiles.Dirt);
            Categories.Last().Objects.Add(GroundTiles.Stone);
            Categories.Last().Objects.Add(GroundTiles.StoneDarker);
            Categories.Last().Objects.Add(GroundTiles.Gravel);

            Categories.Add(new Category("Foliage", "editor/tilemenu/foliage.png"));
            Categories.Last().Objects.Add(FoliageTiles.Tree);
            Categories.Last().Objects.Add(FoliageTiles.Birch);
            Categories.Last().Objects.Add(FoliageTiles.Bush);
            Categories.Last().Objects.Add(FoliageTiles.TallGrass);
            Categories.Last().Objects.Add(FoliageTiles.Rock);

            Categories.Add(new Category("City", "editor/tilemenu/city.png"));

            Category walls = new Category("Wall", "");

            walls.Objects.Add(CityTiles.Wall);
            walls.Objects.Add(CityTiles.WallOak);
            walls.Objects.Add(CityTiles.WallRed);
            walls.Objects.Add(CityTiles.WallEbony);
            walls.Objects.Add(CityTiles.Bricks);
            walls.Objects.Add(CityTiles.StoneBricks);
            walls.Objects.Add(Separator);
            walls.Objects.Add(CityTiles.WallBeam);
            Categories.Last().Objects.Add(walls);

            Category roofs = new Category("Roof", "");

            roofs.Objects.Add(CityTiles.RoofBlue);
            roofs.Objects.Add(CityTiles.RoofOrange);
            roofs.Objects.Add(CityTiles.RoofRed);
            roofs.Objects.Add(CityTiles.RoofPurple);
            roofs.Objects.Add(Separator);
            roofs.Objects.Add(CityTiles.RoofPurpleTip);
            roofs.Objects.Add(CityTiles.RoofBeam);
            Categories.Last().Objects.Add(roofs);

            Category windows = new Category("Window", "");

            windows.Objects.Add(CityTiles.WindowBlue);
            windows.Objects.Add(CityTiles.WindowOrange);
            windows.Objects.Add(CityTiles.WindowRed);
            windows.Objects.Add(CityTiles.WindowPurple);
            windows.Objects.Add(Separator);
            windows.Objects.Add(CityTiles.WindowBlinds);
            windows.Objects.Add(CityTiles.WindowStone);
            Categories.Last().Objects.Add(windows);

            Categories.Last().Objects.Add(CityTiles.HouseStairs);
            Categories.Last().Objects.Add(CityTiles.Door);
            Categories.Last().Objects.Add(CityTiles.DoorStone);

            Categories.Last().Objects.Add(Separator);

            Categories.Last().Objects.Add(CityTiles.Road);
            Categories.Last().Objects.Add(CityTiles.Sign);
            Categories.Last().Objects.Add(CityTiles.Waterwheel);

            Categories.Add(new Category("Inside", "editor/tilemenu/inside.png"));
            Categories.Last().Objects.Add(InsideTiles.Floor);
            Categories.Last().Objects.Add(InsideTiles.Wall);
            Categories.Last().Objects.Add(InsideTiles.Panel);

            Categories.Last().Objects.Add(Separator);

            Categories.Last().Objects.Add(InsideTiles.Door);
            Categories.Last().Objects.Add(InsideTiles.Doormat);

            Categories.Last().Objects.Add(Separator);
            Categories.Last().Objects.Add(InsideTiles.Bookshelf);
            Categories.Last().Objects.Add(InsideTiles.Chair);
            Categories.Last().Objects.Add(InsideTiles.Table);

            Categories.Add(new Category("Control", "editor/tilemenu/control.png"));
            Categories.Last().Objects.Add(ControlTiles.Spawnpoint);
            Categories.Last().Objects.Add(ControlTiles.MapPortal);
            Categories.Last().Objects.Add(Separator);
            Categories.Last().Objects.Add(ControlTiles.TextBox);
            Categories.Last().Objects.Add(Separator);
            Categories.Last().Objects.Add(ControlTiles.Barrier);
            Categories.Last().Objects.Add(ControlTiles.InvertedBarrier);

            Categories.Add(new Category("NPCs", "editor/tilemenu/npcs.png"));

            Category animals = new Category("Animals", "");

            animals.Objects.Add(NPCs.Pig.TileTemplate);
            animals.Objects.Add(NPCs.GreenPig.TileTemplate);

            Categories.Last().Objects.Add(animals);

            SelectedTile = WaterTiles.DeepWaterOrVoid;

            TotalArea = new Vector2(0, 0);

            // icons
            TotalArea.X += 18 + 10;

            foreach (Category category in Categories)
            {
                Point measure = CalculateCategorySize(category, true);
                TotalArea.X  = Math.Max(18 + 10 + measure.X + 40, TotalArea.X);
                TotalArea.Y += measure.Y;
            }

            TotalArea.X += 16;

            Rectangle.TweenTo(new Rectangle(Rectangle.TargetValue.X, Rectangle.TargetValue.Y, (int)TotalArea.X, Rectangle.TargetValue.Height), TweenEaseType.Linear, 0);
        }
 public async Task <int> AddNewCategory(Categories newCategory)
 {
     return(await App.Database.SaveCategoryAsync(newCategory));
 }
Example #34
0
 // Loads categories from database.
 public void LoadCategories()
 {
     Categories.Clear();
     Context.Load(Context.GetCategoriesQuery(), GetCategoriesQueryCallback, null);
 }
Example #35
0
        public static Video constructVideo(string Title, string Description, string[] tags, Categories category, string PrivacyStatus)
        {
            var video = new Video();

            video.Snippet             = new VideoSnippet();
            video.Snippet.Title       = Title;
            video.Snippet.Description = Description;
            video.Snippet.Tags        = tags;
            video.Snippet.CategoryId  = ((int)category).ToString(); // See https://developers.google.com/youtube/v3/docs/videoCategories/list ---> Find ich nicht
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = PrivacyStatus;             // or "private" or "public
            return(video);
        }
Example #36
0
        private void FillDummyData()
        {
            Categories.Add(new Category()
            {
                Id    = 1,
                Name  = "Dairy",
                Order = 1
            });

            Categories.Add(new Category()
            {
                Id           = 2,
                MainCategory = 1,
                Name         = "Milks",
                Order        = 1
            });

            Categories.Add(new Category()
            {
                Id           = 3,
                MainCategory = 1,
                Name         = "Cheeses",
                Order        = 0
            });

            ProductTypes.Add(new ProductType()
            {
                Id          = 1,
                Name        = "Groceries",
                Description = "",
                Order       = 0
            });

            ProductTypes.Add(new ProductType()
            {
                Id          = 2,
                Name        = "Chemistry",
                Description = "",
                Order       = 1
            });

            Products.Add(new Product()
            {
                Id          = 1,
                Name        = "Milk 2% UHT",
                Description = "A nice milk with medium fat content. Very delicious.",
                Category    = Categories.Where(item => item.Name == "Milks")
                              .FirstOrDefault(),
                TypeOfProduct = ProductTypes.Where(item => item.Name == "Groceries")
                                .FirstOrDefault()
            });

            Products.Add(new Product()
            {
                Id          = 2,
                Name        = "Gouda Chees",
                Description = "Very yellow and fat gouda chees. Yummy!",
                Category    = Categories.Where(item => item.Name == "Cheeses")
                              .FirstOrDefault(),
                TypeOfProduct = ProductTypes.Where(item => item.Name == "Groceries")
                                .FirstOrDefault()
            });
        }
Example #37
0
        // Retrieve a Specific Category

        public Category GetCategoryById(int categoryId)
        {
            return(Categories.First(c => c.CategoryID == categoryId));
        }
Example #38
0
 public void AuditEnumerateSubCategoriesTest()
 {
     Assert.That(SubCategories, Is.Not.Empty);
     Assert.That(GetSubCategories(Categories.First()), Is.Not.Empty);
 }
Example #39
0
        public static void Initial(AppDbContext context)
        {
            // context.Phone.RemoveRange(context.Phone);
            // context.Category.RemoveRange(context.Category);
            context.Database.Migrate();
            if (!context.Category.Any())
            {
                context.Category.AddRange(Categories.Select(temp => temp.Value));
            }

            if (!context.Phone.Any())
            {
                context.AddRange(
                    new Phone
                {
                    namePhone    = "iPhone SE 2 выйдет в новом дизайне",
                    companyPhone = "Apple",
                    ramPhone     = "3 ГБ",
                    cpuPhone     = "Apple A13 Bionic",
                    shortDesc    = "iPhone SE 2 находится в разработке и его представят весной 2020 года.",
                    fullDesc     = "Да, смартфон выйдет в абсолютно новом дизайне для линейки SE. А если точнее, то это будет копия iPhone 8, как и сообщалось ранее. То есть будет кнопка с Touch ID и даже никакого намёка на безрамочный дисплей.Одна основная камера, стеклянная задняя панель с поддержкой беспроводной зарядки, а также разъём Lightning. Характеристики, правда, как у iPhone 11: процессор Apple A13 Bionic и 3 ГБ оперативной памяти.",
                    img          = "/images/SE.jpg",
                    isFavorite   = true,
                    Category     = Categories["Телефоны"]
                },
                    new Phone
                {
                    namePhone    = "Презентация нового ASUS ZenFone 5",
                    companyPhone = "ASUS",
                    ramPhone     = "4 ГБ",
                    cpuPhone     = " Qualcomm Snapdragon 636",
                    shortDesc    = "ASUS представила в Москве новый ZenFone 5 и доступный ZenFone 5 Lite",
                    fullDesc     = "Компания ASUS анонсировала для российского рынка три новых смартфона: полуфлагман ZenFone 5, его «облегченный» вариант ZenFone 5 Lite и ZenFone Max с мощной батареей. Все новинки ускорены функцией искусственного интеллекта AI Boost, обладают просторными экранами и двойными камерами.6,2-дюймовый экран ZenFone 5 занимает 90% его лицевой площади. Смартфон оборудован процессором Qualcomm Snapdragon 636, графикой Adreno 509 и LTE-модемом Snapdragon X12, обеспечивающим максимальную скорость скачивания в сотовых сетях до 600 Мбит/с. Установлено 4 гигабайта оперативной и 64 ГБ встроенной памяти.",
                    img          = "/images/ASUS.jpg",
                    isFavorite   = false,
                    Category     = Categories["Телефоны"]
                },
                    new Phone
                {
                    namePhone    = "Слухи об HTC U12+",
                    companyPhone = "HTC",
                    ramPhone     = "6 ГБ",
                    cpuPhone     = " Qualcomm Snapdragon 845",
                    shortDesc    = "HTC U12+: дизайн флагмана с четырьмя камерами полностью раскрыли",
                    fullDesc     = "Компания HTC в этом году представит только один флагман, и почему-то называться он будет U12+, а не просто U12. Анонс состоится уже в мае, так что появляется все больше утечек — на этот раз производитель защитных пленок помог раскрыть дизайн смартфона. Цена HTC U12+ пока не известна, но вряд ли он будет стоить дороже прошлой моделиU11+ на старте.",
                    img          = "/images/HTC122.jpg",
                    isFavorite   = false,
                    Category     = Categories["Телефоны"]
                },
                    new Phone
                {
                    namePhone    = "Начало продаж Blackview P10000 Pro ",
                    companyPhone = "Blackview",
                    ramPhone     = "4 ГБ",
                    cpuPhone     = "MediaTek (MT6763)",
                    shortDesc    = "В Китае начали продавать смартфон Blackview P10000 Pro с батареей на 11 000 мА*ч",
                    fullDesc     = "Китайский бренд Blackview выпустил смартфон с аккумулятором, номинальная емкость которого сопоставима с батареей ноутбука. Новинка комплектуется аккумулятором рекордного объема — на 11 тысяч мАч, что в несколько раз больше, чем у конкурирующих устройств (1500–3000 мАч). По емкости батареи P10000 Pro превосходит прошлого рекордсмена Oukitel K10000, который комплектовался аккумулятором на 10 000 мАч и полностью заряжался за 3,5 часа.",
                    img          = "/images/charge.jpg",
                    isFavorite   = false,
                    Category     = Categories["Телефоны"]
                }


                    );
            }

            context.SaveChanges();
        }
Example #40
0
        /// <summary>
        /// Reduces the index value of the specified category by 1 by
        /// exchaning it with the category before it.  If there is no
        /// category before it, then this does nothing.
        /// </summary>
        /// <param name="category">The category to decrease the index of</param>
        public override bool DecreaseCategoryIndex(ICategory category)
        {
            ILineCategory pc = category as ILineCategory;

            return(pc != null && Categories.DecreaseIndex(pc));
        }
        /// <summary>
        /// The method is used to collect template information, specifying the New Window Parameters
        /// </summary>
        private void CollectTemplateInfo()
        {
            List <Wall> walls = Utility.GetElements <Wall>(m_application, m_document);

            m_wallThickness = walls[0].Width;
            ParameterMap paraMap        = walls[0].ParametersMap;
            Parameter    wallheightPara = walls[0].get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);//paraMap.get_Item("Unconnected Height");

            if (wallheightPara != null)
            {
                m_wallHeight = wallheightPara.AsDouble();
            }

            LocationCurve location = walls[0].Location as LocationCurve;

            m_wallWidth = location.Curve.Length;

            m_windowInset = m_wallThickness / 10;
            FamilyType      type           = m_familyManager.CurrentType;
            FamilyParameter heightPara     = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT);
            FamilyParameter widthPara      = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH);
            FamilyParameter sillHeightPara = m_familyManager.get_Parameter("Default Sill Height");

            if (type.HasValue(heightPara))
            {
                switch (heightPara.StorageType)
                {
                case StorageType.Double:
                    m_height = type.AsDouble(heightPara).Value;
                    break;

                case StorageType.Integer:
                    m_height = type.AsInteger(heightPara).Value;
                    break;
                }
            }
            if (type.HasValue(widthPara))
            {
                switch (widthPara.StorageType)
                {
                case StorageType.Double:
                    m_width = type.AsDouble(widthPara).Value;
                    break;

                case StorageType.Integer:
                    m_width = type.AsDouble(widthPara).Value;
                    break;
                }
            }
            if (type.HasValue(sillHeightPara))
            {
                switch (sillHeightPara.StorageType)
                {
                case StorageType.Double:
                    m_sillHeight = type.AsDouble(sillHeightPara).Value;
                    break;

                case StorageType.Integer:
                    m_sillHeight = type.AsDouble(sillHeightPara).Value;
                    break;
                }
            }

            //set the height,width and sillheight parameter of the opening
            m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT),
                                m_height);
            m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH),
                                m_width);
            m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"), m_sillHeight);

            //get materials

            FilteredElementCollector elementCollector = new FilteredElementCollector(m_document);

            elementCollector.WherePasses(new ElementClassFilter(typeof(Material)));
            IList <Element> materials = elementCollector.ToElements();

            foreach (Element materialElement in materials)
            {
                Material material = materialElement as Material;
                m_para.GlassMaterials.Add(material.Name);
                m_para.FrameMaterials.Add(material.Name);
            }

            //get categories
            Categories      categories = m_document.Settings.Categories;
            Category        category   = categories.get_Item(BuiltInCategory.OST_Windows);
            CategoryNameMap cnm        = category.SubCategories;

            m_frameCat = categories.get_Item(BuiltInCategory.OST_WindowsFrameMullionProjection);
            m_glassCat = categories.get_Item(BuiltInCategory.OST_WindowsGlassProjection);

            //get referenceplanes
            List <ReferencePlane> planes = Utility.GetElements <ReferencePlane>(m_application, m_document);

            foreach (ReferencePlane p in planes)
            {
                if (p.Name.Equals("Sash"))
                {
                    m_sashPlane = p;
                }
                if (p.Name.Equals("Exterior"))
                {
                    m_exteriorPlane = p;
                }
                if (p.Name.Equals("Center (Front/Back)"))
                {
                    m_centerPlane = p;
                }
                if (p.Name.Equals("Top") || p.Name.Equals("Head"))
                {
                    m_topPlane = p;
                }
                if (p.Name.Equals("Sill") || p.Name.Equals("Bottom"))
                {
                    m_sillPlane = p;
                }
            }
        }
Example #42
0
        public static void Initial(AppDBContent content)
        {
            if (!content.Category.Any())
            {
                content.Category.AddRange(Categories.Select(c => c.Value)); // создание списков объектов и проверка на не отсутствие категории
            }
            if (!content.Site.Any())
            {
                content.AddRange(
                    new Site
                {
                    name       = "Сайт-Визитка",
                    shortDesc  = "Персональный сайт визитка",
                    longDesc   = "",
                    img        = "/img/site-vizitka.png",
                    price      = 100,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Легкий"]
                },
                    new Site
                {
                    name       = "Лэндинг",
                    shortDesc  = "Одностраничный сайт",
                    longDesc   = "",
                    img        = "/img/site-landing.png",
                    price      = 100,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Легкий"]
                },
                    new Site
                {
                    name       = "Корпоротивный сайт",
                    shortDesc  = "Корпоротивный сайт или сайт с каталогом",
                    longDesc   = "",
                    img        = "/img/site-mobile.png",
                    price      = 600,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Сложный"]
                },

                    new Site
                {
                    name       = "Интернет-магазин",
                    shortDesc  = "Интернет-магазин под ключ",
                    longDesc   = "",
                    img        = "/img/site-vizitka.png",
                    price      = 200,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Сложный"]
                },
                    new Site
                {
                    name       = "Дороботка",
                    shortDesc  = "Дороботка и сопровождение вашего сайта",
                    img        = "/img/site-service.png",
                    longDesc   = "",
                    price      = 100,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Легкий"]
                },
                    new Site
                {
                    name       = "Макет",
                    shortDesc  = "Верстка сайта по макетам заказчика",
                    longDesc   = "",
                    img        = "/img/site-verstka.png",
                    price      = 100,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Легкий"]
                },
                    new Site
                {
                    name       = "Оптимизация",
                    shortDesc  = "Оптимизация сайта под мобильные устройства",
                    longDesc   = "",
                    img        = "/img/site-mobile.png",
                    price      = 100,
                    isFavorite = true,
                    available  = true,
                    category   = Categories["Сложный"]
                }
                    );
            }
            content.SaveChanges();
        }
        private static void SeedDatabaseAsync(AppDbContext _context, RoleManager <IdentityRole> _roleManager, UserManager <IdentityUser> _userManager)
        {
            var cat1 = new Categories {
                Name = "Fantastic", Description = "The BookShop's Fantastic books."
            };
            var cat2 = new Categories {
                Name = "Horror", Description = "The BookShop's Horror books."
            };
            var cat3 = new Categories {
                Name = "Poetry", Description = "The BookShop's Poetry books."
            };

            var cats = new List <Categories>()
            {
                cat1, cat2, cat3
            };

            var piz1 = new Books {
                Name = "Harry Potter and Cursed child", Price = 7000.00M, Category = cat1, Description = "The official playscript of the original West End production of Harry Potter and the Cursed Child.", ImageUrl = "https://cdn.shopify.com/s/files/1/0939/3316/products/harry-potter-and-the-cursed-child_1024x1024.png?v=1462471346", IsBookOfTheWeek = false
            };
            var piz2 = new Books {
                Name = "Harry Potter and the Philosopher's Stone", Price = 7000.00M, Category = cat3, Description = "Turning the envelope over, his hand trembling, Harry saw a purple wax seal bearing a coat of arms; a lion, an eagle, a badger and a snake surrounding a large letter ‘H’.", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781100219_large.jpg?v=1512057994", IsBookOfTheWeek = false
            };
            var piz3 = new Books {
                Name = "Harry Potter and the Chamber of Secrets", Price = 7500.00M, Category = cat1, Description = "There is a plot, Harry Potter. A plot to make most terrible things happen at Hogwarts School of Witchcraft and Wizardry this year.", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781100226_large.jpg?v=1512058008", IsBookOfTheWeek = true
            };
            var piz4 = new Books {
                Name = "Harry Potter and the Prisoner of Azkaban", Price = 6500.00M, Category = cat1, Description = "Welcome to the Knight Bus, emergency transport for the stranded witch or wizard. Just stick out your wand hand, step on board and we can take you anywhere you want to go.", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781100233_large.jpg?v=1512058021", IsBookOfTheWeek = false
            };
            var piz5 = new Books {
                Name = "Harry Potter and the Goblet of Fire", Price = 8500.00M, Category = cat2, Description = "There will be three tasks, spaced throughout the school year, and they will test the champions in many different ways …", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781105672_large.jpg?v=1512058035", IsBookOfTheWeek = true
            };
            var piz6 = new Books {
                Name = "Harry Potter and the Order of the Phoenix", Price = 8000.00M, Category = cat1, Description = "You are sharing the Dark Lord's thoughts and emotions. The Headmaster thinks it inadvisable for this to continue. He wishes me to teach you how to close your mind to the Dark Lord.", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781100240_large.jpg?v=1512058049", IsBookOfTheWeek = true
            };
            var piz7 = new Books {
                Name = "Harry Potter and the Half-Blood Prince", Price = 7000.00M, Category = cat1, Description = "There it was, hanging in the sky above the school: the blazing green skull with a serpent tongue, the mark Death Eaters left behind whenever they had entered a building… wherever they had murdered… ", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781100257_large.jpg?v=1512058060", IsBookOfTheWeek = false
            };
            var piz8 = new Books {
                Name = "Harry Potter and the Deathly Hallows", Price = 8900.00M, Category = cat2, Description = "Give me Harry Potter,’ said Voldemort's voice, ‘and none shall be harmed. Give me Harry Potter, and I shall leave the school untouched. Give me Harry Potter, and you will be rewarded.", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781100264_0912cb63-727c-48e0-beff-cda2ebaed8e3_large.jpg?v=1523287912", IsBookOfTheWeek = false
            };
            var piz9 = new Books {
                Name = "The Tales of Beedle the Bard", Price = 6900.00M, Category = cat3, Description = "There were once three brothers who were travelling along a lonely, winding road at twilight...", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781106754_9c68e0f8-b7a5-4492-b28d-f7363d4dec61_large.jpg?v=1517910784", IsBookOfTheWeek = false
            };
            var piz10 = new Books {
                Name = "Harry Potter: A History of Magic", Price = 7500.00M, Category = cat1, Description = "Harry Potter: A History of Magic is the official eBook of the once-in-a-lifetime exhibition from the brilliant curators of the British Library.", ImageUrl = "https://cdn.shopify.com/s/files/1/1153/0428/products/9781781109236_large.jpg?v=1517910823", IsBookOfTheWeek = false
            };

            var pizs = new List <Books>()
            {
                piz1, piz2, piz3, piz4, piz5, piz6, piz7, piz8, piz9, piz10
            };

            var user1 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };
            var user2 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };
            var user3 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };
            var user4 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };
            var user5 = new IdentityUser {
                UserName = "******", Email = "*****@*****.**"
            };

            string userPassword = "******";

            var users = new List <IdentityUser>()
            {
                user1, user2, user3, user4, user5
            };

            foreach (var user in users)
            {
                //Bug with Core 2.1/2.2: Throws Disposed Exception after multiple calls. Temp fix Service as Singleton?
                //await _userManager.CreateAsync(user, userPassword);
                var result1 = _userManager.CreateAsync(user, userPassword).Result;
            }



            var ord1 = new Order
            {
                FirstName   = "Zhanel",
                LastName    = "Erkinbekova",
                Address     = "Moldagulova 32",
                City        = "Almaty",
                Country     = "Kazakhstan",
                Email       = "*****@*****.**",
                OrderPlaced = DateTime.Now.AddDays(-2),
                PhoneNumber = "87772369955",
                User        = user1,
                OrderTotal  = 370.00M,
            };

            var ord2 = new Order {
            };
            var ord3 = new Order {
            };

            var orderLines = new List <OrderDetail>()
            {
                new OrderDetail {
                    Order = ord1, Book = piz1, Amount = 2, Price = piz1.Price
                },
                new OrderDetail {
                    Order = ord1, Book = piz3, Amount = 1, Price = piz3.Price
                },
                new OrderDetail {
                    Order = ord1, Book = piz5, Amount = 3, Price = piz5.Price
                },
            };

            var orders = new List <Order>()
            {
                ord1
            };

            _context.Categories.AddRange(cats);
            _context.Books.AddRange(pizs);
            _context.Orders.AddRange(orders);
            _context.OrderDetails.AddRange(orderLines);


            _context.SaveChanges();
        }
Example #44
0
 public Subject(Categories category)
 {
     _categories = category;
 }
Example #45
0
        /// <summary>
        /// Re-orders the specified member by attempting to exchange it with the next higher
        /// index category. If there is no higher index, this does nothing.
        /// </summary>
        /// <param name="category">The category to increase the index of.</param>
        /// <returns>True, if the index was increased.</returns>
        public override bool IncreaseCategoryIndex(ICategory category)
        {
            IPolygonCategory pc = category as IPolygonCategory;

            return(pc != null && Categories.IncreaseIndex(pc));
        }
Example #46
0
 public void AddCategory(ProductCategory category)
 {
     category.Product = this;
     Categories.Add(category);
 }
Example #47
0
        // Retrieve All Category Objects

        public List <Category> GetCategories()
        {
            return(Categories.ToList());
        }
Example #48
0
        public int Put()
        {
            Categories category = JsonConvert.DeserializeObject <Categories>(Request.Form["CategoryFormData"].ToString());

            return(_categoryService.UpdateCategory(category));
        }
Example #49
0
 public async Task EditKnowledgeCategory(Categories categories)
 {
     await CategoryAccessor.Update(categories);
 }
Example #50
0
        public TestModule()
        {
            // Generates any static page given all site content
            Post["/static"] = x =>
            {
                var siteContent = new ContentViewModel
                {
                    GeneratedUrl                = GeneratedUrl,
                    PostsInCategory             = PostsInCategory,
                    AllCategories               = Categories,
                    Keywords                    = Categories.Select(c => c.Name).ToList(),
                    Posts                       = Posts,
                    PostsPaged                  = PostsPaged,
                    PostsGroupedByYearThenMonth = PostsGroupedByYearThenMonth,
                    HasPreviousPage             = HasPreviousPage,
                    HasNextPage                 = HasNextPage,
                    NextPage                    = PageNumber + 1,
                    PreviousPage                = PageNumber - 1,
                    MonthYearList               = MonthYear,
                    GeneratedDate               = GeneratedDate,
                    Category                    = Category,
                    Drafts                      = Drafts,
                    Published                   = Published
                };

                return(View[StaticFile, siteContent]);
            };

            // Generates an actual post based on the Markdown content
            // with a SiteContent property for access to everything
            Post["/compose"] = x =>
            {
                dynamic result = new PostViewModel
                {
                    Drafts        = Drafts,
                    Posts         = Posts,
                    GeneratedUrl  = GeneratedUrl,
                    PostContent   = Data.Content,
                    PostDate      = Data.Date,
                    Layout        = Data.Layout,
                    Title         = Data.Title,
                    GeneratedDate = GeneratedDate,
                    Url           = Data.Url,
                    AllCategories = Categories,
                    Categories    = Data.Categories.Select(c => new Category {
                        Name = c
                    }).ToList(),
                    Keywords        = Data.Categories.ToList(),
                    MonthYearList   = MonthYear,
                    Author          = Data.Author,
                    Email           = Data.Email,
                    Settings        = Settings,
                    Series          = Data.Series,
                    MetaDescription = Data.MetaDescription,
                    Published       = Data.Published
                };

                result.Banana = "WOW!";

                return(View[result.Layout, result]);
            };

            Post["/rss"] = x => Response.AsRSS(Posts, Settings.BlogTitle, Settings.SiteUrl, StaticFile);

            Post["/atom"] = x => Response.AsAtom(Posts, Settings.BlogTitle, Settings.SiteUrl, Settings.Author, Settings.Email, StaticFile);

            Post["/sitemap"] = x =>
            {
                var publishedPosts = Posts.Where(post => post.Published == Published.True);

                return(Response.AsSiteMap(publishedPosts, Settings.SiteUrl));
            };
        }
        // Add or Update
        private void button3_Click(object sender, EventArgs e)
        {
            if (isValid())
            {
                if (thisBook == null)
                {
                    Categories categ  = cmbCathegory.SelectedItem as Categories;
                    int        bookID = books.Add(new Books(txtName.Text, Convert.ToDouble(txtPrice.Text), categ.id, Convert.ToInt32(txtCount.Text)));

                    if (bookID > 0)
                    {
                        foreach (Authors item in listBox1.SelectedItems)
                        {
                            AuthorsBooks authorsBooks = new AuthorsBooks();
                            authorsBooks.BookID   = bookID;
                            authorsBooks.AuthorID = item.id;
                            if (authorsBooksDB.Add(authorsBooks))
                            {
                                txtInfo.Text = "Book added";
                            }
                            else
                            {
                                txtInfo.Text = "Error: Author is not added";
                            }
                        }
                    }
                    else
                    {
                        txtInfo.Text = "Error: Book is not added";
                    }
                }
                else
                {   // Updating
                    Categories categ = cmbCathegory.SelectedItem as Categories;
                    if (books.Update(new Books(txtName.Text, Convert.ToDouble(txtPrice.Text), categ.id, Convert.ToInt32(txtCount.Text)), thisBook.id))
                    {
                        txtInfo.Text = "Book is Updated!";
                    }
                    else
                    {
                        txtInfo.Text = "Warning: book is not updated!";
                    }
                    // Update all authors
                    authorsBooksDB.DeleteRows(thisBook.id); // first remove all authors
                    foreach (Authors item in listBox1.SelectedItems)
                    {
                        AuthorsBooks authorsBooks = new AuthorsBooks();
                        authorsBooks.BookID   = thisBook.id;
                        authorsBooks.AuthorID = item.id;

                        if (authorsBooksDB.Add(authorsBooks))
                        {
                            txtInfo.Text = "Book is Updated!";
                        }
                    }
                }

                ResetForm();
                button3.Text = "Save";
            }
        }
Example #52
0
        public int createNewCategory(Categories c)
        {
            int rows = conn.Insert(c);

            return(rows);
        }
 public async Task <int> DeleteAsyncCategory(Categories categories)
 {
     return(await App.Database.DeleteCategoryAsync(categories));
 }
Example #54
0
        public void Create(Categories model)
        {
            var repository = new CategoriesRepository();

            repository.Create(model);
        }
        public void Add_Should_Throw_Exception_When_Specified_Name_Already_Exists()
        {
            Categories.Add(_factory.CreateCategory("Demo") as Category);

            Assert.Throws <ArgumentException>(() => _categoryRepository.Add(_factory.CreateCategory("Demo")));
        }
Example #56
0
        public void Delete(Categories model)
        {
            var repository = new CategoriesRepository();

            repository.Delete(model);
        }
 public void Add(Categories categories)
 {
     _dbContext.Add(categories);
     _dbContext.SaveChanges();
 }
 public IActionResult Addcategories(Categories C)
 {
     A.Categories.Add(C);
     A.SaveChanges();
     return(View());
 }
Example #59
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp         = commandData.Application;
            UIDocument    uidoc         = uiapp.ActiveUIDocument;
            Document      doc           = uidoc.Document;
            Result        commandResult = Result.Succeeded;
            Categories    cats          = doc.Settings.Categories;

            ElementId catDoorsId = cats.get_Item(
                BuiltInCategory.OST_Doors).Id;

            ElementId catWindowsId = cats.get_Item(
                BuiltInCategory.OST_Windows).Id;

            try
            {
                List <ElementId> selectedIds = uidoc.Selection
                                               .GetElementIds().ToList();

                using (Transaction trans = new Transaction(doc))
                {
                    trans.Start("Cmd: GetOpeningProfiles");

                    List <ElementId> newIds = new List <ElementId>();

                    foreach (ElementId selectedId in selectedIds)
                    {
                        Wall wall = doc.GetElement(selectedId) as Wall;

                        if (wall != null)
                        {
                            List <PlanarFace> faceList = new List <PlanarFace>();

                            List <ElementId> insertIds = wall.FindInserts(
                                true, false, false, false).ToList();

                            foreach (ElementId insertId in insertIds)
                            {
                                Element elem = doc.GetElement(insertId);

                                if (elem is FamilyInstance)
                                {
                                    FamilyInstance inst = elem as FamilyInstance;

                                    CategoryType catType = inst.Category
                                                           .CategoryType;

                                    Category cat = inst.Category;

                                    if (catType == CategoryType.Model &&
                                        (cat.Id == catDoorsId ||
                                         cat.Id == catWindowsId))
                                    {
                                        faceList.AddRange(
                                            GetWallOpeningPlanarFaces(
                                                wall, insertId));
                                    }
                                }
                                else if (elem is Opening)
                                {
                                    faceList.AddRange(
                                        GetWallOpeningPlanarFaces(
                                            wall, insertId));
                                }
                            }

                            foreach (PlanarFace face in faceList)
                            {
                                //Plane facePlane = new Plane(
                                //  face.ComputeNormal( UV.Zero ),
                                //  face.Origin ); // 2016

                                Plane facePlane = Plane.CreateByNormalAndOrigin(
                                    face.ComputeNormal(UV.Zero),
                                    face.Origin); // 2017

                                SketchPlane sketchPlane
                                    = SketchPlane.Create(doc, facePlane);

                                foreach (CurveLoop curveLoop in
                                         face.GetEdgesAsCurveLoops())
                                {
                                    foreach (Curve curve in curveLoop)
                                    {
                                        ModelCurve modelCurve = doc.Create
                                                                .NewModelCurve(curve, sketchPlane);

                                        newIds.Add(modelCurve.Id);
                                    }
                                }
                            }
                        }
                    }

                    if (newIds.Count > 0)
                    {
                        View activeView = uidoc.ActiveGraphicalView;
                        activeView.IsolateElementsTemporary(newIds);
                    }
                    trans.Commit();
                }
            }

            #region Exception Handling

            catch (Autodesk.Revit.Exceptions
                   .ExternalApplicationException e)
            {
                message = e.Message;
                Debug.WriteLine(
                    "Exception Encountered (Application)\n"
                    + e.Message + "\nStack Trace: "
                    + e.StackTrace);

                commandResult = Result.Failed;
            }
            catch (Autodesk.Revit.Exceptions
                   .OperationCanceledException e)
            {
                Debug.WriteLine("Operation cancelled. "
                                + e.Message);

                message = "Operation cancelled.";

                commandResult = Result.Succeeded;
            }
            catch (Exception e)
            {
                message = e.Message;
                Debug.WriteLine(
                    "Exception Encountered (General)\n"
                    + e.Message + "\nStack Trace: "
                    + e.StackTrace);

                commandResult = Result.Failed;
            }

            #endregion

            return(commandResult);
        }
Example #60
0
        static void Main(string[] args)
        {
            logger.Info("Program started");
            Console.ForegroundColor = ConsoleColor.Green;

            try
            {
                var     db = new NorthwindConsole_31_mdoContext();
                int     id = 0;
                string  choice;
                String  displayChoice;
                short   shortChoice;
                decimal decimalChoice;
                do
                {
                    //todo use nlog
                    //todo new product
                    //todo edit specific product
                    //todo display all records in products table (productname only) - user decides if they want to see all products, discontinued products, or active (not discontinued) products
                    //todo display a specific product (display all product fields)
                    //todo
                    //todo edit a category
                    //todo

                    Console.WriteLine("1) Add Product");
                    Console.WriteLine("2) Edit A Product");
                    Console.WriteLine("3) Display All Products");
                    Console.WriteLine("4) Display Specific Product");
                    Console.WriteLine("5) Add A Category");
                    Console.WriteLine("6) Edit A Category");
                    Console.WriteLine("7) Display Categories");
                    Console.WriteLine("8) Display Category and related products");
                    Console.WriteLine("9) Display all Categories and their related active products");
                    Console.WriteLine("\"q\" to quit");
                    choice = Console.ReadLine();
                    Console.Clear();
                    logger.Info($"Option {choice} selected");

                    switch (choice)
                    {
                    case "1":     // Add Product
                        logger.Info("1) selected");
                        var query1 = db.Categories.OrderBy(p => p.CategoryId);

                        Console.WriteLine("Select the category you want to add a product to:");
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        foreach (var item in query1)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        Console.ForegroundColor = ConsoleColor.White;
                        id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"CategoryId {id} selected");

                        if (db.Categories.Any(c => c.CategoryId == id))
                        {
                            logger.Info("Validation passed, category id exists");
                            Products product = new Products();
                            product.CategoryId = id;
                            var querySupplier = db.Suppliers.OrderBy(p => p.SupplierId);

                            Console.WriteLine("Select the supplier of your product:");
                            Console.ForegroundColor = ConsoleColor.DarkRed;
                            foreach (var item in querySupplier)
                            {
                                Console.WriteLine($"{item.SupplierId}) {item.CompanyName}");
                            }
                            Console.ForegroundColor = ConsoleColor.White;
                            id = int.Parse(Console.ReadLine());
                            Console.Clear();
                            logger.Info($"CategoryId {id} selected");

                            if (db.Suppliers.Any(c => c.SupplierId == id))
                            {
                                logger.Info("Validation passed, supplier id exists");
                                product.SupplierId = id;

                                Console.WriteLine("What is the products name?");
                                String productName = Console.ReadLine();
                                Console.WriteLine("What is the quantity per unit for this product?");
                                String quantityPerUnit = Console.ReadLine();
                                Console.WriteLine("What is the unit price for this product (##.##)?");
                                decimal unitPrice = decimal.Round(decimal.Parse(Console.ReadLine()), 2);
                                Console.WriteLine("How many units are in stock (##)?");
                                short stock = short.Parse(Console.ReadLine());

                                if (productName.Equals("") || quantityPerUnit.Equals(""))
                                {
                                    logger.Error("Empty values are not accepted");
                                }
                                else
                                {
                                    if (db.Products.Any(c => c.ProductName == productName))
                                    {
                                        logger.Error("That product name already exists");
                                    }
                                    else
                                    {
                                        //setting default values for a new product
                                        product.UnitsOnOrder = 0;
                                        product.ReorderLevel = 0;
                                        product.Discontinued = false;

                                        product.ProductName     = productName;
                                        product.QuantityPerUnit = quantityPerUnit;
                                        product.UnitPrice       = unitPrice;
                                        product.UnitsInStock    = stock;

                                        db.AddProduct(product);
                                        logger.Info($"{product.ProductName} was added");
                                    }
                                }
                            }
                            else
                            {
                                logger.Error("There was not a supplier with that id");
                            }
                        }
                        else
                        {
                            logger.Error("There was not a category with that id");
                        }
                        break;

                    case "2":     // Edit a product
                        logger.Info("2) selected");
                        logger.Info("All Products Displayed");
                        var query2 = db.Products.OrderBy(p => p.ProductId);
                        foreach (var item in query2)
                        {
                            if (item.Discontinued == true)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"{item.ProductId}) {item.ProductName}");
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"{item.ProductId}) {item.ProductName}");
                            }
                        }
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Select a product to edit");
                        id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"Product id {id} selected to edit");
                        Products editProduct = db.Products.FirstOrDefault(p => p.ProductId == id);
                        Console.WriteLine("Do you want to change the product's name? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the name");
                            Console.WriteLine("What is the new name?");
                            choice = Console.ReadLine();
                            editProduct.ProductName = choice;
                        }

                        Console.WriteLine("Do you want to change the product's quantity per unit? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the quantity per unit");
                            Console.WriteLine("What is the new quantity per unit?");
                            choice = Console.ReadLine();
                            editProduct.QuantityPerUnit = choice;
                        }

                        Console.WriteLine("Do you want to change the product's reorder level? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the reorder level");
                            Console.WriteLine("What is the new reorder level?");
                            shortChoice = short.Parse(Console.ReadLine());
                            editProduct.ReorderLevel = shortChoice;
                        }

                        Console.WriteLine("Do you want to change the product's unit price? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the unit price");
                            Console.WriteLine("What is the new unit price?");
                            decimalChoice         = decimal.Round(decimal.Parse(Console.ReadLine()), 2);
                            editProduct.UnitPrice = decimalChoice;
                        }

                        Console.WriteLine("Do you want to change the product's units in stock? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the units in stock");
                            Console.WriteLine("How many units are in stock?");
                            shortChoice = short.Parse(Console.ReadLine());
                            editProduct.UnitsInStock = shortChoice;
                        }

                        Console.WriteLine("Do you want to change the product's units on order? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the units on order");
                            Console.WriteLine("How many units are on order?");
                            shortChoice = short.Parse(Console.ReadLine());
                            editProduct.UnitsOnOrder = shortChoice;
                        }

                        Console.WriteLine("Do you want to change the discontinued status of the product? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change discontinued status");
                            Console.WriteLine("Is the unit discontinued Y/N?");
                            bool correctInput = true;
                            do
                            {
                                choice = Console.ReadLine();
                                if (choice == "y" || choice == "Y")
                                {
                                    editProduct.Discontinued = true;
                                    correctInput             = true;
                                }
                                else if (choice == "n" || choice == "N")
                                {
                                    editProduct.Discontinued = false;
                                    correctInput             = true;
                                }
                                else
                                {
                                    correctInput = false;
                                }
                            } while (correctInput);
                        }
                        db.EditProduct(editProduct);

                        break;

                    case "3":     // Display all products - all, discontinued, or acitve
                        logger.Info("3) selected");
                        Console.WriteLine("1) All Products");
                        Console.WriteLine("2) Discontinued Products");
                        Console.WriteLine("3) Active Products");
                        displayChoice = Console.ReadLine();

                        switch (displayChoice)
                        {
                        case "1":
                            logger.Info("All Products Displayed");
                            var query3 = db.Products.OrderBy(p => p.ProductName);
                            Console.WriteLine($"{query3.Count()} records returned");
                            Console.ForegroundColor = ConsoleColor.Green;
                            foreach (var item in query3)
                            {
                                if (item.Discontinued == true)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine($"{item.ProductName}");
                                }
                                else
                                {
                                    Console.ForegroundColor = ConsoleColor.Green;
                                    Console.WriteLine($"{item.ProductName}");
                                }
                            }
                            break;

                        case "2":
                            logger.Info("Discontinued Products Displayed");
                            var queryDiscontinued = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued == true);
                            Console.WriteLine($"{queryDiscontinued.Count()} records returned");
                            Console.ForegroundColor = ConsoleColor.Red;
                            foreach (var item in queryDiscontinued)
                            {
                                Console.WriteLine($"{item.ProductName}");
                            }
                            break;

                        case "3":
                            logger.Info("Active Products Displayed");
                            var queryActive = db.Products.OrderBy(p => p.ProductName).Where(p => p.Discontinued == false);
                            Console.WriteLine($"{queryActive.Count()} records returned");
                            Console.ForegroundColor = ConsoleColor.Green;
                            foreach (var item in queryActive)
                            {
                                Console.WriteLine($"{item.ProductName}");
                            }
                            break;

                        default:
                            logger.Error("You did not enter a valid value");
                            break;
                        }
                        Console.ForegroundColor = ConsoleColor.Green;
                        break;

                    case "4":     // Display specific product
                        logger.Info("4) selected");
                        var query4 = db.Products.OrderBy(p => p.ProductId);
                        foreach (var item in query4)
                        {
                            if (item.Discontinued == true)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"{item.ProductId}) {item.ProductName}");
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"{item.ProductId}) {item.ProductName}");
                            }
                        }
                        Console.WriteLine("Select a product");
                        //todo supplier and category are not showing properly --------------------------------------------------------------
                        id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"Product id {id} selected");
                        Products displayProduct = db.Products.FirstOrDefault(p => p.ProductId == id);
                        Console.WriteLine($"{displayProduct.ProductName}");
                        Console.WriteLine($"Supplier: {displayProduct.SupplierId}");
                        Console.WriteLine($"Category: {displayProduct.CategoryId}");
                        Console.WriteLine($"Quantity Per Unit: {displayProduct.QuantityPerUnit}");
                        Console.WriteLine($"Unit Price: ${displayProduct.UnitPrice}");
                        Console.WriteLine($"Units In Stock: {displayProduct.UnitsInStock}");
                        Console.WriteLine($"Units In Order: {displayProduct.UnitsOnOrder}");
                        Console.WriteLine($"Reorder Level: {displayProduct.ReorderLevel}");
                        if (displayProduct.Discontinued == true)
                        {
                            Console.WriteLine("It is discontinued");
                        }
                        break;

                    case "5":     // Add a category
                        logger.Info("5) selected");
                        Categories category5 = new Categories();
                        Console.WriteLine("Enter Category Name:");
                        category5.CategoryName = Console.ReadLine();
                        Console.WriteLine("Enter the Category Description:");
                        category5.Description = Console.ReadLine();

                        ValidationContext       context = new ValidationContext(category5, null, null);
                        List <ValidationResult> results = new List <ValidationResult>();

                        var isValid = Validator.TryValidateObject(category5, context, results, true);
                        if (isValid)
                        {
                            //var db = new NorthwindConsole_31_mdoContext();
                            // check for unique name
                            if (db.Categories.Any(c => c.CategoryName == category5.CategoryName))
                            {
                                // generate validation error
                                isValid = false;
                                results.Add(new ValidationResult("Name exists", new string[] { "CategoryName" }));
                            }
                            else
                            {
                                logger.Info("Validation passed");
                                // Console.WriteLine(category5.CategoryName +" "+category5.Description +"//");
                                // Console.WriteLine(category5.CategoryId);
                                db.AddCategory(category5);
                                logger.Info($"{category5.CategoryName} was added");
                            }
                        }
                        if (!isValid)
                        {
                            foreach (var result in results)
                            {
                                logger.Error($"{result.MemberNames.First()} : {result.ErrorMessage}");
                            }
                        }
                        break;

                    case "6":     //Edit A Category
                        logger.Info("6) selected");
                        var query6 = db.Categories.OrderBy(p => p.CategoryName);

                        Console.ForegroundColor = ConsoleColor.Green;
                        foreach (var item in query6)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine("Select a category to edit");
                        id = int.Parse(Console.ReadLine());
                        logger.Info($"Category id {id} selected to edit");
                        Categories editCategory = db.Categories.FirstOrDefault(c => c.CategoryId == id);
                        Console.WriteLine("Do you want to change the categories's name? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the name");
                            Console.WriteLine("What is the new name?");
                            choice = Console.ReadLine();
                            editCategory.CategoryName = choice;
                        }
                        Console.WriteLine("Do you want to change the categories's description? (Y/N)");
                        choice = Console.ReadLine();
                        if (choice == "y" || choice == "Y")
                        {
                            logger.Info("Chose to change the description");
                            Console.WriteLine("What is the new description?");
                            choice = Console.ReadLine();
                            editCategory.Description = choice;
                        }
                        db.EditCategory(editCategory);

                        break;

                    case "7":     //Display Categories
                        logger.Info("7) selected");
                        //var db = new NorthwindConsole_31_mdoContext();
                        var query7 = db.Categories.OrderBy(p => p.CategoryName);

                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine($"{query7.Count()} records returned");
                        Console.ForegroundColor = ConsoleColor.Magenta;
                        foreach (var item in query7)
                        {
                            Console.WriteLine($"{item.CategoryName} - {item.Description}");
                        }
                        Console.ForegroundColor = ConsoleColor.White;
                        break;

                    case "8":     //Display Category and related products
                        logger.Info("8) selected");
                        //var db = new NorthwindConsole_31_mdoContext();
                        var query8 = db.Categories.OrderBy(p => p.CategoryId);

                        Console.WriteLine("Select the category whose products you want to display:");
                        Console.ForegroundColor = ConsoleColor.DarkRed;
                        foreach (var item in query8)
                        {
                            Console.WriteLine($"{item.CategoryId}) {item.CategoryName}");
                        }
                        Console.ForegroundColor = ConsoleColor.White;
                        id = int.Parse(Console.ReadLine());
                        Console.Clear();
                        logger.Info($"CategoryId {id} selected");
                        Categories category8 = db.Categories.Include("Products").FirstOrDefault(c => c.CategoryId == id);
                        Console.WriteLine($"{category8.CategoryName} - {category8.Description}");
                        foreach (Products p in category8.Products)
                        {
                            Console.WriteLine(p.ProductName);
                        }
                        break;

                    case "9":     //Display all Categories and their related products (active)
                        logger.Info("9) selected");
                        //var db = new NorthwindConsole_31_mdoContext();
                        var query9 = db.Categories.Include("Products").OrderBy(p => p.CategoryId);
                        foreach (var item in query9)
                        {
                            Console.WriteLine($"{item.CategoryName}");
                            foreach (Products p in item.Products)
                            {
                                if (p.Discontinued == false)
                                {
                                    Console.WriteLine($"\t{p.ProductName}");
                                }
                            }
                        }
                        break;

                    default:
                        break;
                    }

                    Console.WriteLine();
                } while (choice.ToLower() != "q");
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }

            logger.Info("Program ended");
        }