public override void Init()
        {
            base.Init();

            _resourceRepository = new ResourceRepository(_container);
            _cacheFileService = _container.Resolve<ICacheFileService>();
        }
        public override void Execute()
        {
            var subject = string.Format("Resource Planning {0} - {1}", _viewPeriod.StartDate.ToDutchString(), _viewPeriod.EndDate.ToDutchString());
            var rep = new ResourceRepository();
            var resources = rep.GetItems();
            var builder = new StringBuilder();

            foreach (var res in resources)
            {
                builder.Append("\n***********************************************");
                builder.Append(string.Format("\n{0}:", res.DisplayName));
                foreach (var ass in res.Assignments.Where(x => x.Period.Overlaps(_viewPeriod)))
                {
                    var overlap = ass.Period.OverlappingPeriod(_viewPeriod);
                    builder.Append(string.Format("\n{0} - {1}:", overlap.StartDate.ToDutchString(), overlap.EndDate.ToDutchString()));
                    builder.Append(string.Format("\n{0} - {1} - {2}: {3} ({4}%)", ass.Phase.Title, ass.Project.Title, ass.Deliverable.Title, ass.Activity.Title, ass.FocusFactor * 100));
                    builder.Append(string.Format("\nDeadline {0}: {1}", ass.Deliverable.Title, ass.Milestone.Date.ToDutchString()));
                    builder.Append("\n----------------------------------------------");
                }
                foreach (var abs in res.PeriodsAway.Where(x => x.Period.Overlaps(_viewPeriod)))
                {
                    builder.Append(string.Format("\nAbsent: {0} - {1} {2}", abs.StartDate.ToDutchString(), abs.EndDate.ToDutchString(), abs.Title));
                }
                builder.Append("\n***********************************************");
                builder.Append("\n\n");
            }
            var content = builder.ToString();
            _mailer.SendMail("*****@*****.**", subject, content);
        }
 public VisualFingerprintMatchingFrm(IMatcher matcher, IResourceProvider resourceProvider, string resourcePath)
 {
     InitializeComponent();
     this.matcher = matcher;
     provider = resourceProvider;
     this.resourcePath = resourcePath;
     repository = new ResourceRepository(resourcePath);
 }
Beispiel #4
0
        public void Get_WithValidKeyAndPartitionWithTwoResourcesInDb_GetOneResource()
        {
            var repository = new ResourceRepository(_resourceContext);
            var resource   = repository.Get("key3", "part2");

            resource.ShouldNotBe(null);
            resource.Key.ShouldBe("key3");
            resource.Partition.ShouldBe("part2");
        }
Beispiel #5
0
        public void DeleteResource_GetNull()
        {
            var resourceRepository = new ResourceRepository(_resourceContext);
            var resource1          = resourceRepository.Get("key1", "part1");

            resourceRepository.Delete(resource1);

            resourceRepository.Get("key1", "part1").ShouldBeNull();
        }
Beispiel #6
0
        //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethoNd().DeclaringType);

        public FavoriteManager(AuthenticationManager authenticationManager, CatalogValueRepository catalogValueRepository,
                               ResourceRepository resourceRepository, FavoritesRepository favoritesRepository, IMapper mapper)
        {
            m_authenticationManager  = authenticationManager;
            m_catalogValueRepository = catalogValueRepository;
            m_favoritesRepository    = favoritesRepository;
            m_mapper             = mapper;
            m_resourceRepository = resourceRepository;
        }
Beispiel #7
0
 public CreateEmptyTextResourceWork(ResourceRepository resourceRepository, long pageId, CreateTextRequestContract data,
                                    int userId, IFulltextStorage fulltextStorage) : base(resourceRepository)
 {
     m_resourceRepository = resourceRepository;
     m_pageId             = pageId;
     m_data            = data;
     m_userId          = userId;
     m_fulltextStorage = fulltextStorage;
 }
Beispiel #8
0
        public void List_WithValidPartitionWithOneResourceInDb_GetSingleResource()
        {
            var repository = new ResourceRepository(_resourceContext);
            var resources  = repository.List("part1").ToList();

            resources.Count.ShouldBe(1);

            resources[0].Key.ShouldBe("key1");
        }
Beispiel #9
0
        public TestResourceControllerMockery WithNoExistingResource()
        {
            ResourceRepository.Setup(r => r.Load(
                                         It.IsAny <Guid>()
                                         ))
            .Returns((TestEntity)null);

            return(this);
        }
Beispiel #10
0
        public async Task <HttpResponseMessage> Upload()
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
                }

                var provider = GetMultipartProvider();
                var result   = await Request.Content.ReadAsMultipartAsync(provider);

                var originalFileName = GetDeserializedFileName(result.FileData.First());

                var imageType = result.FormData.Get("imageType");
                int imageTypeId;

                if (string.IsNullOrWhiteSpace(imageType) || !int.TryParse(imageType, out imageTypeId))
                {
                    imageTypeId = SettingsData.Constants.FranchiseConst.SYNC_FILE_TYPE_LOGO;
                }

                var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);

                var uploadFolder = UploadFolder;

                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                var uidFileName = Guid.NewGuid();

                var destinationFile = new FileInfo(Path.Combine(uploadFolder, uidFileName.ToString()));

                if (destinationFile.Exists)
                {
                    destinationFile.Delete();
                }

                uploadedFileInfo.MoveTo(destinationFile.FullName);

                await result.ExecutePostProcessingAsync();

                var checkSum = destinationFile.FullName.GetChecksum();

                using (IResourceRepository repository = new ResourceRepository())
                {
                    repository.Save(originalFileName, uidFileName, uploadFolder, User.Identity.GetUserId(), imageTypeId, checkSum);
                    return(Request.CreateResponse(HttpStatusCode.OK, new { ResourceName = uidFileName.ToString(), IsSuccess = true }));
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, new { IsSuccess = false, Msg = ex.Message }));
            }
        }
Beispiel #11
0
 public CreateNewTextResourceWork(ResourceRepository resourceRepository, long textId,
                                  CreateTextVersionRequestContract newTextContract, int userId, IFulltextStorage fulltextStorage) : base(resourceRepository)
 {
     m_resourceRepository = resourceRepository;
     m_textId             = textId;
     m_newTextContract    = newTextContract;
     m_userId             = userId;
     m_fulltextStorage    = fulltextStorage;
 }
Beispiel #12
0
 public ResourcesController(ILogger <ResourcesController> logger
                            , CurrentUserContext currentUserContext
                            , ResourceRepository resourceRepository
                            )
 {
     this.logger             = logger;
     this.currentUserContext = currentUserContext;
     this.resourceRepository = resourceRepository;
 }
Beispiel #13
0
        public static async Task <LoginModelOutput> resendSMSCode(string sysUserId, long smsCodeId)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                SoapEntityRepository repo = SoapEntityRepository.GetService();

                QueryExpression query = new QueryExpression(SystemUser.EntityLogicalName);

                query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname", "mzk_axresourcerefrecid");

                query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, new Guid(sysUserId));

                EntityCollection entitycollection = repo.GetEntityCollection(query);

                Entity entity = entitycollection[0];

                SystemUser user = (SystemUser)entity;

                long resourceRecId = user.mzk_AXResourceRefRecId.HasValue ? Convert.ToInt64(user.mzk_AXResourceRefRecId.Value) : 0;

                if (resourceRecId == 0)
                {
                    throw new ValidationException("Resource Id not set for the user. Please contact system administrator");
                }

                ResourceRepository resourceRepo = new ResourceRepository();
                //HMResourceLoginSMSCodeContract contract = resourceRepo.generateResourceSMSCode(resourceRecId, smsCodeId);

                //if (contract == null)
                //{
                //    throw new ValidationException("Error generating SMS code. Please try again");
                //}

                //if (contract.parmSuccess)
                //{
                //    output.success = true;
                //    output.smsCodeId = contract.parmResourceLoginSMSCodeRecId;
                //    output.userId = sysUserId;
                //    output.errorMessage = "SMS code sent successfully";
                //}
                //else
                //{
                //    output.success = false;
                //    output.doLogout = contract.parmLogOut;
                //    output.errorMessage = contract.parmErrorMessage;
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(output);
        }
        public void Setup()
        {
            var initialData = new Dictionary <int, string>();

            initialData.Add(1, "foo");
            initialData.Add(2, "bar");
            initialData.Add(4, "baz");
            initialData.Add(5, null);
            testObj = new ResourceRepository <int>(initialData);
        }
Beispiel #15
0
        public void List_WithValidPartitionWithTwoResourcesInDb_GetTwoResources()
        {
            var repository = new ResourceRepository(_resourceContext);
            var resources  = repository.List("part2").ToList();

            resources.Count.ShouldBe(2);

            resources[0].Key.ShouldBe("key2");
            resources[1].Key.ShouldBe("key3");
        }
 public FingeprintMatchingAlgorithmsForm(IMatcher matcher, IResourceProvider resourceProvider, string resourcePath, string stmatcher, string stprovider)
 {
     InitializeComponent();
     this.matcher            = matcher;
     provider                = resourceProvider;
     this.resourcePath       = resourcePath;
     repository              = new ResourceRepository(resourcePath);
     txtMatcher.Text         = stmatcher;
     txtFeatureProvider.Text = stprovider;
 }
Beispiel #17
0
 public ActionResult Resources()
 {
     using (var context = new AppSecurityContext())
     {
         var repository = new ResourceRepository(context);
         var resources  = repository.GetAll();
         var model      = mapper.Map <IEnumerable <AppResourceViewModel> >(resources);
         return(View(model));
     }
 }
 public CreateNewAudioResourceVersionWork(ResourceRepository resourceRepository, IFileSystemManager fileSystemManager, long audioId,
                                          CreateAudioContract data, Stream fileStream, int userId) : base(resourceRepository)
 {
     m_resourceRepository = resourceRepository;
     m_fileSystemManager  = fileSystemManager;
     m_audioId            = audioId;
     m_data       = data;
     m_fileStream = fileStream;
     m_userId     = userId;
 }
Beispiel #19
0
 public async Task<bool> ForceLoadResourcesAsync()
 {
     if(Connection.IsConnected && CanStudioExecute)
     {
         await ResourceRepository.ForceLoadAsync();
         HasLoadedResources = true;
         return true;
     }
     return false;
 }
Beispiel #20
0
 public ProjectItemManager(AuthenticationManager authenticationManager, ResourceRepository resourceRepository,
                           FulltextStorageProvider fulltextStorageProvider, IFileSystemManager fileSystemManager,
                           IMapper mapper)
 {
     m_authenticationManager   = authenticationManager;
     m_resourceRepository      = resourceRepository;
     m_fulltextStorageProvider = fulltextStorageProvider;
     m_fileSystemManager       = fileSystemManager;
     m_mapper = mapper;
 }
Beispiel #21
0
        public async Task Init()
        {
            await TestCleaner.CleanDatabase();

            var numTestRows = 20;

            IDataGateway                   dataGateway                   = new SQLServerGateway();
            IConnectionStringData          connectionString              = new ConnectionStringData();
            IScopeRepository               scopeRepository               = new ScopeRepository(dataGateway, connectionString);
            IResourceRepository            resourceRepository            = new ResourceRepository(dataGateway, connectionString);
            IClaimRepository               claimRepository               = new ClaimRepository(dataGateway, connectionString);
            IAccessPolicyRepository        accessPolicyRepository        = new AccessPolicyRepository(dataGateway, connectionString);
            IAccessPolicyPairingRepository accessPolicyPairingRepository = new AccessPolicyPairingRepository(dataGateway, connectionString);


            for (int i = 1; i <= numTestRows; ++i)
            {
                ResourceModel resourceModel = new ResourceModel();
                resourceModel.Id   = i;
                resourceModel.Name = "TestResource" + i;

                ScopeModel scopeModel = new ScopeModel();
                scopeModel.Id          = i;
                scopeModel.Type        = "TestScope" + i;
                scopeModel.Description = "TestDescription" + i;

                ClaimModel claimModel = new ClaimModel();
                claimModel.Id        = i;
                claimModel.Type      = "TestClaim" + i;
                claimModel.Value     = "TestDescription" + i;
                claimModel.IsDefault = true;

                var resourceId = await resourceRepository.CreateResource(resourceModel);

                var claimId = await claimRepository.CreateClaim(claimModel);

                var scopeId = await scopeRepository.CreateScope(scopeModel);

                AccessPolicyModel accessPolicyModel = new AccessPolicyModel();
                accessPolicyModel.Id         = i;
                accessPolicyModel.Name       = "TestAccessPolicy" + i;
                accessPolicyModel.ResourceId = resourceId;
                accessPolicyModel.Priority   = i % 4;

                var accessPolicyId = await accessPolicyRepository.CreateAccessPolicy(accessPolicyModel);

                AccessPolicyPairingModel accessPolicyPairingModel = new AccessPolicyPairingModel();
                accessPolicyPairingModel.Id             = i;
                accessPolicyPairingModel.ScopeId        = scopeId;
                accessPolicyPairingModel.ClaimId        = claimId;
                accessPolicyPairingModel.AccessPolicyId = accessPolicyId;

                await accessPolicyPairingRepository.CreateAccessPolicyPairing(accessPolicyPairingModel);
            }
        }
Beispiel #22
0
        public RepositoryFixture()
        {
            Database = new IntegrationDbFixture();

            RefreshTokens       = new RefreshTokenRepository(Database.Ctx);
            Reservations        = new ReservationRepository(Database.Ctx);
            ReservationStatuses = new ReservationStatusRepository(Database.Ctx);
            Resources           = new ResourceRepository(Database.Ctx);
            Roles = new RolesRepository(Database.Ctx);
            Users = new UserRepository(Database.Ctx, Roles);
        }
Beispiel #23
0
 public ProjectContentManager(ResourceRepository resourceRepository, IFileSystemManager fileSystemManager,
                              AuthenticationManager authenticationManager, FulltextStorageProvider fulltextStorageProvider,
                              UserDetailManager userDetailManager, IMapper mapper)
 {
     m_resourceRepository      = resourceRepository;
     m_fileSystemManager       = fileSystemManager;
     m_authenticationManager   = authenticationManager;
     m_fulltextStorageProvider = fulltextStorageProvider;
     m_userDetailManager       = userDetailManager;
     m_mapper = mapper;
 }
 public HttpResponseMessage PostResource([FromBody] ResourceWithValue model)
 {
     try
     { ResourceRepository.AddResourceInfo(model);
       KafkaService.PostResource(model);
       return(Request.CreateResponse(System.Net.HttpStatusCode.OK, 202)); }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex));
     }
 }
    //bool Is_Tower_Near = false;

    void Awake()
    {
        if (autoSetting)
        {
            switch (ObjType)
            {
            case AllType.NormalCube:
                Obj_Name       = "Normal Cube";
                Is_canbePulled = true;
                Canbe_Grab     = true;
                break;

            case AllType.Monitor:
                Obj_Name = "Monitor";
                break;

            case AllType.Tower:
                Obj_Name   = "Tower";
                Canbe_Grab = true;
                break;

            case AllType.CNN_image_classifier:
                Obj_Name = "CNN_Image_Classifier";
                break;

            case AllType.Player:
                Obj_Name       = "Player";
                Is_canbePulled = true;
                break;

            case AllType.PlatForm:
                Obj_Name      = "Platform";
                Platform_Pull = true;
                break;

            case AllType.Door:
                Obj_Name = "Door";
                break;

            case AllType.puzzle_Hologram:
                Obj_Name = "Hologram Section";
                break;

            case AllType.Button:
                Obj_Name = "Button";
                break;

            default:
                Obj_Name = "Null";
                break;
            }
        }
        repository_script = GameObject.Find("Repository_Obj").GetComponent <ResourceRepository>();
    }
        private static ResponseMessageServerFileSync GetSyncResourceFileStream(RequestMessageServerFileSync request)
        {
            var response = new ResponseMessageServerFileSync();

            try
            {
                string path;

                using (var repository = new ResourceRepository())
                {
                    path = repository.GetResourcePath(request.FileName);
                }

                if (String.IsNullOrWhiteSpace(path))
                {
                    response.HasError = true;
                    response.Message  = String.Format("La ruta para el archivo {0} no se encuentra. Por favor revise de nuevo",
                                                      request.FileName);
                    return(response);
                }


                var pathFileName = Path.Combine(path, request.FileName);

                if (File.Exists(pathFileName) == false)
                {
                    response.HasError = true;
                    response.Message  = String.Format("El archivo {0} no se encuentra. Por favor revise de nuevo",
                                                      request.FileName);
                    return(response);
                }

                response.File = File.OpenRead(pathFileName);


                var clientContext = OperationContext.Current;
                clientContext.OperationCompleted += delegate
                {
                    if (response.File != null)
                    {
                        response.File.Dispose();
                    }
                };

                response.HasError = false;
                return(response);
            }
            catch (Exception ex)
            {
                response.HasError = true;
                response.Message  = ex.Message + " - " + ex.StackTrace;
                return(response);
            }
        }
Beispiel #27
0
 public EditionNoteManager(ResourceRepository resourceRepository, FulltextStorageProvider fulltextStorageProvider,
                           AuthorizationManager authorizationManager, AuthenticationManager authenticationManager,
                           IMarkdownToHtmlConverter markdownConverter, IMapper mapper)
 {
     m_resourceRepository      = resourceRepository;
     m_fulltextStorageProvider = fulltextStorageProvider;
     m_authorizationManager    = authorizationManager;
     m_authenticationManager   = authenticationManager;
     m_markdownConverter       = markdownConverter;
     m_mapper = mapper;
 }
Beispiel #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DiscoveryController"/> class.
        /// </summary>
        public DiscoveryController(ResourceRepository resourceRepository)
        {
            Guard.NotNull(resourceRepository, nameof(resourceRepository));

            _resourceRepository = resourceRepository;
            _serializerSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                TypeNameHandling  = TypeNameHandling.Objects
            };
            _serializerSettings.Converters.Add(new StringEnumConverter());
        }
        public void ReadTest()
        {
            // Arrange
            ResourceRepository target   = new ResourceRepository(_context);
            Resource           expected = _mockdata.Resource1();

            // Act
            Resource actual = target.Read(expected.Id);

            // Assert
            Assert.AreEqual(expected.Id, actual.Id);
        }
Beispiel #30
0
 public RelationalDbStoreProcessor(ProjectRepository projectRepository, MetadataRepository metadataRepository,
                                   ResourceRepository resourceRepository, FulltextStoreProcessorProvider fulltextStoreProcessorProvider, CatalogValueRepository catalogValueRepository, PersonRepository personRepository,
                                   PermissionRepository permissionRepository)
 {
     m_projectRepository              = projectRepository;
     m_metadataRepository             = metadataRepository;
     m_resourceRepository             = resourceRepository;
     m_fulltextStoreProcessorProvider = fulltextStoreProcessorProvider;
     m_catalogValueRepository         = catalogValueRepository;
     m_personRepository     = personRepository;
     m_permissionRepository = permissionRepository;
 }
 public AdventureService(AdventureTypeRepository adventureTypeRepository, AdventureListQuery adventureListQuery, UnitRepository unitRepository, UnitTypeListQuery unitTypeListQuery, ProductRepository productRepository, ProductListQuery productListQuery, ResourceRepository resourceRepository, ResourceListQuery resourceListQuery, AdventureRepository adventureRepository)
 {
     this.adventureTypeRepository = adventureTypeRepository;
     this.adventureListQuery      = adventureListQuery;
     this.unitRepository          = unitRepository;
     this.unitTypeListQuery       = unitTypeListQuery;
     this.productRepository       = productRepository;
     this.productListQuery        = productListQuery;
     this.resourceRepository      = resourceRepository;
     this.resourceListQuery       = resourceListQuery;
     this.adventureRepository     = adventureRepository;
 }
        public void ReadAllTest()
        {
            // Arrange
            ResourceRepository target   = new ResourceRepository(_context);
            List <Resource>    expected = _mockdata.GetAll();

            // Act
            List <Resource> actual = target.ReadAll();

            // Assert
            Assert.IsTrue(actual.Count >= 0);
        }
Beispiel #33
0
 /// <summary>
 /// UnAssign the resource from the specified deliverable activity
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static void UnAssignFromRelease(this RHumanResource person, Release release, Project project, Milestone milestone, Deliverable deliverable, Activity activity, Period assignedPeriod)
 {
     var rep = new ResourceRepository();
     try
     {
         rep.DeleteReleaseAssignment(release.Id, project.Id, person.Id, milestone.Id, deliverable.Id, activity.Id, assignedPeriod.StartDate, assignedPeriod.EndDate);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Beispiel #34
0
 /// <summary>
 /// TODO: not used yet; first create continuing process logic
 /// Plan the resource for a continuing process
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static void PlanForContinuingProcess(this RHumanResource person, Process process, Deliverable deliverable, Activity activity, Period assignedPeriod, double dedication)
 {
     var rep = new ResourceRepository();
     try
     {
         rep.SaveContinuingProcessAssignment(process.Id, person.Id, deliverable.Id, activity.Id, assignedPeriod.StartDate, assignedPeriod.EndDate, dedication);
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Beispiel #35
0
 public SelectList PopulateResources(object selectedItem = null)
 {
     using (var context = new AppSecurityContext())
     {
         var repository = new ResourceRepository(context);
         var resources  = repository.GetAll().OrderBy(x => x.Name).ToList();
         resources.Insert(0, new AppResource {
             Key = null, Name = "Seleccione"
         });
         return(new SelectList(resources, "Key", "Name", selectedItem));
     }
 }
        public void TestAllResourceFilesExist()
        {
            // Arrange
            var repository = new ResourceRepository();

            // Act
            foreach (var path in this.GetAllResourceFileKeys())
            {
                var data = repository.GetString(path);

                // Assert
                Assert.IsNotNull(data);
            }
        }
Beispiel #37
0
 /// <summary>
 /// Plan the resource for an assignment
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static void PlanForRelease(this RHumanResource person, RReleasePlanning release, Project project, Milestone milestone, Deliverable deliverable, Activity activity, Period assignedPeriod, double focusFactor)
 {
     var rep = new ResourceRepository();
     try
     {
         rep.SaveReleaseAssignment(release.Id, project.Id, person.Id, milestone.Id, deliverable.Id, activity.Id, assignedPeriod.StartDate, assignedPeriod.EndDate, focusFactor);
         // make sure we have status records for all release, project, milestone and deliverable combinations
         if (release.Milestones.Count == 0)
             release.LoadPhasesAndMilestonesAndProjects();
         release.GenerateMilestoneStatusRecords();
     }
     catch (Exception ex)
     {
         throw;
     }
 }
        public virtual void Init()
        {
            var builder = new ContainerBuilder();

            builder.RegisterAutoMocking(MockBehavior.Loose);

            builder.RegisterInstance(new StubVirtualPathProvider(new StubFileSystem(new StubClock()))).As<IVirtualPathProvider>();
            builder.RegisterType<ResourceFileService>().As<IResourceFileService>();

            CombinatorResourceHelper.Register(builder);

            _container = builder.Build();

            _resourceRepository = new ResourceRepository(_container);
            _resourceFileService = _container.Resolve<IResourceFileService>();
        }
        public override void Execute()
        {
            var repository = new ResourceRepository();
            var absences = repository.GetAbsencesForComingDays(_amtDays);

            foreach (var a in absences)
            {
                var builder = new StringBuilder();

                builder.Append(string.Format("{0}: {1}", a.Person.DisplayName, a.Period.ToString()));
                builder.Append("\n");

                var item = new CueItem("Absent: " + a.Person.DisplayName, a.StartDate, "9:00", builder.ToString());
                _creator.CreateVisualCue(item);
                // add notification to history table
                repository.AddNotificationToHistory(a.Id, "AwesomeNote");
            }
        }
        public virtual void Init()
        {
            var builder = new ContainerBuilder();

            builder.RegisterAutoMocking(MockBehavior.Loose);

            builder.RegisterInstance(new StubMinificationService()).As<IMinificationService>();
            builder.RegisterType<ResourceProcessingService>().As<IResourceProcessingService>();

            _container = builder.Build();

            _resourceRepository = new ResourceRepository(_container);

            builder = new ContainerBuilder();
            builder.RegisterInstance(new StubResourceFileService(_resourceRepository)).As<IResourceFileService>();
            builder.Update(_container);

            _resourceProcessingService = _container.Resolve<IResourceProcessingService>();
        }
Beispiel #41
0
        public PdfDocument()
        {
            m_Fonts = new List<PdfFont>();
              m_Meta = new PdfMeta();
              m_Info = new PdfInfo();
              m_OutLines = new PdfOutlines();
              m_Root = new PdfRoot();
              m_PageTree = new PdfPageTree();
              m_Trailer = new PdfTrailer();
              m_ObjectRepository = new ObjectRepository();
              m_ResourceRepository = new ResourceRepository();

              m_Root.Info = m_Info;
              m_Root.Outlines = m_OutLines;
              m_Root.PageTree = m_PageTree;
              m_Trailer.Root = m_Root;

              m_PageSize = PdfPageSize.Default();
        }
Beispiel #42
0
        public ReleaseModels.Project GetProjectWithWorkload(int projectId, int releaseId, int milestoneId, int deliverableId)
        {
            var project = this.GetProject(projectId);

            var _assignments = new List<ReleaseModels.ResourceAssignment>();

            using (var conn = new SqlConnection(this.ConnectionString))
            {
                var cmdResources = new SqlCommand("get_release_deliverable_assignments", conn);
                cmdResources.Parameters.Add("@DeliverableId", System.Data.SqlDbType.Int).Value = deliverableId;
                cmdResources.Parameters.Add("@PhaseId", System.Data.SqlDbType.Int).Value = releaseId;
                cmdResources.Parameters.Add("@MilestoneId", System.Data.SqlDbType.Int).Value = milestoneId;
                cmdResources.Parameters.Add("@ProjectId", System.Data.SqlDbType.Int).Value = projectId;
                cmdResources.CommandType = System.Data.CommandType.StoredProcedure;

                conn.Open();
                using (var resourcesReader = cmdResources.ExecuteReader())
                {
                    while (resourcesReader.Read())
                    {
                        var resRep = new ResourceRepository();
                        var resource = new ReleaseModels.Resource { Id = int.Parse(resourcesReader["PersonId"].ToString()), FirstName = resourcesReader["FirstName"].ToString(), MiddleName = resourcesReader["MiddleName"].ToString(), LastName = resourcesReader["LastName"].ToString() };
                        resource.PeriodsAway.AddRange(resRep.GetAbsences(resource.Id));

                        _assignments.Add(new ReleaseModels.ResourceAssignment
                        {
                            Id = int.Parse(resourcesReader["Id"].ToString()),
                            FocusFactor = double.Parse(resourcesReader["FocusFactor"].ToString()),
                            Phase = new ReleaseModels.Phase { Id = int.Parse(resourcesReader["PhaseId"].ToString()), Title = resourcesReader["phasetitle"].ToString() },
                            Resource = resource,
                            Project = new ReleaseModels.Project { Id = int.Parse(resourcesReader["ProjectId"].ToString()), Title = resourcesReader["ProjectTitle"].ToString() },
                            //TODO: fill ActivitiesNeeded
                            Deliverable = new ReleaseModels.Deliverable { Id = int.Parse(resourcesReader["DeliverableId"].ToString()), Title = resourcesReader["DeliverableTitle"].ToString() },
                            Milestone = new ReleaseModels.Milestone { Id = int.Parse(resourcesReader["MilestoneId"].ToString()), Title = resourcesReader["MilestoneTitle"].ToString() },
                            StartDate = DateTime.Parse(resourcesReader["StartDate"].ToString()),
                            EndDate = DateTime.Parse(resourcesReader["EndDate"].ToString()),
                            Activity = new ReleaseModels.Activity { Id = int.Parse(resourcesReader["ActivityId"].ToString()), Title = resourcesReader["ActivityTitle"].ToString() }
                        });
                    }
                }
            }

            using (var conn = new SqlConnection(this.ConnectionString))
            {
                var cmdStatus = new SqlCommand("sp_get_deliverable_status", conn);
                cmdStatus.Parameters.Add("@DeliverableId", System.Data.SqlDbType.Int).Value = deliverableId;
                cmdStatus.Parameters.Add("@ReleaseId", System.Data.SqlDbType.Int).Value = releaseId;
                cmdStatus.Parameters.Add("@MilestoneId", System.Data.SqlDbType.Int).Value = milestoneId;
                cmdStatus.Parameters.Add("@ProjectId", System.Data.SqlDbType.Int).Value = projectId;
                cmdStatus.CommandType = System.Data.CommandType.StoredProcedure;

                conn.Open();
                using (var statusReader = cmdStatus.ExecuteReader())
                {
                    while (statusReader.Read())
                    {
                        var assignments = _assignments.Where(a => a.Activity.Id == int.Parse(statusReader["ActivityId"].ToString())).ToList();
                        var status = new ReleaseModels.ActivityStatus
                                        {
                                            //Deliverable = itm,
                                            HoursRemaining = int.Parse(statusReader["HoursRemaining"].ToString()),
                                            //Project = projRep.GetProject(project.Id),
                                            Activity = new ReleaseModels.Activity { Id = int.Parse(statusReader["ActivityId"].ToString()), Title = statusReader["ActivityTitle"].ToString(), Description = statusReader["ActivityDescription"].ToString() },
                                        };
                        foreach(var a in assignments)
                        {
                            status.AssignedResources.Add(a);
                        }
                        project.Workload.Add(status);
                    }
                }
            }
            return project;
        }
        public void SchedulerViewModel_DeActivateSave_AttemptsSave()
        {
            //------------Setup for test--------------------------
            var resources = new ObservableCollection<IScheduledResource>();
            var scheduledResourceForTest = new ScheduledResourceForTest { Trigger = new ScheduleTrigger(TaskState.Ready, new Dev2DailyTrigger(new TaskServiceConvertorFactory(), new DailyTrigger()), new Dev2TaskService(new TaskServiceConvertorFactory()), new TaskServiceConvertorFactory()), IsDirty = true };
            resources.Add(scheduledResourceForTest);
            Dev2JsonSerializer serializer = new Dev2JsonSerializer();
            var serializeObject = serializer.SerializeToBuilder(resources);
            var mockEnvironmentModel = new Mock<IEnvironmentModel>();
            var mockConnection = new Mock<IEnvironmentConnection>();
            mockConnection.Setup(connection => connection.IsConnected).Returns(true);
            mockConnection.Setup(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>())).Returns(serializeObject);
            mockConnection.Setup(connection => connection.WorkspaceID).Returns(Guid.NewGuid());
            mockEnvironmentModel.Setup(model => model.Connection).Returns(mockConnection.Object);
            mockEnvironmentModel.Setup(model => model.IsConnected).Returns(true);
            ResourceRepository resourceRepo = new ResourceRepository(mockEnvironmentModel.Object);
            var setupResourceModelMock = Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow2");
            resourceRepo.Add(Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow1").Object);
            resourceRepo.Add(setupResourceModelMock.Object);
            resourceRepo.Add(Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow3").Object);
            mockEnvironmentModel.Setup(c => c.ResourceRepository).Returns(resourceRepo);
            var popup = new Mock<IPopupController>();
            popup.Setup(a => a.ShowSchedulerCloseConfirmation()).Returns(MessageBoxResult.Yes);
            var schedulerViewModel = new SchedulerViewModel(new Mock<IEventAggregator>().Object, new Mock<DirectoryObjectPickerDialog>().Object, popup.Object, new TestAsyncWorker(), new Mock<IConnectControlViewModel>().Object) { SelectedTask = scheduledResourceForTest };

            var auth = new Mock<IAuthorizationService>();
            mockEnvironmentModel.Setup(a => a.AuthorizationService).Returns(auth.Object);
            auth.Setup(a => a.IsAuthorized(AuthorizationContext.Administrator, null)).Returns(false).Verifiable();
            schedulerViewModel.CurrentEnvironment = mockEnvironmentModel.Object;
            //------------Execute Test---------------------------
            schedulerViewModel.DoDeactivate();
            //------------Assert Results-------------------------
            auth.Verify(a => a.IsAuthorized(AuthorizationContext.Administrator, null));
            Assert.AreEqual(@"Error while saving: You don't have permission to schedule on this server.
You need Administrator permission.", schedulerViewModel.Error);



        }
 public void TestInitialize()
 {
     this.repository = new ResourceRepository();
     this.serializer = new Serializer();
 }
        public void ResourceCreate()
        {
            var resource = new Resource()
                               {
                                   Name = "Account",
                                   ResourceDocs = new List<ResourceDoc>()
                                              {
                                                  new ResourceDoc()
                                                      {
                                                          Language = "en",
                                                          Summary = "This is the default English summary"
                                                      },
                                                  new ResourceDoc()
                                                      {
                                                          Language = "fr",
                                                          Summary = "This is the French summary"
                                                      }
                                              }

                               };

            resource.Fields = new List<Field>()
                                  {
                                      new Field()
                                          {
                                              Name = "Reference",
                                              FieldType = "string",
                                              Resource = resource
                                          },
                                      new Field()
                                          {
                                              Name = "EndOn",
                                              FieldType = "datetime",
                                              Resource = resource
                                          }
                                  };

            using (var repository = new ResourceRepository())
            {
                repository.Add(resource);
                repository.SaveChanges();
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["api.docs.data"].ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand("SELECT Id, Name FROM Resources", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        Assert.IsTrue(reader.Read());
                        Assert.AreEqual(resource.Name, reader.GetString(1));
                        Assert.IsFalse(reader.Read());
                    }
                }

                using (var command = new SqlCommand("SELECT Id, ResourceId, Language, Summary FROM ResourceDocs", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        int i = 0;
                        while (reader.Read())
                        {
                            var docs = new List<ResourceDoc>(resource.ResourceDocs);

                            Assert.AreEqual(resource.Id, reader.GetGuid(1));
                            Assert.AreEqual(docs[i].Language, reader.GetString(2));
                            Assert.AreEqual(docs[i].Summary, reader.GetString(3));
                            i++;
                        }
                        Assert.AreEqual(i, resource.ResourceDocs.Count);
                    }
                }

                using (var command = new SqlCommand("SELECT Id, ResourceId, Name, FieldType FROM Fields", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        int i = 0;
                        while (reader.Read())
                        {
                            var fields = new List<Field>(resource.Fields);

                            Assert.AreEqual(resource.Id, reader.GetGuid(1));
                            Assert.AreEqual(fields[i].Name, reader.GetString(2));
                            Assert.AreEqual(fields[i].FieldType, reader.GetString(3));
                            i++;
                        }
                        Assert.AreEqual(i, resource.Fields.Count);
                    }
                }
            }
        }
Beispiel #46
0
        public void DeployViewModelDeployWithServerExpectedDoesNotDisconnectOtherServers()
        {
            var source = EnviromentRepositoryTest.CreateMockEnvironment();
            var sourceConn = Mock.Get(source.Object.Connection);
            sourceConn.Setup(c => c.Disconnect()).Verifiable();

            var e1 = EnviromentRepositoryTest.CreateMockEnvironment();
            var s1 = e1.Object;
            var c1 = Mock.Get(e1.Object.Connection);
            c1.Setup(c => c.Disconnect()).Verifiable();

            var resourceRepo1 = new ResourceRepository(e1.Object);
            e1.Setup(e => e.ResourceRepository).Returns(resourceRepo1);
            var r1 = new Mock<IContextualResourceModel>();
            r1.Setup(r => r.Category).Returns("test");
            r1.Setup(r => r.ResourceName).Returns("testResource");
            r1.Setup(r => r.Environment).Returns(e1.Object);
            resourceRepo1.Add(r1.Object);

            var e2 = EnviromentRepositoryTest.CreateMockEnvironment();
            var s2 = e2.Object;
            var c2 = Mock.Get(e2.Object.Connection);
            c2.Setup(c => c.Disconnect()).Verifiable();

            var resourceRepo2 = new ResourceRepository(e2.Object);
            e2.Setup(e => e.ResourceRepository).Returns(resourceRepo2);

            var serverProvider = new Mock<IEnvironmentModelProvider>();
            serverProvider.Setup(s => s.Load()).Returns(new List<IEnvironmentModel> { s1, s2 });

            var repo = new TestEnvironmentRespository(source.Object, e1.Object, e2.Object);

            var statsCalc = new Mock<IDeployStatsCalculator>();
            IAsyncWorker asyncWorker = new TestAsyncWorker();
            statsCalc.Setup(s => s.SelectForDeployPredicate(It.IsAny<ExplorerItemModel>())).Returns(true);
            Mock<IStudioResourceRepository> mockStudioResourceRepository = new Mock<IStudioResourceRepository>();
            mockStudioResourceRepository.Setup(repository => repository.FindItem(It.IsAny<Func<IExplorerItemModel, bool>>())).Returns(new ExplorerItemModel(mockStudioResourceRepository.Object, asyncWorker, new Mock<IConnectControlSingleton>().Object));
            IStudioResourceRepository studioResourceRepository = mockStudioResourceRepository.Object;
            var deployViewModel = new DeployViewModel(asyncWorker, serverProvider.Object, repo, new Mock<IEventAggregator>().Object, studioResourceRepository, new Mock<IConnectControlViewModel>().Object, new Mock<IConnectControlViewModel>().Object, statsCalc.Object, null, null, new Mock<IConnectControlSingleton>().Object)
            {
                SelectedSourceServer = s1,
                SelectedDestinationServer = s2
            };

            Assert.IsTrue(source.Object.IsConnected);
            Assert.IsTrue(s1.IsConnected);
            Assert.IsTrue(s2.IsConnected);

            deployViewModel.DeployCommand.Execute(null);

            sourceConn.Verify(c => c.Disconnect(), Times.Never());
            c1.Verify(c => c.Disconnect(), Times.Never());
            c2.Verify(c => c.Disconnect(), Times.Never());
        }
 public void MyTestInitialize()
 {
     //_repo = new ResourceRepository("RavenDB", ResourceRepository.RepositoryType.RavenDb);
      _repo = new ResourceRepository(ConfigurationManager.AppSettings.GetSetting("RepositoryConnection", @"{ type:'File', resourceDir:'~\\FileDb' }"));
 }
 public void TestInitialize()
 {
     this.repository = new ResourceRepository();
 }
            // This code configures Web API. The Startup class is specified as a type
            // parameter in the WebApp.Start method.
            public void Configuration(IAppBuilder appBuilder)
            {
                var repository = new ResourceRepository();

                // authenticate request
                appBuilder.Use(
                    async (ctx, next) =>
                    {
                        var url = ctx.Request.Uri;

                        var queryStrings = System.Web.HttpUtility.ParseQueryString(url.Query);

                        var value = queryStrings["key"];

                        if (value == null)
                        {
                            // missing key
                            var response = ctx.Response;
                            response.StatusCode = 200;
                            ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });
                            await ctx.Response.WriteAsync(@"<?xml version=""1.0""?>
<bustime-response><error><msg>No API access key supplied</msg></error></bustime-response>");
                        }
                        else if (value != ApiKey)
                        {
                            // incorrect key
                            var response = ctx.Response;
                            response.StatusCode = 200;
                            ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });
                            await ctx.Response.WriteAsync(@"<?xml version=""1.0""?>
<bustime-response><error><msg>Invalid API access key supplied</msg></error></bustime-response>");
                        }
                        else
                        {
                            await next();
                        }
                    });

                appBuilder.Map("/bustime/api/v1/gettime",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetTimeResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });

                appBuilder.Map("/bustime/api/v1/getvehicles",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetVehiclesResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });

                appBuilder.Map("/bustime/api/v1/getroutes",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetRoutesResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });

                appBuilder.Map("/bustime/api/v1/getdirections",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetRouteDirectionsResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });

                appBuilder.Map("/bustime/api/v1/getstops",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetStopsResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });

                appBuilder.Map("/bustime/api/v1/getpredictions",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetPredictionsResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });

                appBuilder.Map("/bustime/api/v1/getservicebulletins",
                    map =>
                    {
                        map.Run(
                            async ctx =>
                            {
                                var xml = repository.GetString(ResourceFiles.GetServiceBulletinsResponse);

                                // status code
                                ctx.Response.StatusCode = 200;

                                // headers
                                ctx.Response.Headers.Add("Content-Type", new[] { "text/xml;charset=utf-8" });

                                // content
                                await ctx.Response.WriteAsync(xml);
                            });
                    });
            }
        public void ResourceDelete()
        {
            var resource = new Resource()
            {
                Name = "Account",
                ResourceDocs = new List<ResourceDoc>()
                                              {
                                                  new ResourceDoc()
                                                      {
                                                          Language = "en",
                                                          Summary = "This is the default English summary"
                                                      },
                                                  new ResourceDoc()
                                                      {
                                                          Language = "fr",
                                                          Summary = "This is the French summary"
                                                      }
                                              }
            };

            using (var repository = new ResourceRepository())
            {
                repository.Add(resource);
                repository.SaveChanges();

                repository.DeleteById(resource.Id);
                repository.SaveChanges();
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["api.docs.data"].ConnectionString))
            {
                connection.Open();
                using (var command = new SqlCommand("SELECT Id, Name FROM Resources", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        Assert.IsFalse(reader.Read(), "Resources table");
                    }
                }

                using (var command = new SqlCommand("SELECT Id, ResourceId, Language, Summary FROM ResourceDocs", connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        Assert.IsFalse(reader.Read(), "Docs table");
                    }
                }
            }

        }
        public void SchedulerViewModel_AddWorkflow_WithNewTaskNameSet_WorkflowNameChangedAndNameChanged()
        {
            //------------Setup for test--------------------------
            var resources = new ObservableCollection<IScheduledResource> { new ScheduledResource("New Task1", SchedulerStatus.Enabled, DateTime.MaxValue, new Mock<IScheduleTrigger>().Object, "TestFlow1") { NumberOfHistoryToKeep = 1 } };
            var mockEnvironmentModel = new Mock<IEnvironmentModel>();
            var mockConnection = new Mock<IEnvironmentConnection>();
            mockConnection.Setup(connection => connection.IsConnected).Returns(true);
            mockConnection.Setup(connection => connection.WorkspaceID).Returns(Guid.NewGuid());
            mockEnvironmentModel.Setup(model => model.Connection).Returns(mockConnection.Object);
            mockEnvironmentModel.Setup(model => model.IsConnected).Returns(true);
            ResourceRepository resourceRepo = new ResourceRepository(mockEnvironmentModel.Object);
            var setupResourceModelMock = Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow2");
            var resId = Guid.NewGuid();
            setupResourceModelMock.Setup(c => c.ID).Returns(resId);
            resourceRepo.Add(Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow1").Object);
            resourceRepo.Add(setupResourceModelMock.Object);
            resourceRepo.Add(Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow3").Object);
            mockEnvironmentModel.Setup(c => c.ResourceRepository).Returns(resourceRepo);

            var schedulerViewModel = new SchedulerViewModel(new Mock<IEventAggregator>().Object, new Mock<DirectoryObjectPickerDialog>().Object, new Mock<IPopupController>().Object, new TestAsyncWorker(), new Mock<IConnectControlViewModel>().Object) { CurrentEnvironment = mockEnvironmentModel.Object };
            Mock<IResourcePickerDialog> mockResourcePickerDialog = new Mock<IResourcePickerDialog>();
            mockResourcePickerDialog.Setup(c => c.ShowDialog(It.IsAny<IEnvironmentModel>())).Returns(true);
            mockResourcePickerDialog.Setup(c => c.SelectedResource).Returns(setupResourceModelMock.Object);

            schedulerViewModel.ResourcePickerDialog = mockResourcePickerDialog.Object;

            Mock<IScheduledResourceModel> scheduledResourceModelMock = new Mock<IScheduledResourceModel>();
            scheduledResourceModelMock.Setup(c => c.ScheduledResources).Returns(resources);
            schedulerViewModel.ScheduledResourceModel = scheduledResourceModelMock.Object;
            //------------Execute Test---------------------------
            schedulerViewModel.TaskList[0].WorkflowName = "TestFlow3";
            schedulerViewModel.SelectedTask = schedulerViewModel.TaskList[0];

            var _nameChange = false;
            var _workflowNameChange = false;
            var _taskListChange = false;

            schedulerViewModel.PropertyChanged += delegate(object sender, PropertyChangedEventArgs args)
            {
                switch(args.PropertyName)
                {
                    case "TaskList":
                        _taskListChange = true;
                        break;
                    case "Name":
                        _nameChange = true;
                        break;
                    case "WorkflowName":
                        _workflowNameChange = true;
                        break;
                }
            };

            schedulerViewModel.AddWorkflowCommand.Execute(null);
            //------------Assert Results-------------------------  
            Assert.IsTrue(_nameChange);
            Assert.IsTrue(_workflowNameChange);
            Assert.IsTrue(_taskListChange);
            Assert.IsTrue(schedulerViewModel.SelectedTask.IsDirty);
            Assert.AreEqual("TestFlow2", schedulerViewModel.Name);
            Assert.AreEqual("Category\\Testing", schedulerViewModel.WorkflowName);
            Assert.AreEqual(resId, schedulerViewModel.SelectedTask.ResourceId);
        }
 public StubCacheFileService(ISignals signals, ResourceRepository resourceRepository)
 {
     _signals = signals;
     _resourceRepository = resourceRepository;
 }
        public void SchedulerViewModel_DeActivateCancel_ReturnsFalse()
        {
            //------------Setup for test--------------------------
            var resources = new ObservableCollection<IScheduledResource>();
            var scheduledResourceForTest = new ScheduledResourceForTest { Trigger = new ScheduleTrigger(TaskState.Ready, new Dev2DailyTrigger(new TaskServiceConvertorFactory(), new DailyTrigger()), new Dev2TaskService(new TaskServiceConvertorFactory()), new TaskServiceConvertorFactory()), IsDirty = true };
            resources.Add(scheduledResourceForTest);
            Dev2JsonSerializer serializer = new Dev2JsonSerializer();
            var serializeObject = serializer.SerializeToBuilder(resources);
            var mockEnvironmentModel = new Mock<IEnvironmentModel>();
            var mockConnection = new Mock<IEnvironmentConnection>();
            mockConnection.Setup(connection => connection.IsConnected).Returns(true);
            mockConnection.Setup(connection => connection.ExecuteCommand(It.IsAny<StringBuilder>(), It.IsAny<Guid>())).Returns(serializeObject);
            mockConnection.Setup(connection => connection.WorkspaceID).Returns(Guid.NewGuid());
            mockEnvironmentModel.Setup(model => model.Connection).Returns(mockConnection.Object);
            mockEnvironmentModel.Setup(model => model.IsConnected).Returns(true);
            ResourceRepository resourceRepo = new ResourceRepository(mockEnvironmentModel.Object);
            var setupResourceModelMock = Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow2");
            resourceRepo.Add(Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow1").Object);
            resourceRepo.Add(setupResourceModelMock.Object);
            resourceRepo.Add(Dev2MockFactory.SetupResourceModelMock(ResourceType.WorkflowService, "TestFlow3").Object);
            mockEnvironmentModel.Setup(c => c.ResourceRepository).Returns(resourceRepo);
            var popup = new Mock<IPopupController>();
            popup.Setup(a => a.ShowSchedulerCloseConfirmation()).Returns(MessageBoxResult.Cancel);
            var schedulerViewModel = new SchedulerViewModel(new Mock<IEventAggregator>().Object, new Mock<DirectoryObjectPickerDialog>().Object, popup.Object, new TestAsyncWorker(), new Mock<IConnectControlViewModel>().Object) { SelectedTask = scheduledResourceForTest, CurrentEnvironment = null };
            //------------Execute Test---------------------------
            Assert.IsFalse(schedulerViewModel.DoDeactivate());
            //------------Assert Results-------------------------

        }
        public void ResourceRead()
        {
            var resource = new Resource()
            {
                Name = "Account",
                ResourceDocs = new List<ResourceDoc>()
                                              {
                                                  new ResourceDoc()
                                                      {
                                                          Language = "en",
                                                          Summary = "This is the default English summary"
                                                      },
                                                  new ResourceDoc()
                                                      {
                                                          Language = "fr",
                                                          Summary = "This is the French summary"
                                                      }
                                              }
            };

            using (var repository = new ResourceRepository())
            {
                repository.Add(resource);
                repository.SaveChanges();

                var actual = repository.GetById(resource.Id);

                Assert.AreEqual(resource.Name, actual.Name);
                Assert.AreEqual(resource.ResourceDocs.Count, actual.ResourceDocs.Count);

                var docs = new List<ResourceDoc>(resource.ResourceDocs);
                var actualDocs = new List<ResourceDoc>(actual.ResourceDocs);

                for (int i = 0; i < docs.Count; i++)
                {
                    Assert.AreEqual(docs[i].Language, actualDocs[i].Language);
                    Assert.AreEqual(docs[i].Summary, actualDocs[i].Summary);
                }
            }
        }
 public StubResourceFileService(ResourceRepository resourceRepository)
 {
     _resourceRepository = resourceRepository;
 }
 public virtual void Init()
 {
     _resourceRepository = new ResourceRepository(new ContainerBuilder().Build());
 }
        public virtual void Init()
        {
            var builder = new ContainerBuilder();

            builder.RegisterAutoMocking(MockBehavior.Loose);

            builder.RegisterType<StubCacheFileService>().As<ICacheFileService>();
            builder.RegisterInstance(new StubResourceProcessingService()).As<IResourceProcessingService>();
            builder.RegisterType<StubCacheService>().As<ICacheService>();

            builder.RegisterType<CombinatorService>().As<ICombinatorService>();

            _container = builder.Build();

            _resourceRepository = new ResourceRepository(_container);

            builder = new ContainerBuilder();
            builder.RegisterInstance(_resourceRepository).As<ResourceRepository>(); // For StubCacheFileService
            builder.Update(_container);

            _combinatorService = _container.Resolve<ICombinatorService>();
        }
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ImportModule implements the IPortable ImportModule Interface.
        /// </summary>
        /// <param name="moduleId">The Id of the module to be imported.</param>
        /// <param name="content">The content to be imported.</param>
        /// <param name="version">The version of the module to be imported.</param>
        /// <param name="userId">The Id of the user performing the import.</param>
        /// -----------------------------------------------------------------------------
        public void ImportModule(int moduleId, string content, string version, int userId)
        {
            var groups = new GroupRepository();
            var xmldnngroups = DotNetNuke.Common.Globals.GetContent(content, "Groups");
            var xmlGroupsNodeList = xmldnngroups.SelectNodes("Group");

            if (xmlGroupsNodeList == null) return;

            foreach (XmlNode xmldnngroup in xmlGroupsNodeList)
            {
                //Import a group
                var resourceGroupId = xmldnngroup.SelectSingleNode("ResourceGroupId");
                var resourceName = xmldnngroup.SelectSingleNode("ResourceName");

                if (resourceGroupId == null || resourceName == null) continue;

                var objdnngroup = new Group
                {
                    ResourceGroupId = new Guid(resourceGroupId.InnerText),
                    ResourceName = resourceName.InnerText,
                };

                groups.ImportCreate(objdnngroup);

                var resources = new ResourceRepository();
                var xmlResourcesNodeList = xmldnngroup.SelectNodes("Resources/Resource");

                //Import the resources of this group
                if (xmlResourcesNodeList == null) return;
                foreach (XmlNode xmldnnresource in xmlResourcesNodeList)
                {
                    var rGroupId = xmldnnresource.SelectSingleNode("ResourceGroupId");
                    var resourceKey = xmldnnresource.SelectSingleNode("ResourceKey");
                    var resourceValue = xmldnnresource.SelectSingleNode("ResourceValue");

                    if (rGroupId == null || resourceKey == null || resourceValue == null) continue;

                    var objdnnresource = new Resource
                    {
                        ResourceGroupId = new Guid(rGroupId.InnerText),
                        ResourceKey = resourceKey.InnerText,
                        ResourceValue = resourceValue.InnerText,

                    };

                    resources.Create(objdnnresource);
                }
            }
        }