Example #1
0
        public override void UpdateEntityFields(ApplicationEntity entity)
        {
            var companyEntity = (CompanyEntity)entity;

            companyEntity.EmpresaId = EmpresaId;
            base.UpdateEntityFields(companyEntity);
        }
        private ApplicationDto Convert(ApplicationEntity source)
        {
            var result = new ApplicationDto();

            result.AppNavBarUrl          = source.AppNavBarUrl;
            result.IsOnline              = source.IsOnline;
            result.IsRegistered          = source.IsRegistered;
            result.IsHealthy             = source.IsHealthy;
            result.BackButtonUrl         = source.BackButtonUrl;
            result.Branding              = source.Branding;
            result.BreadcrumbsUrl        = source.BreadcrumbsUrl;
            result.Description           = source.Description;
            result.EntrypointUrl         = source.EntrypointUrl;
            result.HealthCheckUrl        = source.HealthCheckUrl;
            result.LayoutName            = source.LayoutName;
            result.MainMenuText          = source.MainMenuText;
            result.Name                  = source.Name;
            result.PersonalisationUrl    = source.PersonalisationUrl;
            result.RequiresAuthorization = source.RequiresAuthorization;
            result.RootUrl               = source.RootUrl;
            result.RouteName             = source.RouteName;
            result.ShowSideBar           = source.ShowSideBar;
            result.SidebarUrl            = source.SidebarUrl;
            result.Title                 = source.Title;
            return(result);
        }
        public bool AssignRoleToUser(ApplicationEntity application, UserEntity user, RolesEntity role)
        {
            try
            {
                using (IUnitOfWork uow = _UnitFactory.GetUnit(this))
                {
                    uow.BeginTransaction();
                    if (!uow.Query <AppUserRoleEntity>().Any(x => x.ApplicationId.Equals(application.IdApplication) && x.RoleId.Equals(role.Id) && x.UserId.Equals(user.Id)))
                    {
                        AppUserRoleEntity app = new AppUserRoleEntity();
                        app.ApplicationId = app.ApplicationId;
                        app.RoleId        = role.Id;
                        app.UserId        = user.Id;
                        uow.SaveOrUpdate(app);

                        uow.Commit();
                        return(true);
                    }
                }
            }
            catch (Exception err)
            {
                //TODO:Add log here
                return(false);
            }
            return(true);
        }
Example #4
0
        public void ApplicationErrorPopulation()
        {
            IApplicationEntity expected = new ApplicationEntity();

            expected.OnlyInnerException = true;
            expected.WrittenToPlatform  = true;
            expected.Note        = "note";
            expected.LogLevel    = LogLevel.Debug;
            expected.Application = APPLICATION_NAME;

            var result = _application.PopulateApplicationEntity(new Exception(), true, true, LogLevel.Debug, "note");

            Assert.AreEqual(expected.Application, result.Application);
            Assert.AreEqual(expected.LogLevel, result.LogLevel);
            Assert.AreEqual(expected.Note, result.Note);
            Assert.AreEqual(expected.ApplicationMessage, result.ApplicationMessage);
            Assert.AreEqual(expected.WrittenToPlatform, result.WrittenToPlatform);
            Assert.AreEqual(expected.OnlyInnerException, result.OnlyInnerException);
            Assert.AreEqual(expected.CurrentMethod, result.CurrentMethod);

            result = _application.PopulateApplicationEntity(new Exception(), true, true, LogLevel.Debug, null);

            expected.Note = string.Empty;

            Assert.AreEqual(expected.Application, result.Application);
            Assert.AreEqual(expected.LogLevel, result.LogLevel);
            Assert.AreEqual(expected.Note, result.Note);
            Assert.AreEqual(expected.ApplicationMessage, result.ApplicationMessage);
            Assert.AreEqual(expected.WrittenToPlatform, result.WrittenToPlatform);
            Assert.AreEqual(expected.OnlyInnerException, result.OnlyInnerException);
            Assert.AreEqual(expected.CurrentMethod, result.CurrentMethod);
        }
Example #5
0
        /// <summary>
        /// After setting up the mover with your callback(s), call this to start the move process.  All updates
        /// about the operation will be provided via the callbacks.
        /// </summary>
        /// <param name="hostAE">An entity containing the AE title to represent the SCU.</param>
        /// <param name="remoteAE">An entity containing the SCP to attempt to contact.</param>
        /// <param name="sendToAE">This is the AE Title of the move destination.  The remote AE must have full information
        /// about this entity (hostname/address and port), because only the title is passed via this request.</param>
        /// <param name="requestData">A filled out request for what images to target with the MOVE request.</param>
        public void StartMove(ApplicationEntity hostAE, ApplicationEntity remoteAE, string sendToAE, QRRequestData requestData)
        {
            this.FindRequest = requestData;
            this.SendToAE    = sendToAE;

            if (requestData.QueryLevel == QueryRetrieveLevel.PatientRoot)
            {
                conn.AddPresentationContext(new PresentationContext(AbstractSyntaxes.PatientRootQueryRetrieveInformationModelMOVE, new List <TransferSyntax> {
                    TransferSyntaxes.ImplicitVRLittleEndian
                }));
            }
            else if (requestData.QueryLevel == QueryRetrieveLevel.PatientStudyOnly)
            {
                conn.AddPresentationContext(new PresentationContext(AbstractSyntaxes.PatientStudyOnlyQueryRetrieveInformationModelMOVERetired, new List <TransferSyntax> {
                    TransferSyntaxes.ImplicitVRLittleEndian
                }));
            }
            else if (requestData.QueryLevel == QueryRetrieveLevel.StudyRoot)
            {
                conn.AddPresentationContext(new PresentationContext(AbstractSyntaxes.StudyRootQueryRetrieveInformationModelMOVE, new List <TransferSyntax> {
                    TransferSyntaxes.ImplicitVRLittleEndian
                }));
            }

            StartConnection(hostAE, remoteAE);
        }
        private async Task ValidatePayload(
            AuthenticationPayload payload, ApplicationEntity application)
        {
            //Valid request
            if (payload.OldSyncKey == application.NewSyncKey)
            {
                application.OldSyncKey = payload.OldSyncKey;
                application.NewSyncKey = payload.NewSyncKey;

                await mApplicationStore.UpdateState(application.Id, application.OldSyncKey,
                                                    application.NewSyncKey);
            }
            //Handling errors
            else if (payload.OldSyncKey == application.OldSyncKey &&
                     payload.NewSyncKey == application.NewSyncKey)
            {
                throw new ValidationFailedException("Payload invalid - equal to stored payload");
            }
            //Probably compromised private key
            else
            {
                await mApplicationStore.Revoke(application.Id);

                throw new ValidationFailedException("Payload is invalid, application revoked");
            }
        }
Example #7
0
        private void listener_AssociationRequest(DICOMConnection conn)
        {
            //make sure we have the calling AE in our list...
            ApplicationEntity entity = this._db.GetEntity(conn.CallingAE);

            if (this._settings.PromiscuousMode)
            {
                conn.SendAssociateAC();
            }
            else if (entity != null)
            {
                if (conn.CalledAE.Trim() != this._settings.AETitle.Trim())
                {
                    this._logger.Log(LogLevel.Error, "Rejecting Association: Called AE (" + conn.CalledAE + ") doesn't match our AE (" + this._settings.AETitle + ")");
                    conn.SendAssociateRJ(AssociateRJResults.RejectedPermanent, AssociateRJSources.DICOMULServiceProviderPresentation, AssociateRJReasons.CalledAENotRecognized);
                }
                else if (conn.RemoteEndPoint.Address.ToString() != entity.Address)
                {
                    this._logger.Log(LogLevel.Error, "Rejecting Association: Remote Address (" + conn.RemoteEndPoint.Address.ToString() + ") doesn't match AE (" + conn.CallingAE + ")'s Address (" + entity.Address + ")");
                    conn.SendAssociateRJ(AssociateRJResults.RejectedPermanent, AssociateRJSources.DICOMULServiceProviderPresentation, AssociateRJReasons.CallingAENotRecognized);
                }
                else
                {
                    conn.SendAssociateAC();
                }
            }
            else
            {
                this._logger.Log(LogLevel.Error, "Rejecting Association: Couldn't find entity in list with AE title (" + conn.CallingAE + ")");
                conn.SendAssociateRJ(AssociateRJResults.RejectedPermanent, AssociateRJSources.DICOMULServiceProviderPresentation, AssociateRJReasons.CallingAENotRecognized);
            }
        }
        // for read
        public ApplicationEntity GetApplicationEntityRecord(string recordID, string UserID)
        {
            SqlDataReader dr = null;

            try
            {
                ApplicationEntity applicationentity = new ApplicationEntity();
                SqlParameter[]    Parameters        = { new SqlParameter("@SNo", Convert.ToInt32(recordID)),
                                                        new SqlParameter("@UserID",        Convert.ToInt32(UserID)) };

                dr = SqlHelper.ExecuteReader(ReadConnectionString.WebConfigConnectionString, CommandType.StoredProcedure, "dbo.GetRecordApplicationEntity", Parameters);

                if (dr.Read())
                {
                    applicationentity.SNo = Convert.ToInt32(dr["sno"]);
                    applicationentity.ApplicationEntitySno = dr["applicationSNo"].ToString();
                    applicationentity.ApplicationCode      = dr["applicationcode"].ToString();
                    applicationentity.ApplicationName      = dr["applicationName"].ToString();
                    applicationentity.Remarks = dr["remarks"].ToString();
                }
                dr.Close();
                return(applicationentity);
            }
            catch (Exception ex)//
            {
                dr.Close();
                throw ex;
            }
        }
        public async Task <UserOrganizationApplication> Execute(CreateApplication command,
                                                                CancellationToken cancellationToken = new CancellationToken())
        {
            GetOrganization query = new GetOrganizationQuery(command.UserId, command.OrganizationId);

            Organization organization = await _organizationQueryHandler.Execute(query, cancellationToken);

            CloudTable appTable = _tableProvider.GetTable(_settings.ApplicationTableName);

            var appEntity = new ApplicationEntity(command.ApplicationName, command.Timestamp);

            await appTable.ExecuteAsync(TableOperation.Insert(appEntity), cancellationToken);

            var indexEntity = new OrganizationApplicationIndexEntity(organization.Id, organization.Name, appEntity.Id, command.ApplicationName,
                                                                     command.Timestamp);

            CloudTable indexTable = _tableProvider.GetTable(_settings.OrganizationApplicationIndexTableName);

            await indexTable.ExecuteAsync(TableOperation.Insert(indexEntity), cancellationToken);

            var userIndexEntity = new UserApplicationIndexEntity(command.UserId, organization.Id, organization.Name, appEntity.Id, command.ApplicationName,
                                                                 command.Timestamp);

            CloudTable userIndexTable = _tableProvider.GetTable(_settings.UserApplicationIndexTableName);

            await userIndexTable.ExecuteAsync(TableOperation.Insert(userIndexEntity), cancellationToken);

            return(userIndexEntity);
        }
Example #10
0
        public ActionResult Edit(int id, ApplicationViewModel viewModel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }
                else
                {
                    var entity = new ApplicationEntity();

                    entity.Id          = viewModel.Id;
                    entity.Name        = viewModel.Name;
                    entity.Description = viewModel.Description;
                    entity.IsActive    = viewModel.IsActive;

                    this.repository.Edit(id, entity);
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
        public async Task WhenFindingExistingApplicationWithWrongPasswordThenNullIsReturned()
        {
            // Arrange
            ApplicationEntity application = new ApplicationEntity()
            {
                Id           = 0,
                DisplayName  = "TestApplicationDisplayName",
                PasswordHash = "TestPasswordHash",
                PasswordSalt = "TestPasswordSalt"
            };

            IApplicationRepository fakeApplicationRepository = A.Fake <IApplicationRepository>();

            A.CallTo(() => fakeApplicationRepository.TryGetByDisplayNameAsync("TestApplicationDisplayName")).Returns(Task.FromResult(application));

            IUnitOfWork fakeUnitOfWork = A.Fake <IUnitOfWork>();

            IPasswordWithSaltHasher fakePasswordHasher = A.Fake <IPasswordWithSaltHasher>();

            A.CallTo(() => fakePasswordHasher.CheckPassword(A <string> .Ignored, A <string> .Ignored, A <string> .Ignored)).Returns(false);

            IApplicationService applicationService = new ApplicationService(fakeApplicationRepository, fakeUnitOfWork, fakePasswordHasher);

            // Act
            ApplicationDto applicationDto = await applicationService.FindApplicationAsync("TestApplicationDisplayName", "TestPassword");

            // Assert
            Assert.IsNull(applicationDto);
        }
        public async Task <int> AddApplicationAsync(ApplicationCreateDto applicationCreateDto)
        {
            if (applicationCreateDto == null ||
                string.IsNullOrWhiteSpace(applicationCreateDto.DisplayName) ||
                string.IsNullOrWhiteSpace(applicationCreateDto.Password))
            {
                throw new ArgumentException("Application name and password must be provided.");
            }

            if (await _applicationRepository.TryGetByDisplayNameAsync(applicationCreateDto.DisplayName) != null)
            {
                throw new ArgumentException($"Application with DisplayName {applicationCreateDto.DisplayName} already exists.");
            }

            ApplicationEntity application = applicationCreateDto.ToApplication();

            HashWithSaltResult hashWithSaltResultDto = _passwordWithSaltHasher.HashPassword(applicationCreateDto.Password);

            application.PasswordHash = hashWithSaltResultDto.Hash;
            application.PasswordSalt = hashWithSaltResultDto.Salt;

            _applicationRepository.Add(application);
            await _unitOfWork.CommitAsync();

            return(application.Id);
        }
        private static async Task ReadEvent(Graph graph, ApplicationEntity application)
        {
            try
            {
                var events = await Events.GetEvents(graph);

                LogEntity log = new LogEntity
                {
                    ApplicationId = application.Id,
                    Message       = $"读取条数:{events.Count}",
                    Operation     = "读取日历事件",
                    Status        = "成功",
                    CreateDate    = DateTime.Now
                };
                LiteDbHelper.Instance.InsertOrUpdate(nameof(LogEntity), log);
            }
            catch (Exception e)
            {
                LogEntity log = new LogEntity
                {
                    ApplicationId = application.Id,
                    Message       = e.Message,
                    Operation     = "读取日历事件",
                    Status        = "失败",
                    CreateDate    = DateTime.Now
                };
                LiteDbHelper.Instance.InsertOrUpdate(nameof(LogEntity), log);
            }
        }
Example #14
0
        public static ServerDirectoryEntry ToDataContract(this Device device)
        {
            bool isStreaming = device.StreamingHeaderPort != null && device.StreamingImagePort != null;
            var  server      = new ApplicationEntity
            {
                Name          = device.Name,
                AETitle       = device.AETitle,
                ScpParameters = new ScpParameters(device.HostName, device.Port),
                Location      = device.Location,
                Description   = device.Description
            };

            if (isStreaming)
            {
                server.StreamingParameters = new StreamingParameters(device.StreamingHeaderPort.Value, device.StreamingImagePort.Value);
            }

            Dictionary <string, object> extensionData = null;

            if (device.ExtensionData != null)
            {
                extensionData = Serializer.DeserializeServerExtensionData(device.ExtensionData);
            }

            return(new ServerDirectoryEntry(server)
            {
                IsPriorsServer = device.IsPriorsServer, Data = extensionData
            });
        }
        private static async Task ReadFiles(Graph graph, ApplicationEntity application)
        {
            try
            {
                var files = await File.ListFiles(graph);

                LogEntity log = new LogEntity
                {
                    ApplicationId = application.Id,
                    Message       = $"读取条数:{files.Count}",
                    Operation     = "读取OneDrive",
                    Status        = "成功",
                    CreateDate    = DateTime.Now
                };
                LiteDbHelper.Instance.InsertOrUpdate(nameof(LogEntity), log);
            }
            catch (Exception e)
            {
                LogEntity log = new LogEntity
                {
                    ApplicationId = application.Id,
                    Message       = e.Message,
                    Operation     = "读取OneDrive",
                    Status        = "失败",
                    CreateDate    = DateTime.Now
                };
                LiteDbHelper.Instance.InsertOrUpdate(nameof(LogEntity), log);
            }
        }
        private static async Task ReadMail(Graph graph, ApplicationEntity application)
        {
            try
            {
                var mailList = await Mail.GetMailInfo(graph, 5);

                LogEntity log = new LogEntity
                {
                    ApplicationId = application.Id,
                    Message       = $"读取条数:{mailList.Count}",
                    Operation     = "读取邮箱",
                    Status        = "成功",
                    CreateDate    = DateTime.Now
                };
                LiteDbHelper.Instance.InsertOrUpdate(nameof(LogEntity), log);
            }
            catch (Exception e)
            {
                LogEntity log = new LogEntity
                {
                    ApplicationId = application.Id,
                    Message       = e.Message,
                    Operation     = "读取邮箱",
                    Status        = "失败",
                    CreateDate    = DateTime.Now
                };
                LiteDbHelper.Instance.InsertOrUpdate(nameof(LogEntity), log);
            }
        }
Example #17
0
        public void InternalCMoveTest()
        {
            // make sure DICOM at "." is empty
            DicomDir dir = new DicomDir(".");

            dir.Empty();

            ApplicationEntity storage = new ApplicationEntity("ImageServer", IPAddress.Parse("127.0.0.1"), 2000);
            ApplicationEntity server  = new ApplicationEntity("ImageServer", IPAddress.Parse("127.0.0.1"), 5104);

            Dictionary <string, ApplicationEntity> stations = new Dictionary <string, ApplicationEntity>();

            stations.Add(storage.Title, storage);

            StorageTest.Start(storage);
            CMoveTest.Start(server, stations);

            // add three images to a DICOMDIR at "."
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\Y2ASNFDS.dcm", storage, false);
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\WNGVU1P1.dcm", storage, false);
            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\THGLUZ5J.dcm", storage, false);

            // ask for an image from a DICOMDIR at "." be delivered to a DICOMDIR at "."
            // should create a duplicate SOPInstanceUID, which results in a WARNING
            try
            {
                move(storage.Title, server);
            }
            catch (Exception)
            {
            }

            CMoveTest.Stop();
            StorageTest.Stop();
        }
Example #18
0
        public static void Start(ApplicationEntity host)
        {
            if (server != null)
            {
                throw new Exception("CFindTest.Server in use.");
            }

            server = new Server(host.Title, host.Port);

            VerificationServiceSCP echo = new VerificationServiceSCP();

            echo.Syntaxes.Add(Syntax.ImplicitVrLittleEndian);
            echo.Syntaxes.Add(Syntax.ExplicitVrLittleEndian);

            CFindServiceSCP study = new CFindServiceSCP(SOPClass.StudyRootQueryRetrieveInformationModelFIND);

            study.Syntaxes.Add(Syntax.ImplicitVrLittleEndian);
            study.Syntaxes.Add(Syntax.ExplicitVrLittleEndian);

            CFindServiceSCP patient = new CFindServiceSCP(SOPClass.PatientRootQueryRetrieveInformationModelFIND);

            patient.Syntaxes.Add(Syntax.ImplicitVrLittleEndian);
            patient.Syntaxes.Add(Syntax.ExplicitVrLittleEndian);

            server.AddService(echo);
            server.AddService(study);
            server.AddService(patient);

            server.Start();
        }
Example #19
0
        public MessageEntity Update(ApplicationEntity entity)
        {
            var msgEntity = new MessageEntity();

            try
            {
                using (var _uow = _unitOfWorkProvider.GetUnitOfWork())
                {
                    var data = _uow.Db.SingleOrDefault <ApplicationEntity>("SELECT * FROM Application WHERE Id=@0", entity.Id);
                    if (data != null && data.Id == entity.Id)
                    {
                        entity.CreatedBy   = data.CreatedBy;
                        entity.CreatedDate = data.CreatedDate;
                        _uow.Db.Update(entity);
                        msgEntity.message = ConstantsHandler.ErrorMessage.Message_OK;
                        msgEntity.result  = true;
                        msgEntity.code    = 0;
                    }
                    _uow.Commit();
                }
            }
            catch (Exception ex)
            {
                msgEntity.result  = false;
                msgEntity.message = ConstantsHandler.ErrorMessage.Message_EX;
                Logger.ErrorLog(ConstantsHandler.ForderLogName.RepoBranch, "Update : ", ex.ToString());
            }

            return(msgEntity);
        }
Example #20
0
        public void EditorTest()
        {
            Process pacs = new Process();

            pacs.StartInfo.FileName = Tools.RootFolder + @"\EK\Capture\Dicom\Tools\DicomEditor\bin\Debug\DicomEditor.exe";

            ApplicationEntity editor  = new ApplicationEntity("DICOMEDITOR", IPAddress.Parse("127.0.0.1"), 2009);
            ApplicationEntity console = new ApplicationEntity("CONSOLE", IPAddress.Parse("127.0.0.1"), 2010);

            try
            {
                pacs.Start();
                StorageTest.Start(console);
            }
            catch
            {
                pacs.StartInfo.FileName = Tools.RootFolder + @"\EK\Capture\Dicom\Tools\DicomEditor\bin\Debug\DicomEditor.exe";
                pacs.Start();
            }
            Thread.Sleep(1000);

            StorageTest.store(@"EK\Capture\Dicom\DicomToolKit\Test\Data\DicomDir\THGLUZ5J.dcm", editor, true);

            System.Windows.Forms.MessageBox.Show("Click OK to stop Server.");

            StorageTest.Stop();

            pacs.Kill();
        }
Example #21
0
        public override void UpdateEntityFields(ApplicationEntity entity)
        {
            var linea = (Linea)entity;

            linea.Nombre = Nombre;
            base.UpdateEntityFields(linea);
        }
Example #22
0
        public void ExternalPrinterStatusTest()
        {
            ApplicationEntity host = new ApplicationEntity("NER_8900", IPAddress.Parse("10.95.16.219"), 5040);

            PrintServiceSCU print = new PrintServiceSCU(SOPClass.BasicGrayscalePrintManagementMetaSOPClass);

            print.Syntaxes.Add(Syntax.ImplicitVrLittleEndian);

            Association association = new Association();

            association.AddService(print);

            PrinterStatusEventHandler handler = new PrinterStatusEventHandler(OnPrinterStatus);

            print.PrinterStatus += handler;

            if (association.Open(host))
            {
                if (print.Active)
                {
                    print.GetPrinterStatus();
                }
            }
            else
            {
                Debug.WriteLine("\ncan't Open.");
            }

            association.Close();
        }
Example #23
0
        public static async Task <RoleEntity> GivenARole(
            this TestServerFixture fixture,
            string name,
            ApplicationEntity application,
            SubjectEntity subject,
            bool withPermissions = true)
        {
            var role = new RoleEntity(name, application.Id, $"{name} role");

            await fixture.ExecuteDbContextAsync(async db =>
            {
                role.Subjects.Add(new RoleSubjectEntity {
                    SubjectId = subject.Id
                });

                if (withPermissions)
                {
                    foreach (var permission in application.Permissions)
                    {
                        role.Permissions.Add(new RolePermissionEntity {
                            PermissionId = permission.Id
                        });
                    }
                }

                db.Add(role);

                await db.SaveChangesAsync();
            });

            return(role);
        }
Example #24
0
        public static void End(string uid, ApplicationEntity host)
        {
            MppsServiceSCU mpps = new MppsServiceSCU();

            mpps.Syntaxes.Add(Syntax.ExplicitVrLittleEndian);

            Association association = new Association();

            association.AddService(mpps);

            if (association.Open(host))
            {
                DataSet dicom = DataSetTest.GetDataSet(Path.Combine(Tools.RootFolder, @"EK\Capture\Dicom\DicomToolKit\Test\Data\Mpps\end.dcm"));

                mpps.End(uid, dicom);
                //System.Console.WriteLine("end done!");
            }
            else
            {
                //System.Console.WriteLine("\ncan't Open.");
            }
            //System.Console.WriteLine("before Close!");
            association.Close();
            //System.Console.WriteLine("after Close!");
        }
Example #25
0
        public static void EnsureSampleData()
        {
            List <UserEntity> userList = RepositoryContext.Current.Users.GetAll();


            if (userList == null || userList.Count == 0)
            {
                ApplicationEntity app = new ApplicationEntity();
                app.ApplicationName = "SampleApp";
                app.IsActive        = true;
                app.StartDate       = DateTime.Now;
                app.EndDate         = DateTime.Now.AddYears(1);
                app.PublicKey       = new Guid("{8C075ED0-45A7-495A-8E09-3A98FD6E8248}");
                RepositoryContext.Current.Applications.Save(app);

                // Insert admin user
                UserEntity user = new UserEntity();
                user.CreationDate = DateTime.Now;
                user.Email        = "*****@*****.**";
                user.IsAdmin      = true;
                user.IsApproved   = true;
                user.IsLockedOut  = false;
                user.Password     = UserHelper.EncodePassword("12345678");
                user.Username     = "******";

                RepositoryContext.Current.Users.Save(user);

                RolesEntity role = RepositoryContext.Current.Roles.GetRoleByName(Constants.Roles.Admin);
                RepositoryContext.Current.Applications.AssignRoleToUser(app, user, role);
            }
        }
Example #26
0
        public void InternalPrinterStatusTest()
        {
            ApplicationEntity host = new ApplicationEntity("PRINTER", IPAddress.Parse("10.95.16.219"), 5042);

            Server server = StartServer(host.Title, host.Port, null);

            PrintServiceSCU print = new PrintServiceSCU(SOPClass.BasicGrayscalePrintManagementMetaSOPClass);

            print.Syntaxes.Add(Syntax.ImplicitVrLittleEndian);

            Association association = new Association();

            association.AddService(print);

            PrinterStatusEventHandler handler = new PrinterStatusEventHandler(OnPrinterStatus);

            print.PrinterStatus += handler;

            if (association.Open(host))
            {
                if (print.Active)
                {
                    PrinterStatusEventArgs status = print.GetPrinterStatus();
                }
            }
            else
            {
                Debug.WriteLine("\ncan't Open.");
            }

            association.Close();

            server.Stop();
        }
Example #27
0
        public ActionResult Create(ApplicationViewModel viewModel)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }
                else
                {
                    ApplicationEntity entity = new ApplicationEntity();

                    entity.Name        = viewModel.Name;
                    entity.Description = viewModel.Description;
                    entity.IsActive    = false;

                    OperationResult <bool> result = this.repository.Save(entity);
                }

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Example #28
0
        public static async Task Seed(BaleaDbContext db)
        {
            if (!db.Roles.Any())
            {
                var john = new SubjectEntity("Alice", "1");
                var mary = new SubjectEntity("Bob", "11");

                db.Add(john);
                db.Add(mary);

                await db.SaveChangesAsync();

                var application          = new ApplicationEntity(BaleaConstants.DefaultApplicationName, "Default application");
                var viewGradesPermission = new PermissionEntity(Policies.GradesView);
                var editGradesPermission = new PermissionEntity(Policies.GradesEdit);
                application.Permissions.Add(viewGradesPermission);
                application.Permissions.Add(editGradesPermission);
                var teacherRole = new RoleEntity("Teacher", "Teacher role");
                teacherRole.Subjects.Add(new RoleSubjectEntity {
                    SubjectId = john.Id
                });
                teacherRole.Permissions.Add(new RolePermissionEntity {
                    Permission = viewGradesPermission
                });
                teacherRole.Permissions.Add(new RolePermissionEntity {
                    Permission = editGradesPermission
                });
                application.Roles.Add(teacherRole);
                application.Delegations.Add(new DelegationEntity(john.Id, mary.Id, DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1), true));
                db.Applications.Add(application);
                await db.SaveChangesAsync();
            }
        }
Example #29
0
        public IActionResult AddApplication(int id)
        {
            ApplicationEntity application;

            if (id == 0)
            {
                ViewBag.Title = "添加新应用";
                application   = new ApplicationEntity();
            }
            else
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier);
                if (userId == null)
                {
                    return(RedirectToAction("Login", "User"));
                }
                application = LiteDbHelper.Instance.GetCollection <ApplicationEntity>(nameof(ApplicationEntity))
                              .FindOne(x => x.Id == id && x.UserId == userId.Value);
                if (application == null)
                {
                    return(RedirectToAction("Index", new { message = "当前应用不存在或当前应用不属于你" }));
                }
                ViewBag.Title = "修改当前应用";
            }
            ViewBag.CreateUrl = Graph.GetCreateAppUrl("DeveloperRenewal", Request.GetRegisterUrl());
            return(View(application));
        }
Example #30
0
        public MessageEntity Create(ApplicationEntity entity)
        {
            var msgEntity = new MessageEntity();

            try
            {
                using (var _uow = _unitOfWorkProvider.GetUnitOfWork())
                {
                    int Id = Protector.Int(_uow.Db.Insert(entity));
                    if (Id > 0)
                    {
                        msgEntity.code    = 0;
                        msgEntity.result  = true;
                        msgEntity.message = ConstantsHandler.ErrorMessage.Message_OK;

                        _uow.Commit();
                    }
                    else
                    {
                        msgEntity.code    = -2;
                        msgEntity.result  = false;
                        msgEntity.message = ConstantsHandler.ErrorMessage.Message_ERR;
                    }
                }
            }
            catch (Exception ex)
            {
                msgEntity.code    = -1;
                msgEntity.result  = false;
                msgEntity.message = ConstantsHandler.ErrorMessage.Message_EX;
                Logger.ErrorLog(ConstantsHandler.ForderLogName.RepoBranch, "Create : ", ex.ToString());
            }
            return(msgEntity);
        }
 public WcfStudyRootQuery( )
 {
     var ae = new ApplicationEntity
         {
             AETitle = "UIHPACSSERVER",
             ScpParameters = new ScpParameters("localhost", 3333)
         };
     _remoteServer = ae;
     _real = new DicomStudyRootQuery("lrf", _remoteServer);
 }
Example #32
0
        private static void QueryByApi()
        {
            ApplicationEntity ae = new ApplicationEntity
                {
                    AETitle = "UIHPACSSERVER",
                    ScpParameters = new ScpParameters("localhost", 3333)
                };

            var query = new StudyRootQueryBridge(new RemoteStudyRootQuery(ae));
            IList<StudyRootStudyIdentifier> results = query.QueryByPatientId("013127");
            foreach (var id in results)
            {
                Console.WriteLine(@"PatientId = {0}, PatientName = {1}", id.PatientId, id.PatientsName);
            }
        }
Example #33
0
        private static DICOMElement CreateVRObject(string vr, Constants.EncodeType encType, byte[] data, Tag t, bool isLittleEndian, bool isIndefinite)
        {
            switch (vr)
            {
                case "CS":
                    CodeString cs = new CodeString();
                    cs.ByteData = data;
                    cs.EncodeType = encType;
                    cs.IsLittleEndian = isLittleEndian;
                    cs.Tag = t;
                    return cs;

                case "SH":
                    ShortString sh = new ShortString();
                    sh.ByteData = data;
                    sh.EncodeType = encType;
                    sh.IsLittleEndian = isLittleEndian;
                    sh.Tag = t;
                    return sh;

                case "LO":
                    LongString lo = new LongString();
                    lo.ByteData = data;
                    lo.EncodeType = encType;
                    lo.IsLittleEndian = isLittleEndian;
                    lo.Tag = t;
                    return lo;

                case "ST":
                    ShortText st = new ShortText();
                    st.ByteData = data;
                    st.EncodeType = encType;
                    st.IsLittleEndian = isLittleEndian;
                    st.Tag = t;
                    return st;

                case "LT":
                    LongText lt = new LongText();
                    lt.ByteData = data;
                    lt.EncodeType = encType;
                    lt.IsLittleEndian = isLittleEndian;
                    lt.Tag = t;
                    return lt;

                case "UT":
                    UnlimitedText ut = new UnlimitedText();
                    ut.ByteData = data;
                    ut.EncodeType = encType;
                    ut.IsLittleEndian = isLittleEndian;
                    ut.Tag = t;
                    return ut;

                case "AE":
                    ApplicationEntity ae = new ApplicationEntity();
                    ae.ByteData = data;
                    ae.EncodeType = encType;
                    ae.IsLittleEndian = isLittleEndian;
                    ae.Tag = t;
                    return ae;

                case "PN":
                    PersonsName pn = new PersonsName();
                    pn.ByteData = data;
                    pn.EncodeType = encType;
                    pn.IsLittleEndian = isLittleEndian;
                    pn.Tag = t;
                    return pn;

                case "UI":
                    UniqueIdentifier ui = new UniqueIdentifier();
                    ui.ByteData = data;
                    ui.EncodeType = encType;
                    ui.IsLittleEndian = isLittleEndian;
                    ui.Tag = t;
                    return ui;

                case "DA":
                    DateVR da = new DateVR();
                    da.ByteData = data;
                    da.EncodeType = encType;
                    da.IsLittleEndian = isLittleEndian;
                    da.Tag = t;
                    return da;

                case "TM":
                    TimeVR tm = new TimeVR();
                    tm.ByteData = data;
                    tm.EncodeType = encType;
                    tm.IsLittleEndian = isLittleEndian;
                    tm.Tag = t;
                    return tm;

                case "DT":
                    DateTimeVR dt = new DateTimeVR();
                    dt.ByteData = data;
                    dt.EncodeType = encType;
                    dt.IsLittleEndian = isLittleEndian;
                    dt.Tag = t;
                    return dt;

                case "AS":
                    AgeString aSt = new AgeString();
                    aSt.ByteData = data;
                    aSt.EncodeType = encType;
                    aSt.IsLittleEndian = isLittleEndian;
                    aSt.Tag = t;
                    return aSt;

                case "IS":
                    IntegerString iSt = new IntegerString();
                    iSt.ByteData = data;
                    iSt.EncodeType = encType;
                    iSt.IsLittleEndian = isLittleEndian;
                    iSt.Tag = t;
                    return iSt;

                case "DS":
                    DecimalString ds = new DecimalString();
                    ds.ByteData = data;
                    ds.EncodeType = encType;
                    ds.IsLittleEndian = isLittleEndian;
                    ds.Tag = t;
                    return ds;

                case "SS":
                    SignedShort ss = new SignedShort();
                    ss.ByteData = data;
                    ss.EncodeType = encType;
                    ss.IsLittleEndian = isLittleEndian;
                    ss.Tag = t;
                    return ss;

                case "US":
                    UnsignedShort us = new UnsignedShort();
                    us.ByteData = data;
                    us.EncodeType = encType;
                    us.IsLittleEndian = isLittleEndian;
                    us.Tag = t;
                    return us;

                case "SL":
                    SignedLong sl = new SignedLong();
                    sl.ByteData = data;
                    sl.EncodeType = encType;
                    sl.IsLittleEndian = isLittleEndian;
                    sl.Tag = t;
                    return sl;

                case "UL":
                    UnsignedLong ul = new UnsignedLong();
                    ul.ByteData = data;
                    ul.EncodeType = encType;
                    ul.IsLittleEndian = isLittleEndian;
                    ul.Tag = t;
                    return ul;

                case "AT":
                    AttributeTag at = new AttributeTag();
                    at.ByteData = data;
                    at.EncodeType = encType;
                    at.IsLittleEndian = isLittleEndian;
                    at.Tag = t;
                    return at;

                case "FL":
                    FloatingPointSingle fl = new FloatingPointSingle();
                    fl.ByteData = data;
                    fl.EncodeType = encType;
                    fl.IsLittleEndian = isLittleEndian;
                    fl.Tag = t;
                    return fl;

                case "FD":
                    FloatingPointDouble fd = new FloatingPointDouble();
                    fd.ByteData = data;
                    fd.EncodeType = encType;
                    fd.IsLittleEndian = isLittleEndian;
                    fd.Tag = t;
                    return fd;

                case "OB":
                    if (t.Id == TagHelper.PIXEL_DATA)
                    {
                        PixelData fd1 = new PixelData(data, encType, isLittleEndian, "OB", isIndefinite);
                        fd1.Format = isIndefinite ? FrameDataFormat.ENCAPSULATED : FrameDataFormat.NATIVE;
                        fd1.EncodeType = encType;
                        fd1.IsLittleEndian = isLittleEndian;
                        fd1.Tag = t;
                        return fd1;
                    }
                    else
                    {
                        OtherByteString ob = new OtherByteString();
                        ob.ByteData = data;
                        ob.EncodeType = encType;
                        ob.IsLittleEndian = isLittleEndian;
                        ob.Tag = t;
                        return ob;
                    }
                case "OW":
                    if (t.Id == TagHelper.PIXEL_DATA)
                    {
                        PixelData fd2 = new PixelData(data, encType, isLittleEndian, "OW", isIndefinite);
                        fd2.Format = isIndefinite ? FrameDataFormat.ENCAPSULATED : FrameDataFormat.NATIVE;
                        fd2.EncodeType = encType;
                        fd2.IsLittleEndian = isLittleEndian;
                        fd2.Tag = t;
                        return fd2;
                    }
                    else
                    {
                        OtherWordString ow = new OtherWordString();
                        ow.ByteData = data;
                        ow.EncodeType = encType;
                        ow.IsLittleEndian = isLittleEndian;
                        ow.Tag = t;
                        return ow;
                    }

                case "OF":
                    OtherFloatString of = new OtherFloatString();
                    of.ByteData = data;
                    of.EncodeType = encType;
                    of.IsLittleEndian = isLittleEndian;
                    of.Tag = t;
                    return of;

                case "SQ":
                    Sequence s = new Sequence();
                    s.ByteData = data;
                    s.EncodeType = encType;
                    s.IsLittleEndian = isLittleEndian;
                    s.Tag = t;
                    s.ReadChildren();
                    return s;

                default:
                    //Case for unknown VR
                    DICOMElement dOb = new DICOMElement();
                    dOb.ByteData = data;
                    dOb.EncodeType = encType;
                    dOb.IsLittleEndian = isLittleEndian;
                    dOb.Tag = t;
                    return dOb;
            }
        }
        /// <summary>
        /// Creates an application.
        /// </summary>
        /// <param name="name">The name of the application.</param>
        /// <param name="friendlyName">The friendly name of the application.</param>
        /// <param name="organizationName">The organization that owns the application.</param>
        /// <param name="clientId">the client id.</param>
        /// <param name="clientSecret">the client secret.</param>
        /// <param name="homePageUrl">The home page URL.</param>
        /// <param name="authorizationCallbackUrl">The authorization callback URL.</param>
        /// <param name="accountId">The user creating the application.</param>
        /// <remarks>
        /// This call assumes the user has been already authorized to create the application.
        /// </remarks>
        public void CreateApplication(
            DomainLabel name,
            string friendlyName,
            DomainLabel organizationName,
            string clientId,
            string clientSecret,
            Uri homePageUrl,
            Uri authorizationCallbackUrl,
            EmailAddress accountId)
        {
            if (!ValidateApplicationName(name))
            {
                throw new ArgumentOutOfRangeException("name");
            }

            if (string.IsNullOrWhiteSpace(friendlyName))
            {
                throw new ArgumentOutOfRangeException("friendlyName");
            }

            if (organizationName == null)
            {
                throw new ArgumentNullException("organizationName");
            }

            if (accountId == null)
            {
                throw new ArgumentNullException("accountId");
            }

            if (string.IsNullOrWhiteSpace(clientId))
            {
                throw new ArgumentOutOfRangeException("clientId");
            }

            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                throw new ArgumentOutOfRangeException("clientSecret");
            }

            if (homePageUrl == null)
            {
                throw new ArgumentNullException("homePageUrl");
            }

            if (authorizationCallbackUrl == null)
            {
                throw new ArgumentNullException("authorizationCallbackUrl");
            }

            CloudTable appTable = this.GetApplicationTable();
            CloudTable appByClientIdTable = this.GetApplicationNameByClientIdTable();
            CloudTable orgAppsTable = this.GetOrganizationApplicationsTable();
            if (FindExistingApplication(appTable, name.ToString()) != null)
            {
                throw new InvalidOperationException("Application already exists.");
            }

            ApplicationEntity appEntity = new ApplicationEntity(name.ToString())
            {
                FriendlyName = friendlyName,
                OrganizationId = organizationName.ToString(),
                ClientId = clientId,
                ClientSecret = clientSecret,
                CreatedByAccountId = accountId.ToString(),
                CreatedTime = DateTime.UtcNow,
                HomePageUrl = homePageUrl.ToString(),
                AuthorizationCallbackUrl = authorizationCallbackUrl.ToString()
            };

            appEntity.LastModifiedByAccountId = appEntity.CreatedByAccountId;
            appEntity.LastModifiedTime = appEntity.CreatedTime;

            OrganizationApplicationEntity orgAppEntity = new OrganizationApplicationEntity(
                organizationName.ToString(),
                name.ToString());

            ApplicationNameByClientIdEntity appByClientIdEntity = new ApplicationNameByClientIdEntity(
                clientId)
                {
                    ApplicationName = name.ToString()
                };

            TableOperation insertAppByClientId = TableOperation.InsertOrMerge(appByClientIdEntity);
            appByClientIdTable.Execute(insertAppByClientId);

            TableOperation insertOrgApp = TableOperation.InsertOrMerge(orgAppEntity);
            orgAppsTable.Execute(insertOrgApp);

            TableOperation insertApp = TableOperation.Insert(appEntity);
            appTable.Execute(insertApp);
        }
        private static StudyItemList Query(QueryParameters queryParams, List<KeyValuePair<string, Exception>> failedServerInfo, List<IServerTreeNode> servers)
        {
            var aggregateStudyItemList = new StudyItemList();
            foreach (var serverNode in servers)
            {
                try
                {
                    StudyItemList serverStudyItemList;

                    if (serverNode.IsLocalDataStore)
                    {
                        serverStudyItemList = ImageViewerComponent.FindStudy(queryParams, null, "DICOM_LOCAL");
                    }
                    else if (serverNode.IsServer)
                    {
                        var server = (Server)serverNode;
                        var ae = new ApplicationEntity(
                            server.Host,
                            server.AETitle,
                            server.Name,
                            server.Port,
                            server.IsStreaming,
                            server.HeaderServicePort,
                            server.WadoServicePort);

                        serverStudyItemList = ImageViewerComponent.FindStudy(queryParams, ae, "DICOM_REMOTE");
                    }
                    else
                    {
                        throw new Exception("Server is not queryable");
                    }

                    aggregateStudyItemList.AddRange(serverStudyItemList);
                }
                catch (Exception e)
                {
                    failedServerInfo.Add(new KeyValuePair<string, Exception>(serverNode.Name, e));
                }
            }
            return aggregateStudyItemList;
        }