private void ExecuteAddSerialNumber()
        {
            if (string.IsNullOrWhiteSpace(SerialNumberToAdd))
            {
                HasAddSerialError     = true;
                AddSerialErrorMessage = "Please enter a serial number.";
            }
            else if (Modules.Any(t => t.SerialNumber == SerialNumberToAdd.Trim()))
            {
                AddSerialErrorMessage = "Modules is already in list.";
                HasAddSerialError     = true;
            }
            else
            {
                HasAddSerialError = false;
                LoadModuleScan scan = new LoadModuleScan
                {
                    EPC          = SerialNumberToAdd,
                    SerialNumber = SerialNumberToAdd,
                    ScanTime     = DateTime.UtcNow
                };

                Modules.Add(scan);
                ModuleHeader = Modules.Count().ToString() + " IN LOAD";
            }
            SerialNumberToAdd = "";
        }
Exemplo n.º 2
0
        private void LoadParentModules(MixCmsContext _context, IDbContextTransaction _transaction)
        {
            var getModulePost = MixModulePosts.ReadViewModel.GetModulePostNavAsync(Id, Specificulture, _context, _transaction);

            if (getModulePost.IsSucceed)
            {
                this.Modules = getModulePost.Data;
                this.Modules.ForEach(c =>
                {
                    c.IsActived = MixModulePosts.ReadViewModel.Repository.CheckIsExists(n => n.ModuleId == c.ModuleId && n.PostId == Id, _context, _transaction);
                });
            }
            var otherModules = MixModules.ReadListItemViewModel.Repository.GetModelListBy(
                m => (m.Type == (int)MixEnums.MixModuleType.Content || m.Type == (int)MixEnums.MixModuleType.ListPost) &&
                m.Specificulture == Specificulture &&
                !Modules.Any(n => n.ModuleId == m.Id && n.Specificulture == m.Specificulture)
                , "CreatedDateTime", 1, null, 0, _context, _transaction);

            foreach (var item in otherModules.Data.Items)
            {
                Modules.Add(new MixModulePosts.ReadViewModel()
                {
                    ModuleId    = item.Id,
                    Image       = item.Image,
                    PostId      = Id,
                    Description = Title
                });
            }
        }
Exemplo n.º 3
0
 /// <summary>
 /// Builds an event with the current data in this builder. If you want to create and send an event immediately,
 /// use <see cref="CaptureAsync"/> instead.
 /// </summary>
 public SentryEvent Build()
 {
     return(new SentryEvent
     {
         EventId = (EventId ?? Guid.NewGuid()).ToString("N"),
         Timestamp = Timestamp ?? DateTime.UtcNow,
         Logger = Logger,
         Platform = Platform,
         Sdk = Sdk,
         Level = Level ?? (Exception == null ? SeverityLevel.Info : SeverityLevel.Error),
         Culprit = Culprit,
         ServerName = ServerName,
         Release = Release,
         Tags = Tags.Any() ? Tags.ToDictionary(p => p.Key, p => p.Value) : null,
         Environment = Environment,
         Modules = Modules.Any() ? Modules : null,
         Extra = Extra,
         Fingerprint = Fingerprint.Any() ? Fingerprint : null,
         Exception = Exception != null && Exception.Any() ? Exception : null,
         Message = Message,
         Breadcrumbs = Breadcrumbs,
         Request = Request,
         User = User,
         Contexts = Contexts.Any() ? Contexts.ToDictionary(p => p.Key, p => p.Value) : null
     });
 }
Exemplo n.º 4
0
 private void OnKeyUp(object sender, KeyEventArgs e)
 {
     if (e.KeyCode == Keys.Return)
     {
         Finish();
     }
     else if (e.KeyCode == Keys.Space)
     {
         var addition = Modules.Any(module => module.Install) && !Modules.All(module => module.Install);
         foreach (var selectedRow in gridView.GetSelectedRows())
         {
             if (!gridView.IsGroupRow(selectedRow))
             {
                 if (gridView.GetRow(selectedRow) is XpandModule xpandModule)
                 {
                     xpandModule.Install = addition || !xpandModule.Install;
                 }
             }
         }
         gridView.RefreshData();
     }
     else if (e.KeyCode == Keys.A && e.Modifiers == Keys.Control)
     {
         for (int i = 0; i < gridView.RowCount; i++)
         {
             gridView.SelectRow(i);
         }
     }
 }
Exemplo n.º 5
0
        private void SyncModuleList(RoomPresenceMessage roomPresenceMessage)
        {
            var toRemove = Modules.Where(module => module != _lobbyModule && module != _logModule &&
                                         !roomPresenceMessage.IsPresentIn(module.Caption)).ToList();
            var toAdd = roomPresenceMessage.Rooms.Where(room =>
                                                        !Modules.Any(m => m.Caption.Equals(room.Name, StringComparison.InvariantCultureIgnoreCase))).ToList();

            foreach (var module in toRemove)
            {
                Modules.Remove(module);

                if (module == _activeModule)
                {
                    ActiveModule = _lobbyModule;
                }

                _creator.ReleaseModule(module);
            }
            foreach (var room in toAdd)
            {
                var newModule = _creator.CreateRoomModule(room);

                int index = Modules.IndexOf(_logModule);
                Modules.Insert(index, newModule);
            }
        }
Exemplo n.º 6
0
Arquivo: Game.cs Projeto: Vtek/Pulsar
        /// <summary>
        /// Add game module
        /// </summary>
        public Game AddModule <T>() where T : IModule
        {
            PulsarHost.Instance.Kernel.Bind <IModule> ().To <T> ().InSingletonScope();

            var module = PulsarHost.Instance.Kernel.GetService(typeof(T));

            var wasAdded = Modules.Any(x => x.GetType().IsInstanceOfType(module));

            if (wasAdded)
            {
                throw new InvalidOperationException(string.Format("Module {0} already added", module.GetType()));
            }

            if (module is GameModule)
            {
                var gm = (GameModule)module;
                gm.GlobalData = GlobalData;
                gm.TempData   = GlobalData;
            }

            Modules.Add((IModule)module);

            if (module is IDrawable)
            {
                Drawables.Add((IDrawable)module);
            }

            return(this);
        }
Exemplo n.º 7
0
 internal override void Validate()
 {
     base.Validate();
     if (Modules == null || !Modules.Any())
     {
         throw new ArgumentNullException("must add shelfmodule, use addModule function");
     }
 }
Exemplo n.º 8
0
        protected virtual void InitApp()
        {
            Status = EntityAppStatus.Initializing;
            SetupLogFileWriters();
            ActivationLog.WriteMessage("Initializing EntityApp {0}.====================================", this.AppName);
            this.AppEvents.OnInitializing(EntityAppInitStep.Initializing);
            //Check dependencies
            foreach (var mod in this.Modules)
            {
                var depList = mod.GetDependencies();
                foreach (var dep in depList)
                {
                    var ok = Modules.Any(m => dep.IsTypeOrSubType(m));
                    if (!ok)
                    {
                        ActivationLog.LogError($"Module {mod.Name} requires dependent module {dep} which is not included in the app.");
                    }
                }
            }
            CheckActivationErrors();

            //Build model
            var builder = new EntityModelBuilder(this);

            builder.BuildModel();
            CheckActivationErrors();

            //Notify modules that entity app is constructed
            foreach (var module in this.Modules)
            {
                module.Init();
            }
            //init services; note that service might be registered more than once, under different interface
            var servList = this.GetAllServices().Distinct().ToList();

            for (int i = 0; i < servList.Count; i++)
            {
                var service      = servList[i];
                var iServiceInit = service as IEntityServiceBase;
                if (iServiceInit != null)
                {
                    iServiceInit.Init(this);
                }
            }
            //complete initialization
            this.AppEvents.OnInitializing(EntityAppInitStep.Initialized);
            foreach (var module in this.Modules)
            {
                module.AppInitComplete();
            }

            builder.CheckErrors();
            Status = EntityAppStatus.Initialized;
            ActivationLog.WriteMessage("App {0} initialized.", this.AppName);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Writes all reachable modules and their (randomized) edges to the console for debugging purposes.
        /// </summary>
        public void WriteReachableToConsole()
        {
            foreach (var vertex in Reachable.Where(kvp => kvp.Value == true))
            {
                if (!Modules.Any(v => v.WarpCode == vertex.Key))
                {
                    continue;
                }
                var module = Modules.Find(v => v.WarpCode == vertex.Key);

                StringBuilder sb = new StringBuilder();
                sb.Append($"{module.WarpCode}");

                if (module.Tags.Count > 0)
                {
                    sb.Append($" [{module.Tags.Aggregate((i, j) => $"{i},{j}")}]");
                }

                if (!string.IsNullOrWhiteSpace(module.LockedTag))
                {
                    sb.Append($" -[{module.LockedTag}]-");
                }

                if (module.Unlock.Count > 0)
                {
                    sb.Append($" =[{module.Unlock.Aggregate((i, j) => $"{i},{j}")}]=");
                }

                sb.AppendLine();

                foreach (var edge in module.LeadsTo)
                {
                    sb.Append($"-> {edge.WarpCode} ({RandomLookup[edge.WarpCode]})");

                    if (edge.Tags.Count > 0)
                    {
                        sb.Append($" [{edge.Tags.Aggregate((i, j) => $"{i},{j}")}]");
                    }

                    if (edge.UnlockSets.Count > 0)
                    {
                        sb.Append(" =[");
                        foreach (var set in edge.UnlockSets)
                        {
                            sb.Append($"{set.Aggregate((i, j) => $"{i},{j}")};");
                        }
                        sb.Append("]=");
                    }

                    sb.AppendLine();
                }

                Console.Write(sb.ToString());
            }
        }
Exemplo n.º 10
0
            /// <summary>
            /// Load a mod .dll given its metadata at runtime. Doesn't load the mod content.
            /// If required, loads the mod after all of its dependencies have been loaded.
            /// </summary>
            /// <param name="meta">Metadata of the mod to load.</param>
            /// <param name="callback">Callback to be executed after the mod has been loaded. Executed immediately if meta == null.</param>
            public static void LoadModDelayed(EverestModuleMetadata meta, Action callback)
            {
                if (Flags.IsDisabled || !Flags.SupportRuntimeMods)
                {
                    Logger.Log(LogLevel.Warn, "loader", "Loader disabled!");
                    return;
                }

                if (meta == null)
                {
                    callback?.Invoke();
                    return;
                }

                if (Modules.Any(module => module.Metadata.Name == meta.Name))
                {
                    Logger.Log(LogLevel.Warn, "loader", $"Mod {meta.Name} already loaded!");
                    return;
                }

                if (PermanentBlacklist.TryGetValue(meta.Name, out Version minver) && meta.Version < minver)
                {
                    Logger.Log(LogLevel.Warn, "loader", $"Mod {meta} permanently blacklisted by Everest!");
                    return;
                }

                Tuple <string, Version, string, Version> conflictRow = PermanentConflictlist.FirstOrDefault(row =>
                                                                                                            (meta.Name == row.Item1 && meta.Version < row.Item2 && (_Modules.FirstOrDefault(other => other.Metadata.Name == row.Item3)?.Metadata.Version ?? _VersionInvalid) < row.Item4) ||
                                                                                                            (meta.Name == row.Item3 && meta.Version < row.Item4 && (_Modules.FirstOrDefault(other => other.Metadata.Name == row.Item1)?.Metadata.Version ?? _VersionInvalid) < row.Item2)
                                                                                                            );

                if (conflictRow != null)
                {
                    throw new Exception($"CONFLICTING MODS: {conflictRow.Item1} VS {conflictRow.Item3}");
                }


                foreach (EverestModuleMetadata dep in meta.Dependencies)
                {
                    if (!DependencyLoaded(dep))
                    {
                        Logger.Log(LogLevel.Info, "loader", $"Dependency {dep} of mod {meta} not loaded! Delaying.");
                        lock (Delayed) {
                            Delayed.Add(Tuple.Create(meta, callback));
                        }
                        return;
                    }
                }

                callback?.Invoke();

                LoadMod(meta);
            }
Exemplo n.º 11
0
 private void ExportPageModuleNav(MixPages.ImportViewModel item, MixCmsContext context, IDbContextTransaction transaction)
 {
     PageModuleNavs.AddRange(item.GetModuleNavs(context, transaction)
                             .Where(m => !PageModuleNavs.Any(n => n.ModuleId == m.ModuleId && n.PageId == m.PageId)));
     foreach (var nav in PageModuleNavs)
     {
         if (!Modules.Any(m => m.Id == nav.ModuleId && m.Specificulture == Specificulture))
         {
             Modules.Add(nav.Module);
         }
     }
 }
Exemplo n.º 12
0
        public static void UpdateInstalledModules()
        {
            AddInStore.Update(AddInPipelineRoot);
            var addins = AddInStore.FindAddIns(typeof(IModule), AddInPipelineRoot);

            foreach (var token in addins)
            {
                if (!Modules.Any(m => m._token.Equals(token)))
                {
                    Modules.Add(new Module(token));
                }
            }
        }
Exemplo n.º 13
0
        public IEnumerable <string> Validate()
        {
            if (Transport == null)
            {
                yield return("Transport implementation is not set. It is a required part of configuration.");
            }

            if (ClusterProvider == null)
            {
                yield return("Cluster provider implementation is not set. It is a required part of configuration.");
            }

            if (ResponseCriteria?.Count > 0)
            {
                var lastCriterion = ResponseCriteria.Last();
                if (!(lastCriterion is AlwaysRejectCriterion) && !(lastCriterion is AlwaysAcceptCriterion))
                {
                    yield return($"Last response criterion must always be either an '{typeof (AlwaysRejectCriterion).Name}' or '{typeof (AlwaysAcceptCriterion).Name}'.");
                }
            }

            if (ResponseCriteria != null && ResponseCriteria.Any(criterion => criterion == null))
            {
                yield return("One of provided response criteria is null");
            }

            if (RequestTransforms != null && RequestTransforms.Any(transform => transform == null))
            {
                yield return("One of provided request transforms is null");
            }

            if (ResponseTransforms != null && ResponseTransforms.Any(transform => transform == null))
            {
                yield return("One of provided response transforms is null");
            }

            if (Modules != null && Modules.Any(module => module == null))
            {
                yield return("One of provided request modules is null");
            }

            if (DefaultTimeout <= TimeSpan.Zero)
            {
                yield return($"Default timeout must be positive, but was '{DefaultTimeout}'");
            }

            if (MaxReplicasUsedPerRequest <= 0)
            {
                yield return($"Maximum replicas per request must be > 0, but was {MaxReplicasUsedPerRequest}");
            }
        }
Exemplo n.º 14
0
        public ThresholdTypeFlags GetThresholdTypesBelowThreshold(CoverageSummary summary, Dictionary <ThresholdTypeFlags, double> thresholdTypeFlagValues, ThresholdStatistic thresholdStat)
        {
            var thresholdTypeFlags = ThresholdTypeFlags.None;

            switch (thresholdStat)
            {
            case ThresholdStatistic.Minimum:
            {
                if (!Modules.Any())
                {
                    thresholdTypeFlags = CompareThresholdValues(thresholdTypeFlagValues, thresholdTypeFlags, 0, 0, 0);
                }

                foreach (var module in Modules)
                {
                    double line   = summary.CalculateLineCoverage(module.Value).Percent;
                    double branch = summary.CalculateBranchCoverage(module.Value).Percent;
                    double method = summary.CalculateMethodCoverage(module.Value).Percent;

                    thresholdTypeFlags = CompareThresholdValues(thresholdTypeFlagValues, thresholdTypeFlags, line, branch, method);
                }
            }
            break;

            case ThresholdStatistic.Average:
            {
                double line   = summary.CalculateLineCoverage(Modules).AverageModulePercent;
                double branch = summary.CalculateBranchCoverage(Modules).AverageModulePercent;
                double method = summary.CalculateMethodCoverage(Modules).AverageModulePercent;

                thresholdTypeFlags = CompareThresholdValues(thresholdTypeFlagValues, thresholdTypeFlags, line, branch, method);
            }
            break;

            case ThresholdStatistic.Total:
            {
                double line   = summary.CalculateLineCoverage(Modules).Percent;
                double branch = summary.CalculateBranchCoverage(Modules).Percent;
                double method = summary.CalculateMethodCoverage(Modules).Percent;

                thresholdTypeFlags = CompareThresholdValues(thresholdTypeFlagValues, thresholdTypeFlags, line, branch, method);
            }
            break;
            }

            return(thresholdTypeFlags);
        }
Exemplo n.º 15
0
        protected override CommandLineBuilder GetCommandLineBuilder()
        {
            var cmd = base.GetCommandLineBuilder();

            cmd.AppendSwitch("build-bundle");
            var modules = new List <string> ();

            modules.Add(BaseZip);
            if (Modules != null && Modules.Any())
            {
                modules.AddRange(Modules);
            }
            cmd.AppendSwitchIfNotNull("--modules ", string.Join(",", modules));
            cmd.AppendSwitchIfNotNull("--output ", Output);
            cmd.AppendSwitchIfNotNull("--config ", temp);
            return(cmd);
        }
Exemplo n.º 16
0
        public static void GetModules()
        {
            if (Modules.Any())
            {
                Modules.Clear();
            }

            if (!string.IsNullOrEmpty(Module.ModuleName) &&
                !Modules.ContainsKey(Module.ModuleName))
            {
                Modules
                .Cast <ProcessModule>()
                .ToList()
                .ForEach(m => Modules.Add(m.ModuleName,
                                          m.BaseAddress));
            }
        }
Exemplo n.º 17
0
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);
     if (!Modules.Any())
     {
         DialogResult = DialogResult.None;
     }
     else
     {
         var dataSource = new BindingList <XpandModule>(Modules);
         dataSource.ListChanged += DataSourceOnListChanged;
         gridControl1.DataSource = dataSource;
         gridControl1.Focus();
         gridView.Focus();
         gridView.FocusedColumn    = gridView.Columns.Cast <GridColumn>().First(column => column.FieldName == nameof(XpandModule.Module));
         gridView.FocusedRowHandle = GridControl.AutoFilterRowHandle;
     }
 }
Exemplo n.º 18
0
        private Bitness DetectBitness()
        {
            // In case we are a x64 process, we detect wether the inspected
            // window is running in Wow64 mode; if this is the case, the
            // inspected app is a 32bits application running on a x64 box.
            // Hope nobody will have the good idea to name one of its dll
            // wow64 in a 32bits app... ;)
            if (HawkeyeApplication.CurrentBitness == Bitness.x64)
            {
                var isWow64 = Modules.Any(
                    m => m.Name.ToLowerInvariant().Contains("wow64"));
                return(isWow64 ? Bitness.x86 : Bitness.x64);
            }

            // Otherwise, the test is simple: if we can detect modules,
            // it means the app is x86 (as we are).
            return(Modules.Length > 0 ? Bitness.x86 : Bitness.x64);
        }
Exemplo n.º 19
0
 public FurnitureFactoryDbContext(DbContextOptions <FurnitureFactoryDbContext> dbContextOptions) : base(dbContextOptions)
 {
     Database.EnsureCreated();
     if (!Modules.Any())
     {
         Modules.Add(new Module()
         {
             Name  = "TestName1",
             Price = 100.0
         });
         Modules.Add(new Module()
         {
             Name  = "TestName2",
             Price = 200.0
         });
         SaveChanges();
     }
 }
Exemplo n.º 20
0
        /// <inheritdoc />
        public override DifferenceDecoration GetDifferenceDecoration()
        {
            if (string.IsNullOrWhiteSpace(Map.OldType))
            {
                return(DifferenceDecoration.Added);
            }

            if (string.IsNullOrWhiteSpace(Map.NewType))
            {
                return(DifferenceDecoration.Deleted);
            }

            if (Modules.Any(moduleNode => moduleNode.DifferenceDecoration == DifferenceDecoration.Modified))
            {
                return(DifferenceDecoration.Modified);
            }

            return(DifferenceDecoration.NoDifferences);
        }
Exemplo n.º 21
0
        public FrameworkConfiguration(
            IServiceProvider clientServiceProvider,
            string defaultCommandPrefix,
            IEnumerable <ulong> ownerIDs,
            IEnumerable <ModuleInfo> modules,
            ICommunicator communicator,
            Action <ILoggingBuilder> loggingConfiguration,
            IFrameworkGuildConfigProvider guildConfigProvider,
            BaseSocketClient discordClient)
        {
            ClientServiceProvider = clientServiceProvider ?? throw new ArgumentNullException(nameof(clientServiceProvider));

            if (string.IsNullOrWhiteSpace(defaultCommandPrefix))
            {
                throw new ArgumentException(defaultCommandPrefix);
            }

            DefaultCommandPrefix = defaultCommandPrefix;

            LoggingConfiguration = loggingConfiguration ?? throw new ArgumentNullException(nameof(loggingConfiguration));
            GuildConfigProvider  = guildConfigProvider ?? throw new ArgumentNullException(nameof(guildConfigProvider));

            OwnerIDs = ownerIDs?.ToList() ?? throw new ArgumentNullException(nameof(ownerIDs));

            if (!OwnerIDs.Any())
            {
                throw new ArgumentException(nameof(ownerIDs));
            }

            Modules = modules?.ToList() ?? throw new ArgumentNullException(nameof(modules));

            if (!Modules.Any())
            {
                throw new ArgumentException(nameof(modules));
            }

            DiscordClient = discordClient ?? throw new ArgumentNullException(nameof(discordClient));
            Communicator  = communicator;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Enumera os módulos carregado pela thread principal do processo.
        /// </summary>
        public void GetModules()
        {
            if (Modules.Any())
            {
                Modules.Clear();
            }

            if (Process == null)
            {
                throw new ArgumentNullException(nameof(Process));
            }

            if (!string.IsNullOrEmpty(Module.ModuleName) &&
                !Modules.ContainsKey(Module.ModuleName))
            {
                Modules
                .Cast <ProcessModule>()
                .ToList()
                .ForEach(m => Modules.Add(m.ModuleName,
                                          m.BaseAddress));
            }
        }
Exemplo n.º 23
0
        public void SeedMembershipData()
        {
            var description = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +
                              "Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus " +
                              "et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, " +
                              "pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, " +
                              "aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. " +
                              "Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. " +
                              "Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. " +
                              "Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. " +
                              "Quisque rutrum. ";
            var email  = "[email protected]";
            var userId = string.Empty;

            if (Users.Any(r => r.Email.Equals(email)))
            {
                userId = Users.First(r => r.Email.Equals(email)).Id;
            }
            else
            {
                return;
            }

            if (!Instructors.Any())
            {
                var instructors = new List <Instructor>
                {
                    new Instructor
                    {
                        Name        = "John Doe",
                        Description = description.Substring(20, 50),
                        Thumbnail   = "/images/Ice-Age-Scrat-icon.png"
                    },
                    new Instructor
                    {
                        Name        = "Jane Doe",
                        Description = description.Substring(30, 40),
                        Thumbnail   = "/images/Ice-Age-Scrat-icon.png"
                    }
                };
                Instructors.AddRange(instructors);
                SaveChanges();
            }

            if (Instructors.Count() < 2)
            {
                return;
            }

            if (!Courses.Any())
            {
                var instructorId1 = Instructors.First().Id;
                var instructorId2 = Instructors.Skip(1).FirstOrDefault().Id;

                var courses = new List <Course>
                {
                    new Course {
                        InstructorId    = instructorId1,
                        Title           = "Course 1",
                        Description     = description,
                        ImageUrl        = "/images/course1.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course {
                        InstructorId    = instructorId2,
                        Title           = "Course 2",
                        Description     = description,
                        ImageUrl        = "/images/course2.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course {
                        InstructorId    = instructorId1,
                        Title           = "Course 3",
                        Description     = description,
                        ImageUrl        = "/images/course3.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    }
                };
                Courses.AddRange(courses);
                SaveChanges();
            }
            if (Courses.Count() < 3)
            {
                return;
            }

            var courseId1 = Courses.First().Id;
            var courseId2 = Courses.Skip(1).FirstOrDefault().Id;
            var courseId3 = Courses.Skip(2).FirstOrDefault().Id;

            if (!UserCourses.Any())
            {
                if (!courseId1.Equals(int.MinValue))
                {
                    UserCourses.Add(new UserCourse {
                        UserId = userId, CourseId = courseId1
                    });
                }

                if (!courseId2.Equals(int.MinValue))
                {
                    UserCourses.Add(new UserCourse {
                        UserId = userId, CourseId = courseId2
                    });
                }

                if (!courseId3.Equals(int.MinValue))
                {
                    UserCourses.Add(new UserCourse {
                        UserId = userId, CourseId = courseId3
                    });
                }

                SaveChanges();
            }

            if (UserCourses.Count() < 3)
            {
                return;
            }

            if (!Modules.Any())
            {
                var modules = new List <Module>
                {
                    new Module {
                        Course = Find <Course>(courseId1), Title = "Module 1"
                    },
                    new Module {
                        Course = Find <Course>(courseId2), Title = "Module 2"
                    },
                    new Module {
                        Course = Find <Course>(courseId3), Title = "Module 3"
                    }
                };
                Modules.AddRange(modules);
                SaveChanges();
            }

            if (Modules.Count() < 3)
            {
                return;
            }

            var module1 = Modules.First();
            var module2 = Modules.Skip(1).FirstOrDefault();
            var module3 = Modules.Skip(2).FirstOrDefault();

            if (!Videos.Any())
            {
                var videos = new List <Video> {
                    new Video {
                        ModuleId    = module1.Id,
                        CourseId    = courseId1,
                        Title       = "Video 1 Title",
                        Description = description.Substring(1, 35),
                        Duration    = 50, Thumbnail = "/images/video1.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module2.Id,
                        CourseId    = courseId2,
                        Title       = "Video 2 Title",
                        Description = description.Substring(5, 35),
                        Duration    = 45, Thumbnail = "/images/video2.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module3.Id,
                        CourseId    = courseId3,
                        Title       = "Video 3 Title",
                        Description = description.Substring(10, 35),
                        Duration    = 41, Thumbnail = "/images/video3.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module3.Id,
                        CourseId    = courseId2,
                        Title       = "Video 4 Title",
                        Description = description.Substring(15, 35),
                        Duration    = 41, Thumbnail = "/images/video4.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module2.Id,
                        CourseId    = courseId1,
                        Title       = "Video 5 Title",
                        Description = description.Substring(20, 35),
                        Duration    = 42, Thumbnail = "/images/video5.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    }
                };
                Videos.AddRange(videos);
                SaveChanges();
            }
            if (!Downloads.Any())
            {
                var downloads = new List <Download>
                {
                    new Download {
                        ModuleId = module1.Id, CourseId = courseId1,
                        Title    = "ADO.NET 1 (PDF)", Url = "https://some-url"
                    },

                    new Download {
                        ModuleId = module2.Id, CourseId = courseId2,
                        Title    = "ADO.NET 2 (PDF)", Url = "https://some-url"
                    },

                    new Download {
                        ModuleId = module3.Id, CourseId = courseId3,
                        Title    = "ADO.NET 1 (PDF)", Url = "https://some-url"
                    }
                };

                Downloads.AddRange(downloads);
                SaveChanges();
            }
        }
Exemplo n.º 24
0
        internal protected virtual void SaveToElement(PomXmlElement element)
        {
            //writing modules
            var modulesNode = element.ReadOrCreateElement("modules");

            if (!Modules.Any())
            {
                modulesNode.Remove();
            }
            else
            {
                modulesNode.RemoveAllChildElements();
                foreach (Module module in Modules)
                {
                    if (!string.IsNullOrEmpty(module.Path))
                    {
                        var moduleNode = modulesNode.CreateElement("module");
                        module.SaveTo(moduleNode);
                    }
                }
            }

            //writing dependencies
            var dependenciesNode = element.ReadOrCreateElement("dependencies");

            if (!Dependencies.Any())
            {
                dependenciesNode.Remove();
            }
            else
            {
                dependenciesNode.RemoveAllChildElements();
                foreach (Dependency dependency in Dependencies)
                {
                    var dependencyNode = dependenciesNode.CreateElement("dependency");
                    dependency.SaveToElement(dependencyNode);
                }
            }

            //writing properties
            var propertiesNode = element.ReadOrCreateElement("properties");

            if (!Properties.Any())
            {
                propertiesNode.Remove();
            }
            else
            {
                propertiesNode.RemoveAllChildElements();
                foreach (Property prop in Properties)
                {
                    prop.SaveTo(propertiesNode);
                }
            }

            var buildNode = element.ReadOrCreateElement("build");

            if (!Plugins.Any() && !PluginManagement.Any())             // empty build section
            {
                buildNode.Remove();
            }
            else
            {
                var pluginsNode = buildNode.ReadOrCreateElement("plugins");
                if (!Plugins.Any())
                {
                    pluginsNode.Remove();
                }
                else
                {
                    pluginsNode.RemoveAllChildElements();
                    foreach (Plugin plugin in Plugins)
                    {
                        var pluginNode = pluginsNode.CreateElement("plugin");
                        plugin.SaveToElement(pluginNode);
                    }
                }

                var pluginManagementNode        = buildNode.ReadOrCreateElement("pluginManagement");
                var pluginManagementPluginsNode = pluginManagementNode.ReadOrCreateElement("plugins");

                if (!PluginManagement.Any())
                {
                    pluginManagementNode.Remove();
                }
                else
                {
                    pluginManagementPluginsNode.RemoveAllChildElements();
                    foreach (Plugin plugin in PluginManagement)
                    {
                        var pluginNode = pluginManagementPluginsNode.CreateElement("plugin");
                        plugin.SaveToElement(pluginNode);
                    }
                }
            }
        }
Exemplo n.º 25
0
        public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            Cultures = LoadCultures(Specificulture, _context, _transaction);

            if (!string.IsNullOrEmpty(this.Tags))
            {
                ListTag = JArray.Parse(this.Tags);
            }
            Properties = new List <ExtraProperty>();
            if (!string.IsNullOrEmpty(ExtraProperties))
            {
                JArray arr = JArray.Parse(ExtraProperties);
                foreach (JToken item in arr)
                {
                    Properties.Add(item.ToObject <ExtraProperty>());
                }
            }

            //Get Templates
            this.Templates = this.Templates ?? MixTemplates.UpdateViewModel.Repository.GetModelListBy(
                t => t.Theme.Name == ActivedTheme && t.FolderType == this.TemplateFolderType).Data;
            View = MixTemplates.UpdateViewModel.GetTemplateByPath(Template, Specificulture, MixEnums.EnumTemplateFolder.Articles, _context, _transaction);

            this.Template = CommonHelper.GetFullPath(new string[]
            {
                this.View?.FileFolder
                , this.View?.FileName
            });

            var getPageArticle = MixPageArticles.ReadViewModel.GetPageArticleNavAsync(Id, Specificulture, _context, _transaction);

            if (getPageArticle.IsSucceed)
            {
                this.Pages = getPageArticle.Data;
                this.Pages.ForEach(c =>
                {
                    c.IsActived = MixPageArticles.ReadViewModel.Repository.CheckIsExists(n => n.CategoryId == c.CategoryId && n.ArticleId == Id, _context, _transaction);
                });
            }

            var getModuleArticle = MixModuleArticles.ReadViewModel.GetModuleArticleNavAsync(Id, Specificulture, _context, _transaction);

            if (getModuleArticle.IsSucceed)
            {
                this.Modules = getModuleArticle.Data;
                this.Modules.ForEach(c =>
                {
                    c.IsActived = MixModuleArticles.ReadViewModel.Repository.CheckIsExists(n => n.ModuleId == c.ModuleId && n.ArticleId == Id, _context, _transaction);
                });
            }
            var otherModules = MixModules.ReadListItemViewModel.Repository.GetModelListBy(
                m => (m.Type == (int)MixEnums.MixModuleType.Content || m.Type == (int)MixEnums.MixModuleType.ListArticle) &&
                m.Specificulture == Specificulture &&
                !Modules.Any(n => n.ModuleId == m.Id && n.Specificulture == m.Specificulture)
                , "CreatedDateTime", 1, null, 0, _context, _transaction);

            foreach (var item in otherModules.Data.Items)
            {
                Modules.Add(new MixModuleArticles.ReadViewModel()
                {
                    ModuleId    = item.Id,
                    Image       = item.Image,
                    ArticleId   = Id,
                    Description = item.Title
                });
            }

            // Medias
            var getArticleMedia = MixArticleMedias.ReadViewModel.Repository.GetModelListBy(n => n.ArticleId == Id && n.Specificulture == Specificulture, _context, _transaction);

            if (getArticleMedia.IsSucceed)
            {
                MediaNavs = getArticleMedia.Data.OrderBy(p => p.Priority).ToList();
                MediaNavs.ForEach(n => n.IsActived = true);
            }
            // var otherMedias = MixMedias.UpdateViewModel.Repository.GetModelListBy(m => !MediaNavs.Any(n => n.MediaId == m.Id), "CreatedDateTime", 1, 10, 0, _context, _transaction);
            // foreach (var item in otherMedias.Data.Items)
            // {
            //     MediaNavs.Add(new MixArticleMedias.ReadViewModel()
            //     {
            //         MediaId = item.Id,
            //         Image = item.FullPath,
            //         ArticleId = Id,
            //         Description = item.Title
            //     });
            // }
            // Modules
            var getArticleModule = MixArticleModules.ReadViewModel.Repository.GetModelListBy(
                n => n.ArticleId == Id && n.Specificulture == Specificulture, _context, _transaction);

            if (getArticleModule.IsSucceed)
            {
                ModuleNavs = getArticleModule.Data.OrderBy(p => p.Priority).ToList();
                foreach (var item in ModuleNavs)
                {
                    item.IsActived = true;
                    item.Module.LoadData(articleId: Id, _context: _context, _transaction: _transaction);
                }
            }
            var otherModuleNavs = MixModules.ReadMvcViewModel.Repository.GetModelListBy(
                m => (m.Type == (int)MixEnums.MixModuleType.SubArticle) && m.Specificulture == Specificulture &&
                !ModuleNavs.Any(n => n.ModuleId == m.Id), "CreatedDateTime", 1, null, 0, _context, _transaction);

            foreach (var item in otherModuleNavs.Data.Items)
            {
                item.LoadData(articleId: Id, _context: _context, _transaction: _transaction);
                ModuleNavs.Add(new MixArticleModules.ReadViewModel()
                {
                    ModuleId    = item.Id,
                    Image       = item.Image,
                    ArticleId   = Id,
                    Description = item.Title,
                    Module      = item
                });
            }

            // Related Articles
            ArticleNavs = GetRelated(_context, _transaction);
            var otherArticles = MixArticles.ReadListItemViewModel.Repository.GetModelListBy(m => !ArticleNavs.Any(n => n.SourceId == m.Id), "CreatedDateTime", 1, 10, 0, _context, _transaction);

            foreach (var item in otherArticles.Data.Items)
            {
                ArticleNavs.Add(new MixArticleArticles.ReadViewModel()
                {
                    SourceId      = Id,
                    Image         = item.ImageUrl,
                    DestinationId = item.Id,
                    Description   = item.Title
                });
            }
        }
Exemplo n.º 26
0
        public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            if (Id == 0)
            {
                ExtraFields = MixService.GetConfig <string>("DefaultPostAttr");
            }
            Cultures   = LoadCultures(Specificulture, _context, _transaction);
            UrlAliases = GetAliases(_context, _transaction);
            if (!string.IsNullOrEmpty(this.Tags))
            {
                ListTag = JArray.Parse(this.Tags);
            }

            // Parsing Extra Properties fields
            Columns = new List <ModuleFieldViewModel>();
            JArray arrField = !string.IsNullOrEmpty(ExtraFields) ? JArray.Parse(ExtraFields) : new JArray();

            foreach (var field in arrField)
            {
                ModuleFieldViewModel thisField = new ModuleFieldViewModel()
                {
                    Name       = MixCommonHelper.ParseJsonPropertyName(field["name"].ToString()),
                    Title      = field["title"]?.ToString(),
                    Options    = field["options"] != null ? field["options"].Value <JArray>() : new JArray(),
                    Priority   = field["priority"] != null ? field["priority"].Value <int>() : 0,
                    DataType   = (MixDataType)(int)field["dataType"],
                    Width      = field["width"] != null ? field["width"].Value <int>() : 3,
                    IsUnique   = field["isUnique"] != null ? field["isUnique"].Value <bool>() : true,
                    IsRequired = field["isRequired"] != null ? field["isRequired"].Value <bool>() : true,
                    IsDisplay  = field["isDisplay"] != null ? field["isDisplay"].Value <bool>() : true,
                    IsSelect   = field["isSelect"] != null ? field["isSelect"].Value <bool>() : false,
                    IsGroupBy  = field["isGroupBy"] != null ? field["isGroupBy"].Value <bool>() : false,
                };
                Columns.Add(thisField);
            }

            // Parsing Extra Properties value
            Properties = new List <ExtraProperty>();

            if (!string.IsNullOrEmpty(ExtraProperties))
            {
                JArray arr = JArray.Parse(ExtraProperties);
                foreach (JToken item in arr)
                {
                    Properties.Add(item.ToObject <ExtraProperty>());
                }
            }
            //Get Templates
            this.Templates = this.Templates ?? MixTemplates.UpdateViewModel.Repository.GetModelListBy(
                t => t.Theme.Id == ActivedTheme && t.FolderType == this.TemplateFolderType).Data;
            View = MixTemplates.UpdateViewModel.GetTemplateByPath(Template, Specificulture, MixTemplateFolders.Posts, _context, _transaction);

            this.Template = $"{this.View?.FileFolder}/{this.View?.FileName}";

            var getPagePost = MixPagePosts.ReadViewModel.GetPagePostNavAsync(Id, Specificulture, _context, _transaction);

            if (getPagePost.IsSucceed)
            {
                this.Pages = getPagePost.Data;
                this.Pages.ForEach(c =>
                {
                    c.IsActived = MixPagePosts.ReadViewModel.Repository.CheckIsExists(n => n.PageId == c.PageId && n.PostId == Id, _context, _transaction);
                });
            }

            var getModulePost = MixModulePosts.ReadViewModel.GetModulePostNavAsync(Id, Specificulture, _context, _transaction);

            if (getModulePost.IsSucceed)
            {
                this.Modules = getModulePost.Data;
                this.Modules.ForEach(c =>
                {
                    c.IsActived = MixModulePosts.ReadViewModel.Repository.CheckIsExists(n => n.ModuleId == c.ModuleId && n.PostId == Id, _context, _transaction);
                });
            }
            var otherModules = MixModules.ReadListItemViewModel.Repository.GetModelListBy(
                m => (m.Type == (int)MixModuleType.Content || m.Type == (int)MixModuleType.ListPost) &&
                m.Specificulture == Specificulture &&
                !Modules.Any(n => n.ModuleId == m.Id && n.Specificulture == m.Specificulture)
                , "CreatedDateTime", Heart.Enums.DisplayDirection.Desc, null, 0, _context, _transaction);

            foreach (var item in otherModules.Data.Items)
            {
                Modules.Add(new MixModulePosts.ReadViewModel()
                {
                    ModuleId    = item.Id,
                    Image       = item.Image,
                    PostId      = Id,
                    Description = Title
                });
            }

            // Medias
            var getPostMedia = MixPostMedias.ReadViewModel.Repository.GetModelListBy(n => n.PostId == Id && n.Specificulture == Specificulture, _context, _transaction);

            if (getPostMedia.IsSucceed)
            {
                MediaNavs = getPostMedia.Data.OrderBy(p => p.Priority).ToList();
                MediaNavs.ForEach(n => n.IsActived = true);
            }
            // Modules
            var getPostModule = MixPostModules.ReadViewModel.Repository.GetModelListBy(
                n => n.PostId == Id && n.Specificulture == Specificulture, _context, _transaction);

            if (getPostModule.IsSucceed)
            {
                ModuleNavs = getPostModule.Data.OrderBy(p => p.Priority).ToList();
                foreach (var item in ModuleNavs)
                {
                    item.IsActived = true;
                    item.Module.LoadData(postId: Id, _context: _context, _transaction: _transaction);
                }
            }

            // Related Posts
            PostNavs = GetRelated(_context, _transaction);
            var otherPosts = MixPosts.ReadListItemViewModel.Repository.GetModelListBy(
                m => m.Id != Id && m.Specificulture == Specificulture &&
                !PostNavs.Any(n => n.SourceId == Id)
                , "CreatedDateTime", Heart.Enums.DisplayDirection.Desc, 10, 0, _context, _transaction);

            foreach (var item in otherPosts.Data.Items)
            {
                PostNavs.Add(new MixPostPosts.ReadViewModel()
                {
                    SourceId      = Id,
                    Image         = item.ImageUrl,
                    DestinationId = item.Id,
                    Description   = item.Title
                });
            }
        }
Exemplo n.º 27
0
        /// <summary>Initializes the entity app. </summary>
        /// <remarks>Call this method after you finished composing entity application of modules.
        /// The method is called automatically when you connect the application to the database
        /// with <c>ConnectTo()</c> extension method.</remarks>
        public virtual void Init()
        {
            if (Status != EntityAppStatus.Created)
            {
                return;
            }
            Status = EntityAppStatus.Initializing;
            SystemLog.Info("Initializing app {0}...", this.AppName);
            this.AppEvents.OnInitializing(EntityAppInitStep.Initializing);
            //Check dependencies
            foreach (var mod in this.Modules)
            {
                var depList = mod.GetDependencies();
                foreach (var dep in depList)
                {
                    var ok = Modules.Any(m => dep.IsTypeOrSubType(m));
                    if (!ok)
                    {
                        this.SystemLog.Error("Module {0} requires dependent module {1} which is not included in the app.", mod.GetType(), dep);
                    }
                }
            }
            this.CheckActivationErrors();
            // Init linked apps
            foreach (var linkedApp in LinkedApps)
            {
                linkedApp.Init();
            }
            // create default services, possibly importing from LinkedApps
            CreateDefaultServices();
            // Create log file writer
            if (!string.IsNullOrWhiteSpace(_logFilePath))
            {
                _logFileWriter = new LogFileWriter(this, _logFilePath);
            }

            //Build model
            SystemLog.Info("  Building entity model...", this.AppName);
            var modelBuilder = new EntityModelBuilder(this);

            modelBuilder.BuildModel();
            if (SystemLog.HasErrors)
            {
                var errors = SystemLog.GetAllAsText();
                throw new StartupFailureException("Entity model build failed.", errors);
            }
            //Notify modules that entity app is constructed
            foreach (var module in this.Modules)
            {
                module.Init();
            }
            //init services
            var servList = this.GetAllServices();

            for (int i = 0; i < servList.Count; i++)
            {
                var service      = servList[i];
                var iServiceInit = service as IEntityService;
                if (iServiceInit != null)
                {
                    iServiceInit.Init(this);
                }
            }
            //complete initialization
            this.AppEvents.OnInitializing(EntityAppInitStep.Initialized);
            foreach (var module in this.Modules)
            {
                module.AppInitComplete();
            }

            CheckActivationErrors();
            Status = EntityAppStatus.Initialized;
            SystemLog.Info("  App {0} initialized.", this.AppName);
        }
Exemplo n.º 28
0
        private string GetMenu(User user = null, bool drawActions = true)
        {
            bool showTooltips = user?.Config?.Tooltips ?? true;

            StringBuilder panel = new StringBuilder();

            panel.AppendLine("> **Help Menu**");

            if (showTooltips)
            {
                panel.AppendLine("> 🛠️ Use `help <name>` to learn more about a command or category.");
            }

            // TODO: Handle report status icon management
            if (Guides?.Any() ?? false)
            {
                panel.AppendLine();
                panel.AppendLine("**Guides**");

                foreach (GuideNode guide in Guides)
                {
                    panel.AppendLine($"> {guide.Tooltip}");
                }
            }

            if (Modules.Any())
            {
                panel.AppendLine();
                panel.AppendLine("**Categories**");

                foreach (ModuleNode module in GetBaseModules().Select(x => new ModuleNode(x)))
                {
                    panel.Append("> ");

                    if (Check.NotNull(module.Icon))
                    {
                        panel.Append($"{module.Icon} ");
                    }

                    panel.Append($"**{module.Name}**");

                    if (Check.NotNull(module.Subtitle) || module.Commands.Count > 0)
                    {
                        panel.Append(": ");
                    }

                    if (Check.NotNull(module.Subtitle))
                    {
                        panel.AppendLine(module.Subtitle);
                    }

                    if (module.Commands.Count > 0)
                    {
                        if (Check.NotNull(module.Subtitle))
                        {
                            panel.Append("> ");
                        }

                        int inserted = 0;
                        foreach (CommandNode command in module.Commands.OrderBy(x => x.Name))
                        {
                            if (inserted >= MAX_COMMAND_DISPLAY)
                            {
                                break;
                            }

                            if (inserted > 0)
                            {
                                panel.Append(" ");
                            }

                            panel.Append($"`{command.Name}`");

                            inserted++;
                        }

                        if (module.Commands.Count() - inserted > 0)
                        {
                            panel.Append($" (+**{module.Commands.Count() - inserted}** more)");
                        }

                        panel.AppendLine();
                    }
                    else
                    {
                        panel.Append("...");
                        panel.AppendLine();
                    }
                }
            }

            //if (user != null && drawActions)
            //   if (user.Husk != null)
            //       panel.Append(GetActions(user));

            return(panel.ToString());
        }
Exemplo n.º 29
0
        public void SeedMembershipData()
        {
            #region Lorem Ipsum - Dummy Data
            var description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
            #endregion

            #region Fetch a User
            var email  = "[email protected]";
            var userId = string.Empty;

            if (Users.Any(r => r.Email.Equals(email)))
            {
                userId = Users.First(r => r.Email.Equals(email)).Id;
            }
            else
            {
                return;
            }
            #endregion

            #region Add Instructors if they don't already exist
            if (!Instructors.Any())
            {
                var instructors = new List <Instructor>
                {
                    new Instructor {
                        Name        = "John Doe",
                        Description = description.Substring(20, 50),
                        Thumbnail   = "/images/Ice-Age-Scrat-icon.png"
                    },
                    new Instructor {
                        Name        = "Jane Doe",
                        Description = description.Substring(30, 40),
                        Thumbnail   = "/images/Ice-Age-Scrat-icon.png"
                    }
                };
                Instructors.AddRange(instructors);
                SaveChanges();
            }
            if (Instructors.Count() < 2)
            {
                return;
            }
            #endregion

            #region Add Courses if they don't already exist
            if (!Courses.Any())
            {
                var instructorId1 = Instructors.First().Id;
                var instructorId2 = Instructors.Skip(1).FirstOrDefault().Id;

                var courses = new List <Course>
                {
                    new Course {
                        InstructorId    = instructorId1,
                        Title           = "Course 1",
                        Description     = description,
                        ImageUrl        = "/images/course1.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course {
                        InstructorId    = instructorId2,
                        Title           = "Course 2",
                        Description     = description,
                        ImageUrl        = "/images/course2.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course {
                        InstructorId    = instructorId1,
                        Title           = "Course 3",
                        Description     = description,
                        ImageUrl        = "/images/course3.jpg",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    }
                };
                Courses.AddRange(courses);
                SaveChanges();
            }
            if (Courses.Count() < 3)
            {
                return;
            }
            #endregion

            #region Fetch Course ids if any courses exists
            var courseId1 = Courses.First().Id;
            var courseId2 = Courses.Skip(1).FirstOrDefault().Id;
            var courseId3 = Courses.Skip(2).FirstOrDefault().Id;
            #endregion

            #region Add UserCourses connections if they don't already exist
            if (!UserCourses.Any())
            {
                UserCourses.Add(new UserCourse {
                    UserId = userId, CourseId = courseId1
                });
                UserCourses.Add(new UserCourse {
                    UserId = userId, CourseId = courseId2
                });
                UserCourses.Add(new UserCourse {
                    UserId = userId, CourseId = courseId3
                });

                SaveChanges();
            }
            if (UserCourses.Count() < 3)
            {
                return;
            }
            #endregion

            #region Add Modules if they don't already exist
            if (!Modules.Any())
            {
                var modules = new List <Module>
                {
                    new Module {
                        Course = Find <Course>(courseId1), Title = "Modeule 1"
                    },
                    new Module {
                        Course = Find <Course>(courseId1), Title = "Modeule 2"
                    },
                    new Module {
                        Course = Find <Course>(courseId2), Title = "Modeule 3"
                    }
                };
                Modules.AddRange(modules);
                SaveChanges();
            }
            if (Modules.Count() < 3)
            {
                return;
            }
            #endregion

            #region Fetch Module ids if any modules exist
            var module1 = Modules.First();
            var module2 = Modules.Skip(1).FirstOrDefault();
            var module3 = Modules.Skip(2).FirstOrDefault();
            #endregion

            #region Add Videos if they don't already exist
            if (!Videos.Any())
            {
                var videos = new List <Video>
                {
                    new Video {
                        ModuleId    = module1.Id, CourseId = module1.CourseId,
                        Title       = "Video 1 Title",
                        Description = description.Substring(1, 35),
                        Duration    = 50, Thumbnail = "/images/video1.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module1.Id, CourseId = module1.CourseId,
                        Title       = "Video 2 Title",
                        Description = description.Substring(5, 35),
                        Duration    = 45, Thumbnail = "/images/video2.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module1.Id, CourseId = module1.CourseId,
                        Title       = "Video 3 Title",
                        Description = description.Substring(10, 35),
                        Duration    = 41, Thumbnail = "/images/video3.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module3.Id, CourseId = module3.CourseId,
                        Title       = "Video 4 Title",
                        Description = description.Substring(15, 35),
                        Duration    = 41, Thumbnail = "/images/video4.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    },
                    new Video {
                        ModuleId    = module2.Id, CourseId = module2.CourseId,
                        Title       = "Video 5 Title",
                        Description = description.Substring(20, 35),
                        Duration    = 42, Thumbnail = "/images/video5.jpg",
                        Url         = "https://www.youtube.com/embed/BJFyzpBcaCY"
                    }
                };
                Videos.AddRange(videos);
                SaveChanges();
            }
            #endregion

            #region Add Downloads if they don't already exist
            if (!Downloads.Any())
            {
                var downloads = new List <Download>
                {
                    new Download {
                        ModuleId = module1.Id, CourseId = module1.CourseId,
                        Title    = "ADO.NET 1 (PDF)", Url = "https://some-url"
                    },

                    new Download {
                        ModuleId = module1.Id, CourseId = module1.CourseId,
                        Title    = "ADO.NET 2 (PDF)", Url = "https://some-url"
                    },

                    new Download {
                        ModuleId = module3.Id, CourseId = module3.CourseId,
                        Title    = "ADO.NET 1 (PDF)", Url = "https://some-url"
                    }
                };

                Downloads.AddRange(downloads);
                SaveChanges();
            }
            #endregion
        }
Exemplo n.º 30
0
        public void SeedMembershipData()
        {
            var description1 =
                "C# is a simple, modern, general-purpose, object-oriented programming language" +
                " developed by Microsoft within its .NET initiative led by Anders Hejlsberg.";
            var description2 = "JavaScript is a fun and flexible programming language." +
                               " It's one of the core technologies of web development" +
                               " and can be used on both the front-end and the ..";
            var description3 = "HTML is the World Wide Web's core markup language. Originally," +
                               " HTML was primarily designed as a language for semantically describing ";

            #region Fetch a User

            var email = "a.b@c";
            var userId = string.Empty;

            if (Users.Any(r => r.Email.Equals(email)))
                userId = Users.First(r => r.Email.Equals(email)).Id;
            else
                return;

            #endregion Fetch a User

            #region Add Instructors if they don't already exist

            if (!Instructors.Any())
            {
                var instructors = new List<Instructor>
                {
                    new Instructor
                    {
                        Name = "Garad Gafadi",
                        Description =
                            "Garad Gafadi is a software developer and a future co-founder of OneLove Corporation.",

                        Thumbnail = "/images/avatar2.jpg"
                    },
                    new Instructor
                    {
                        Name = "Adam Ganays",
                        Description = "Adam is a software developer and a future co-founder of OneLove Corporation.",
                        Thumbnail = " /Images/avatar.png"
                    },
                    new Instructor
                    {
                        Name = "Lovisa Jonsson",
                        Description = "Adam is a software developer and a future co-founder of OneLove Corporation.",
                        Thumbnail = " /Images/avatar.png"
                    }
                };
                Instructors.AddRange(instructors);
                SaveChanges();
            }

            if (Instructors.Count() < 3) return;

            #endregion Add Instructors if they don't already exist

            #region Add Courses if they don't already exist

            if (!Courses.Any())
            {
                var instructorId1 = Instructors.First().Id;
                var instructorId2 = Instructors.Skip(1).FirstOrDefault().Id;
                var instructorId3 = Instructors.Skip(2).FirstOrDefault().Id;

                var courses = new List<Course>
                {
                    new Course
                    {
                        InstructorId = instructorId1,
                        Title = "C#",
                        Description = description1,
                        ImageUrl = "/Images/cours1.jpg",
                        MarqueeImageUrl = "/Images/laptop.jpg"
                    },
                    new Course
                    {
                        InstructorId = instructorId2,
                        Title = "JavaScript",
                        Description = description2,
                        ImageUrl = "/Images/cours2.png",
                        MarqueeImageUrl = "/images/laptop.jpg"
                    },
                    new Course
                    {
                        InstructorId = instructorId3,
                        Title = "HMTL",
                        Description = description3,
                        ImageUrl = "/Images/cours3.png",
                        MarqueeImageUrl = "/Images/laptop.jpg"
                    }
                };
                Courses.AddRange(courses);
                SaveChanges();
            }

            if (Courses.Count() < 3) return;

            #endregion Add Courses if they don't already exist

            #region Fetch Course ids if any courses exists

            var courseId1 = Courses.First().Id;
            var courseId2 = Courses.Skip(1).FirstOrDefault().Id;
            var courseId3 = Courses.Skip(2).FirstOrDefault().Id;

            #endregion Fetch Course ids if any courses exists

            #region Add UserCourses connections if they don't already exist

            if (!UserCourses.Any())
            {
                UserCourses.Add(new UserCourse {UserId = userId, CourseId = courseId1});
                UserCourses.Add(new UserCourse {UserId = userId, CourseId = courseId2});
                UserCourses.Add(new UserCourse {UserId = userId, CourseId = courseId3});

                SaveChanges();
            }

            if (UserCourses.Count() < 3) return;

            #endregion Add UserCourses connections if they don't already exist

            #region Add Modules if they don't already exist

            if (!Modules.Any())
            {
                var modules = new List<Module>
                {
                    new Module
                    {
                        Course = Find<Course>(courseId1), Title = "Module 1"
                    },

                    new Module
                    {
                        Course = Find<Course>(courseId2), Title = "Module 2"
                    },
                    new Module
                    {
                        Course = Find<Course>(courseId3), Title = "Module 3"
                    }
                };
                Modules.AddRange(modules);
                SaveChanges();
            }

            if (Modules.Count() < 3) return;

            #endregion Add Modules if they don't already exist

            #region Fetch Module ids if any modules exist

            var moduleId1 = Modules.First().Id;
            var moduleId2 = Modules.Skip(1).FirstOrDefault().Id;
            var moduleId3 = Modules.Skip(2).FirstOrDefault().Id;

            #endregion Fetch Module ids if any modules exist

            #region Add Videos if they don't already exist

            if (!Videos.Any())
            {
                var video = new List<Video>
                {
                    new Video
                    {
                        ModuleId = moduleId1, CourseId = courseId1, Title = "C# Toturial1",
                        Description = description1.Substring(1, 100),
                        Thumbnail = "/images/video1.jpg",
                        Duration = 14, Url = "https://youtu.be/yK6zlTVqWzo"
                    },

                    new Video
                    {
                        ModuleId = moduleId1, CourseId = courseId1, Title = "JavaScript For Beginers",
                        Description = description2.Substring(1, 50),
                        Thumbnail = "/images/video2.jpg",
                        Duration = 48, Url = "https://www.youtube.com/watch?v=qv6ZflueASY"
                    },

                    new Video
                    {
                        ModuleId = moduleId1, CourseId = courseId1, Title = "HTML For Beginers",
                        Description = description3.Substring(1, 80),
                        Thumbnail = "/images/video3.jpg",
                        Duration = 12, Url = "https://youtu.be/bWPMSSsVdPk"
                    },

                    new Video
                    {
                        ModuleId = moduleId2, CourseId = courseId2, Title = "JavaScript For Beginers",
                        Description = description2.Substring(1, 50),
                        Thumbnail = "/images/video2.jpg",
                        Duration = 48, Url = "https://youtu.be/W6NZfCO5SIk"
                    },

                    new Video
                    {
                        ModuleId = moduleId2, CourseId = courseId2, Title = "HTML For Beginers",
                        Description = description3.Substring(1, 80),
                        Thumbnail = "/images/video3.jpg",
                        Duration = 12, Url = "https://youtu.be/bWPMSSsVdPk"
                    },
                    new Video
                    {
                        ModuleId = moduleId3, CourseId = courseId2, Title = "JavaScript For Beginers",
                        Description = description2.Substring(1, 50),
                        Thumbnail = "/images/video2.jpg",
                        Duration = 48, Url = "https://youtu.be/W6NZfCO5SIk"
                    },

                    new Video
                    {
                        ModuleId = moduleId3, CourseId = courseId2, Title = "HTML For Beginers",
                        Description = description3.Substring(1, 80),
                        Thumbnail = "/images/video3.jpg",
                        Duration = 12, Url = "https://youtu.be/bWPMSSsVdPk"
                    }
                };
                Videos.AddRange(video);
                SaveChanges();
            }

            #endregion Add Videos if they don't already exist

            #region Add Downloads if they don't already exist

            if (!Downloads.Any())
            {
                var downloads = new List<Download>
                {
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId1, Title = "C# Toturials (PDF)",
                        Url = "https://some-url"
                    },
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId1, Title = "JavaScript Toturials (PDF)",
                        Url = "https://some-url"
                    },
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId1, Title = "HTML Toturials (PDF)",
                        Url = "https://some-url"
                    },
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId2, Title = "JavaScript Toturials (PDF)",
                        Url = "https://some-url"
                    },
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId2, Title = "HTML Toturials (PDF)",
                        Url = "https://some-url"
                    },
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId3, Title = "JavaScript Toturials (PDF)",
                        Url = "https://some-url"
                    },
                    new Download
                    {
                        ModuleId = moduleId1, CourseId = courseId3, Title = "HTML Toturials (PDF)",
                        Url = "https://some-url"
                    }
                };

                Downloads.AddRange(downloads);
                SaveChanges();
            }

            #endregion Add Downloads if they don't already exist
        }