示例#1
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            this.RequestWindowFeature(WindowFeatures.NoTitle);
            Settings settings = Settings.LoadSettings();

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var surfaceOrientation = WindowManager.DefaultDisplay.Rotation;

            DisplayMetrics metrics = Resources.DisplayMetrics;
            int            bHeight = metrics.HeightPixels;

            if (surfaceOrientation == SurfaceOrientation.Rotation0 || surfaceOrientation == SurfaceOrientation.Rotation180)
            {
                bHeight = bHeight / 2;
            }
            bHeight = bHeight / 5;

            if (settings.invertControls && !(surfaceOrientation == SurfaceOrientation.Rotation0 ||
                                             surfaceOrientation == SurfaceOrientation.Rotation180))
            {
                LinearLayout main = FindViewById <LinearLayout>(Resource.Id.mainLayout);
                LinearLayout ll1  = FindViewById <LinearLayout>(Resource.Id.linearLayout1);
                LinearLayout ll2  = FindViewById <LinearLayout>(Resource.Id.linearLayout2);

                main.RemoveAllViews();
                main.AddView(ll2);
                main.AddView(ll1);
            }

            if (settings.nightmode)
            {
                LinearLayout main = FindViewById <LinearLayout>(Resource.Id.mainLayout);
                if (surfaceOrientation == SurfaceOrientation.Rotation0 || surfaceOrientation == SurfaceOrientation.Rotation180)
                {
                    main.SetBackgroundResource(Resource.Drawable.backgr_night_port);
                }
                else
                {
                    main.SetBackgroundResource(Resource.Drawable.backgr_night_land);
                }
            }


            // Get our button from the layout resource,
            // and attach an event to it
            Button bPlay     = FindViewById <Button>(Resource.Id.buttonPlay);
            Button bSettings = FindViewById <Button>(Resource.Id.buttonSettings);
            Button bExit     = FindViewById <Button>(Resource.Id.buttonExit);

            Drawable dPlay  = GetDrawable(Resource.Drawable.play);
            Bitmap   bmPlay = ((BitmapDrawable)dPlay).Bitmap;

            bmPlay = Bitmap.CreateScaledBitmap(bmPlay, bHeight, bHeight, false);
            dPlay  = new BitmapDrawable(this.Resources, bmPlay);
            bPlay.SetCompoundDrawablesWithIntrinsicBounds(dPlay, null, null, null);

            Drawable dSet  = GetDrawable(Resource.Drawable.settings);
            Bitmap   bmSet = ((BitmapDrawable)dSet).Bitmap;

            bmSet = Bitmap.CreateScaledBitmap(bmSet, bHeight, bHeight, false);
            dSet  = new BitmapDrawable(this.Resources, bmSet);
            bSettings.SetCompoundDrawablesWithIntrinsicBounds(dSet, null, null, null);

            Drawable dEx  = GetDrawable(Resource.Drawable.exit);
            Bitmap   bmEx = ((BitmapDrawable)dEx).Bitmap;

            bmEx = Bitmap.CreateScaledBitmap(bmEx, bHeight, bHeight, false);
            dEx  = new BitmapDrawable(this.Resources, bmEx);
            bExit.SetCompoundDrawablesWithIntrinsicBounds(dEx, null, null, null);

            switch (settings.colorConfig)
            {
            case Color.COLOR_GREEN:
                bPlay.SetBackgroundResource(Resource.Drawable.backg_button1);
                bSettings.SetBackgroundResource(Resource.Drawable.backg_button1);
                bExit.SetBackgroundResource(Resource.Drawable.backg_button1);
                break;

            case Color.COLOR_RED:
                bPlay.SetBackgroundResource(Resource.Drawable.backg_button2);
                bSettings.SetBackgroundResource(Resource.Drawable.backg_button2);
                bExit.SetBackgroundResource(Resource.Drawable.backg_button2);
                break;

            case Color.COLOR_BLUE:
                bPlay.SetBackgroundResource(Resource.Drawable.backg_button3);
                bSettings.SetBackgroundResource(Resource.Drawable.backg_button3);
                bExit.SetBackgroundResource(Resource.Drawable.backg_button3);
                break;
            }

            Intent bss = new Intent(ApplicationContext, typeof(FXSoundService));

            bss.SetAction(FXSoundService.VolumeSound);
            StartService(bss);
            bss.SetAction(FXSoundService.ButtonSound);

            bPlay.Click += delegate
            {
                StartService(bss);
                var intent = new Intent(this, typeof(PlayActivity));
                StartActivity(intent);
            };

            bSettings.Click += delegate
            {
                StartService(bss);
                Finish();
                var intent = new Intent(this, typeof(SettingsActivity));
                StartActivity(intent);
            };

            bExit.Click += delegate
            {
                StartService(bss);
                Exit();
            };

            Intent ns = new Intent(ApplicationContext, typeof(NotificationService));

            if (settings.notifications)
            {
                StartService(ns);
            }
            else if (!settings.notifications)
            {
                StopService(ns);
            }

            if (!ServiceUtils.IsMyServiceRunning(ApplicationContext, typeof(MusicSoundService).Name))
            {
                Intent mss = new Intent(ApplicationContext, typeof(MusicSoundService));
                mss.SetAction(MusicSoundService.Initialize);
                StartService(mss);
                mss.SetAction(MusicSoundService.MenuTheme);
                StartService(mss);
            }
        }
示例#2
0
        private List <HubConnection> Create(int startCliIndex, int endCliIndex, string url,
                                            string transportTypeName = "Websockets",
                                            string hubProtocol       = "json")
        {
            Util.Log($"transport type: {transportTypeName}");
            var transportType = HttpTransportType.WebSockets;

            switch (transportTypeName)
            {
            case "LongPolling":
                transportType = HttpTransportType.LongPolling;
                break;

            case "ServerSentEvents":
                transportType = HttpTransportType.ServerSentEvents;
                break;

            case "None":
                transportType = HttpTransportType.None;
                break;

            default:
                transportType = HttpTransportType.WebSockets;
                break;
            }
            Util.Log($"Connection string: {url}");
            var serviceUtils = new ServiceUtils(url);

            _tk.State = Stat.Types.State.HubconnCreating;
            var connections = new List <HubConnection>(endCliIndex - startCliIndex);

            for (var i = startCliIndex; i < endCliIndex; i++)
            {
                var serviceUrl = serviceUtils.GetClientUrl();
                var userId     = $"{ServiceUtils.ClientUserIdPrefix}{i}";

                var cookies           = new CookieContainer();
                var httpClientHandler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                    CookieContainer = cookies,
                };
                var hubConnectionBuilder = new HubConnectionBuilder()

                                           /* TODO. Console log is important for finding errors.
                                            * But if every connection enables it, there will be thousands of
                                            * 'Console logger queue processing thread' which degrade the system
                                            * response, and bring issues to counters statistic.
                                            * Temporarily, we disable it. We need to find the best way
                                            * to enable it.
                                            */
                                           //.ConfigureLogging(logging =>
                                           //{
                                           //    logging.AddConsole();
                                           //    logging.SetMinimumLevel(LogLevel.Warning);
                                           //})
                                           .WithUrl(serviceUrl, httpConnectionOptions =>
                {
                    httpConnectionOptions.HttpMessageHandlerFactory = _ => httpClientHandler;
                    httpConnectionOptions.Transports          = transportType;
                    httpConnectionOptions.CloseTimeout        = TimeSpan.FromMinutes(100);
                    httpConnectionOptions.Cookies             = cookies;
                    httpConnectionOptions.AccessTokenProvider = () =>
                    {
                        return(Task.FromResult(serviceUtils.GenerateAccessToken(serviceUrl, userId)));
                    };
                });

                HubConnection connection = null;
                switch (hubProtocol)
                {
                case "json":
                    connection = hubConnectionBuilder.Build();
                    break;

                case "messagepack":
                    connection = hubConnectionBuilder.AddMessagePackProtocol().Build();
                    break;

                default:
                    throw new Exception($"{hubProtocol} is invalid.");
                }

                connection.Closed += e =>
                {
                    if (_tk.State <= Stat.Types.State.SendComplete && _tk.State >= Stat.Types.State.SendReady)
                    {
                        var error = $"Connection closed early: {e}";
                        Util.Log(error);
                    }

                    return(Task.CompletedTask);
                };
                connections.Add(connection);
            }

            _tk.State = Stat.Types.State.HubconnCreated;
            return(connections);
        }
示例#3
0
 public Startup(string options)
 {
     _staticFilePath = options;
     ServiceWatcher.Init(ServiceUtils.GetAllEzeServices());
 }
示例#4
0
        public async void Refresh()
        {
            if (SessionContext.Role == "")
            {
                GotoLogon();
                return;
            }

            // Databind Name
            ServiceUtils utils = new ServiceUtils();

            try
            {
                switch (SessionContext.Role)
                {
                case "Student":
                    // Get the details of the current user (which must be a student)
                    var student = utils.GetStudent(SessionContext.UserName);

                    // Display the name of the student
                    try
                    {
                        LocalStudent localStudent = new LocalStudent();
                        localStudent.Record           = student;
                        SessionContext.CurrentStudent = localStudent;
                        txtName.Text = String.Format("Welcome {0} {1}!", localStudent.FirstName, localStudent.LastName);
                    }
                    catch (DataServiceQueryException ex)
                    {
                        MessageBox.Show(String.Format("Error: {0} - {1}",
                                                      ex.Response.StatusCode.ToString(), ex.Response.Error.Message));
                    }

                    // Display the details of the student
                    GotoStudentProfile();
                    break;

                case "Parent":
                    // Get the details of the current user (which must be a parent)
                    var parent = utils.GetParent(SessionContext.UserName);

                    // Display the name of the parent
                    try
                    {
                        SessionContext.CurrentParent = parent;
                        txtName.Text = String.Format("Welcome {0} {1}!", parent.FirstName, parent.LastName);
                    }
                    catch (DataServiceQueryException ex)
                    {
                        MessageBox.Show(String.Format("Error: {0} - {1}",
                                                      ex.Response.StatusCode.ToString(), ex.Response.Error.Message));
                    }

                    // Find all the students that are children of this parent
                    var students = utils.GetStudentsByParent(SessionContext.UserName);

                    // Display the details for the first child
                    try
                    {
                        foreach (var s in students)
                        {
                            LocalStudent child = new LocalStudent();
                            child.Record = s;

                            SessionContext.CurrentStudent = child;
                            GotoStudentProfile();
                            break;
                        }
                    }
                    catch (DataServiceQueryException ex)
                    {
                        MessageBox.Show(String.Format("Error: {0} - {1}",
                                                      ex.Response.StatusCode.ToString(), ex.Response.Error.Message));
                    }
                    break;

                case "Teacher":
                    // Get the details of the current user (which must be a teacher)
                    var teacher = await utils.GetTeacher(SessionContext.UserName);

                    // Display the details for the teacher
                    try
                    {
                        SessionContext.CurrentTeacher = teacher;
                        txtName.Text = String.Format("Welcome {0} {1}!", teacher.FirstName, teacher.LastName);

                        // Display the students in the class taught by this teacher
                        GotoStudentsPage();
                    }
                    catch (DataServiceQueryException ex)
                    {
                        MessageBox.Show(String.Format("Error: {0} - {1}",
                                                      ex.Response.StatusCode.ToString(), ex.Response.Error.Message));
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error fetching details", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
示例#5
0
 public static void Save()
 {
     File.WriteAllText(_filePath, JsonConvert.SerializeObject(Profiles));
     ServiceWatcher.Init(ServiceUtils.GetAllEzeServices());
 }
示例#6
0
        public Stream DownloadImage(string authenticationCookie, string sopInstanceUID, int frame, int bitsPerPixel, int qualityFactor, int width, int height, string annotationFileName, double xDpi, double yDpi, string userData)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            if (frame <= 0)
            {
                frame = 1;
            }

            if (qualityFactor < 2)
            {
                qualityFactor = 2;
            }

            // string dir = HostingEnvironment.ApplicationPhysicalPath;
            string dir = Path.GetTempPath();

            if (null == dir)
            {
                dir = string.Empty;
            }
            string outDir         = Path.Combine(dir, "Temp");
            string filePath       = null;
            string annotationData = null;

            if (!String.IsNullOrEmpty(annotationFileName))
            {
                filePath = Path.Combine(outDir, annotationFileName);
            }

            if (filePath != null && File.Exists(filePath))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                annotationData = doc.InnerXml;

                File.Delete(filePath);
            }

            if (null != WebOperationContext.Current)
            {
                WebOperationContext.Current.OutgoingResponse.ContentType = SupportedMimeTypes.JPG;
                WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", string.Format("attachment; filename={0}.jpg", sopInstanceUID.ToString()));
            }

            if (width == 0 && height == 0)
            {
                var captureSize = ConfigurationManager.AppSettings.Get("MaxCaptureSize");
                if (!string.IsNullOrEmpty(captureSize))
                {
                    int.TryParse(captureSize, out width);
                    int.TryParse(captureSize, out height);
                }
            }

            Stream stream = AddinsFactory.CreateObjectRetrieveAddin().DownloadImage(sopInstanceUID, frame, SupportedMimeTypes.JPG, bitsPerPixel, qualityFactor, width, height, annotationData, xDpi, yDpi, userData);

            if (null != WebOperationContext.Current)
            {
                WebOperationContext.Current.OutgoingResponse.ContentLength = stream.Length;
            }

            return(stream);
        }
        private protected override void RunAccessCheck(IEnumerable <TokenEntry> tokens)
        {
            if (CheckScmAccess)
            {
                SecurityDescriptor sd            = ServiceUtils.GetScmSecurityDescriptor();
                GenericMapping     scm_mapping   = ServiceUtils.GetScmGenericMapping();
                AccessMask         access_rights = scm_mapping.MapMask(ScmAccess);
                foreach (TokenEntry token in tokens)
                {
                    AccessMask granted_access = NtSecurity.GetMaximumAccess(sd, token.Token, scm_mapping);
                    if (IsAccessGranted(granted_access, access_rights))
                    {
                        WriteAccessCheckResult("SCM", "SCM", granted_access, scm_mapping, sd,
                                               typeof(ServiceControlManagerAccessRights), false, token.Information);
                    }
                }
            }
            else
            {
                IEnumerable <Win32Service>      services    = GetServices();
                InternalGetAccessibleFileCmdlet file_cmdlet = null;
                HashSet <string> checked_files = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                if (CheckFiles)
                {
                    file_cmdlet = new InternalGetAccessibleFileCmdlet(this)
                    {
                        FormatWin32Path    = true,
                        Access             = FileAccessRights.WriteData | FileAccessRights.WriteDac | FileAccessRights.WriteOwner | FileAccessRights.AppendData | FileAccessRights.Delete,
                        DirectoryAccess    = FileDirectoryAccessRights.AddFile | FileDirectoryAccessRights.WriteDac | FileDirectoryAccessRights.WriteOwner,
                        AllowPartialAccess = true
                    };
                }

                GenericMapping service_mapping = ServiceUtils.GetServiceGenericMapping();
                AccessMask     access_rights   = service_mapping.MapMask(Access);

                foreach (var service in services.Where(s => s?.SecurityDescriptor != null))
                {
                    foreach (TokenEntry token in tokens)
                    {
                        AccessMask granted_access = NtSecurity.GetMaximumAccess(service.SecurityDescriptor,
                                                                                token.Token, service_mapping);
                        ServiceAccessRights trigger_access = GetTriggerAccess(service, token.Token);
                        if (IsAccessGranted(granted_access, access_rights))
                        {
                            WriteObject(new ServiceAccessCheckResult(service.Name, granted_access | trigger_access,
                                                                     service.SecurityDescriptor, token.Information, trigger_access,
                                                                     granted_access.ToSpecificAccess <ServiceAccessRights>(), service));
                        }
                    }
                    if (CheckFiles)
                    {
                        if (!string.IsNullOrWhiteSpace(service.ImagePath) &&
                            File.Exists(service.ImagePath) &&
                            checked_files.Add(service.ImagePath))
                        {
                            file_cmdlet.RunAccessCheckPathInternal(tokens, service.ImagePath);
                            file_cmdlet.RunAccessCheckPathInternal(tokens, Path.GetDirectoryName(service.ImagePath));
                        }

                        if (!string.IsNullOrWhiteSpace(service.ServiceDll) &&
                            File.Exists(service.ServiceDll) &&
                            checked_files.Add(service.ServiceDll))
                        {
                            file_cmdlet.RunAccessCheckPathInternal(tokens, service.ServiceDll);
                            file_cmdlet.RunAccessCheckPathInternal(tokens, Path.GetDirectoryName(service.ServiceDll));
                        }
                    }
                }
            }
        }
示例#8
0
 /// <summary>
 /// Process record.
 /// </summary>
 protected override void ProcessRecord()
 {
     ServiceUtils.ChangeServiceConfig(MachineName, Name,
                                      DisplayName, Type, Start, ErrorControl,
                                      Path, TagId, LoadOrderGroup, Dependencies, UserName, Password);
 }
示例#9
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            _logger.Info("Zombie is powering up...");
            var connected = false;

            try
            {
                var binding  = ServiceUtils.CreateClientBinding(ServiceUtils.FreeTcpPort());
                var endpoint = new EndpointAddress(new Uri("http://localhost:8000/ZombieService/Service.svc"));
                var context  = new InstanceContext(new ZombieServiceCallback());
                Client = new ZombieServiceClient(context, binding, endpoint);

                GuiUpdateCallbackHandler callbackHandler = OnGuiUpdate;
                GuiUpdateCallbackEvent += callbackHandler;

                Client.Open();
                Client.Subscribe();

                // (Konrad) Get latest settings from ZombieService
                Settings = Client.GetSettings();

                connected = true;
                _logger.Info("Successfully connected to Zombie Service at http://localhost:8000/ZombieService/Service.svc");
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex.Message);
            }

            // Register AUMID and COM server (for Desktop Bridge apps, this no-ops)
            DesktopNotificationManagerCompat.RegisterAumidAndComServer <MyNotificationActivator>("HOK.Zombie");

            // Register COM server and activator type
            DesktopNotificationManagerCompat.RegisterActivator <MyNotificationActivator>();

            // (Konrad) Create the startup window
            var m    = new ZombieModel(Settings);
            var vm   = new ZombieViewModel(m);
            var view = new ZombieView
            {
                DataContext = vm
            };

            var show = true;

            if (e.Args.Length == 1)
            {
                show = e.Args[0] == "show";
            }

            vm.Startup(view, show);

            Messenger.Default.Send(connected
                ? new UpdateStatus {
                Message = "Successfully connected to ZombieService!"
            }
                : new UpdateStatus {
                Message = "Connection to ZombieService failed!"
            });
            _logger.Info("Zombie is up and running!");
        }
 protected virtual void RegisterService(byte[] serviceSignature, byte[] methodSignature, ServiceMethod serviceMethod) =>
 Services.Add(ServiceUtils.CombineSignatures(serviceSignature, methodSignature), serviceMethod);
示例#11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeviceService"/> class.
 /// </summary>
 public DeviceService()
     : this(new DeviceRepo(ServiceUtils.GetConnection("HelpDesk")))
 {
 }
示例#12
0
        public string VerifyConnection(string authenticationCookie, PACSConnection server, ClientConnection client, ExtraOptions extraOptions)
        {
            ServiceUtils.Authenticate(authenticationCookie);

            return(AddinsFactory.CreatePacsQueryAddin().VerifyConnection(server, client));
        }
示例#13
0
        public InstanceData[] FindInstances(string authenticationCookie, DataContracts.PACSConnection server, DataContracts.ClientConnection client, DataContracts.QueryOptions options, DataContracts.ExtraOptions extraOptions)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanQueryPACS);

            return(AddinsFactory.CreatePacsQueryAddin( ).FindInstances(server, client, options));
        }
示例#14
0
        public ServiceMetadata(Type serviceType, string serviceName, string serviceNamespace, string codeGeneratorVersion)
        {
            this.RequestTypes     = new HashSet <Type>();
            this.ResponseTypes    = new HashSet <Type>();
            this.OperationNameMap = new Dictionary <string, Operation>();
            this.Routes           = new ServiceRoutes();
            this.ServiceTypes     = new List <Type>()
            {
                serviceType
            };
            this.ServiceName            = string.IsNullOrWhiteSpace(serviceName) ? AnonymousServiceName : serviceName;
            this.ServiceNamespace       = string.IsNullOrWhiteSpace(serviceNamespace) ? "http://soa.ant.com/anonymous" : serviceNamespace;
            this.FullServiceName        = ServiceName + "{" + ServiceNamespace + "}";
            this.RefinedFullServiceName = ServiceUtils.RefineServiceName(ServiceNamespace, ServiceName);
            this.ServiceMetricPrefix    = "soa.service";
            this.AntServiceStackVersion = typeof(ServiceMetadata).Assembly.GetName().Version.ToString();
            this.AntCodeGenVersion      = codeGeneratorVersion;

            //判断appseting里面是否设置了特殊的访问前缀的 key
            //如果没有就默认为空的
            string servicePathSettingValue = ConfigUtils.GetNullableAppSetting(GetServiceSpecificSettingKey(DefaultServicePathMapSettingKey));

            this.IsDefaultService = string.IsNullOrWhiteSpace(servicePathSettingValue);
            if (this.IsDefaultService)
            {
                this.ServicePath = DefaultServicePath;
            }
            else
            {
                string servicePath = servicePathSettingValue.Trim().ToLower();
                if (!Regex.IsMatch(servicePath, ServicePathPattern))
                {
                    throw new Exception("ServicePathMap setting is invalid: " + servicePathSettingValue);
                }

                this.ServicePath = servicePath;
            }

            //判断appseting里面是否设置了方法执行的timeout
            string operationTimeoutMapSettingKey = GetServiceSpecificSettingKey(DefaultOperationTimeoutMapSettingKey);
            var    opTimeoutMapSetting           = ConfigUtils.GetNullableAppSetting(operationTimeoutMapSettingKey);

            this.OperationTimeoutMap = ConfigUtils.GetDictionaryFromAppSettingValue(opTimeoutMapSetting);
            foreach (var item in DefaultOperationTimeoutMap)
            {
                if (!this.OperationTimeoutMap.ContainsKey(item.Key))
                {
                    this.OperationTimeoutMap[item.Key] = item.Value;
                }
            }

            #region 电容器开关

            string circuitBreakerForceClosedSettingKey = GetServiceSpecificSettingKey(DefaultCircuitBreakerForceClosedSettingKey);
            bool   circuitBreakerForceClosed;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(circuitBreakerForceClosedSettingKey), out circuitBreakerForceClosed))
            {
                circuitBreakerForceClosed = DefaultCircuitBreakerForceClosed;
            }
            this.CircuitBreakerForceClosed = circuitBreakerForceClosed;

            #endregion

            string logErrorWithRequestInfoSettingKey = GetServiceSpecificSettingKey(DefaultLogErrorWithRequestInfoSettingKey);
            bool   logErrorWithRequestInfo;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(logErrorWithRequestInfoSettingKey), out logErrorWithRequestInfo))
            {
                logErrorWithRequestInfo = DefaultLogErrorWithRequestInfo;
            }
            this.LogErrorWithRequestInfo = logErrorWithRequestInfo;

            string logH5HeadExtensionDataSettingKey = GetServiceSpecificSettingKey(DefaultLogH5HeadExtensionDataSettingKey);
            bool   logH5HeadExtensionData;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(logH5HeadExtensionDataSettingKey), out logH5HeadExtensionData))
            {
                logH5HeadExtensionData = DefaultLogH5HeadExtensionData;
            }
            this.LogH5HeadExtensionData = logH5HeadExtensionData;

            string logCommonRequestInfoSettingKey = GetServiceSpecificSettingKey(DefaultLogCommonRequestInfoSettingKey);
            bool   logCommonRequestInfo;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(logCommonRequestInfoSettingKey), out logCommonRequestInfo))
            {
                logCommonRequestInfo = DefaultLogCommonRequestInfo;
            }
            this.LogCommonRequestInfo = logCommonRequestInfo;

            string useChunkedTransferEncodingSettingKey = GetServiceSpecificSettingKey(DefaultUseChunkedTransferEncodingSettingKey);
            bool   useChunkedTransferEncoding;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(useChunkedTransferEncodingSettingKey), out useChunkedTransferEncoding))
            {
                useChunkedTransferEncoding = DefaultUseChunkedTransferEncoding;
            }
            this.UseChunkedTransferEncoding = useChunkedTransferEncoding;

            string serviceTestSubEnvSettingKey = GetServiceSpecificSettingKey(SERVICE_REGISTRY_ENV_KEY);
            ServiceTestSubEnv = ConfigUtils.GetNullableAppSetting(serviceTestSubEnvSettingKey);
            if (string.IsNullOrWhiteSpace(ServiceTestSubEnv))
            {
                ServiceTestSubEnv = DefaultServiceTestSubEnv;
            }
            else
            {
                ServiceTestSubEnv = ServiceTestSubEnv.Trim().ToLower();
            }



            #region 对于每个单个IP的连接数限制
            //是否打开开关的配置
            string checkConnectionMaxRequestCountSettingKey = GetServiceSpecificSettingKey(DefaultCheckConnectionMaxRequestCountSettingKey);
            bool   checkConnectionMaxRequestCount;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(checkConnectionMaxRequestCountSettingKey), out checkConnectionMaxRequestCount))
            {
                checkConnectionMaxRequestCount = DefaultCheckConnectionMaxRequestCount;//默认false
            }
            this.CheckConnectionMaxRequestCount = checkConnectionMaxRequestCount;


            string connectionMaxRequestCountSettingKey = GetServiceSpecificSettingKey(DefaultConnectionMaxRequestCountSettingKey);
            int    connectionMaxRequestCount;
            if (!int.TryParse(ConfigUtils.GetNullableAppSetting(connectionMaxRequestCountSettingKey), out connectionMaxRequestCount))
            {
                connectionMaxRequestCount = DefaultConnectionMaxRequestCount; // 如果没有配置就默认 2000
            }
            else if (connectionMaxRequestCount < MinConnectionMaxRequestCount)
            {
                connectionMaxRequestCount = MinConnectionMaxRequestCount;//如果配置了低于500 就取500 (最低不能低于500)
            }
            this.ConnectionMaxRequestCount = connectionMaxRequestCount;

            #endregion

            string deserializeRequestUseMemoryStreamSettingKey = GetServiceSpecificSettingKey(DefaultDeserializeRequestUseMemoryStreamSettingKey);
            bool   deserializeRequestUseMemoryStream;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(deserializeRequestUseMemoryStreamSettingKey), out deserializeRequestUseMemoryStream))
            {
                deserializeRequestUseMemoryStream = DefaultDeserializeRequestUseMemoryStream;
            }
            this.DeserializeRequestUseMemoryStream = deserializeRequestUseMemoryStream;

            string metadataFeatureEnabledSettingKey = GetServiceSpecificSettingKey(DefaultEnableMetadataFeatureConfigKey);
            bool   metadataFeatureEnabled;
            if (!bool.TryParse(ConfigUtils.GetNullableAppSetting(metadataFeatureEnabledSettingKey), out metadataFeatureEnabled))
            {
                metadataFeatureEnabled = DefaultMetadataFeatureEnabled;
            }
            this.MetadataFeatureEnabled = metadataFeatureEnabled;

            MessageSensitivityAttribute sensitivityAttribute = null;
            if (serviceType != null)
            {
                sensitivityAttribute = serviceType.GetCustomAttributes(true).OfType <MessageSensitivityAttribute>().FirstOrDefault();
            }
            this.ServiceMessageLogConfig = AttributeToConfig(sensitivityAttribute);
        }
示例#15
0
        public WCFHangingProtocol GetHangingProtocol(string authenticationCookie, string sopInstanceUID, string userData)
        {
            var userName = ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetHangingProtocol(userName, sopInstanceUID, userData));
        }
示例#16
0
        public string UploadAnnotations(string authenticationCookie, XmlElement data)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            if (data == null)
            {
                return(null);
            }

            // Check if the temp folder exists
            // string dir = HostingEnvironment.ApplicationPhysicalPath;
            string dir = Path.GetTempPath();

            if (null == dir)
            {
                dir = string.Empty;
            }
            string outDir = Path.Combine(dir, "Temp");

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

            // Check if we have old files in the directory, delete them
            DateTime now = DateTime.Now;

            string[] files = Directory.GetFiles(outDir, "*.xml");
            foreach (string file in files)
            {
                DateTime fileTime = File.GetCreationTime(file);
                if (fileTime > now.AddHours(24))
                {
                    // Delete it
                    try
                    {
                        File.Delete(file);
                    }
                    catch { }
                }
            }

            // Create the new file
            string fileName = Guid.NewGuid().ToString().Replace("-", "") + ".xml";
            string filePath = Path.Combine(outDir, fileName);

            // Save the data
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent             = true;
            settings.OmitXmlDeclaration = false;
            settings.Encoding           = Encoding.UTF8;

            using (XmlWriter writer = XmlWriter.Create(filePath, settings))
            {
                writer.WriteStartDocument();
                data.WriteTo(writer);
                writer.WriteEndDocument();
            }

            return(fileName);
        }
示例#17
0
        public List <DisplaySetView> GetHangingProtocolInstances(string authenticationCookie, string hangingProtocolSOP, string patientID, string studyInstanceUID, string studyDateMostRecent, string userData)
        {
            var userName = ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetHangingProtocolInstances(userName, hangingProtocolSOP, patientID, studyInstanceUID, studyDateMostRecent, userData));
        }
示例#18
0
        /// <summary>
        /// Gets the raw DICOM object for an object
        /// </summary>
        /// <param name="authenticationCookie">Cookie</param>
        /// <param name="uid">UIDs. Only SOPInstanceUID is used</param>
        /// <param name="options">Query options</param>
        /// <param name="extraOptions">Extra options</param>
        /// <returns>The DICOM as stream</returns>
        /// <remarks>
        /// <para>RoleName:CanRetrieve</para>
        /// </remarks>
        public Stream GetDicom(string authenticationCookie, ObjectUID uid, GetDicomOptions options, ExtraOptions extraOptions)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetDicom(uid, options));
        }
示例#19
0
        public MainPage()
        {
            InitializeComponent();

            Images = new ObservableCollection <PhotoContainer>();           // {new PhotoContainer() { Title = "initial item" }};

            BindingContext = this;

            var toolbarItem = new ToolbarItem
            {
                Text = "Exit"
            };

            toolbarItem.Clicked += OnLogoutButtonClicked;
            ToolbarItems.Add(toolbarItem);


            var submitItem = new ToolbarItem
            {
                Text = "Submit"
            };

            submitItem.Clicked += OnSubmitButtonClicked;
            ToolbarItems.Add(submitItem);


            var signatureMenuItem = new ToolbarItem
            {
                Text = "Sign"
            };

            signatureMenuItem.Clicked += OnSignButtonClicked;
            ToolbarItems.Add(signatureMenuItem);

            Title = "Questionnaire";

            async void OnLogoutButtonClicked(object sender, EventArgs e)
            {
                App.IsUserLoggedIn = false;
                Navigation.InsertPageBefore(new LoginPage(), this);
                await Navigation.PopAsync();

                var closer = DependencyService.Get <ICloseApplication>();

                closer?.Close();
            }

            async void OnSignButtonClicked(object sender, EventArgs e)
            {
                await Navigation.PushModalAsync(new SignaturePage());
            }

            async void OnSubmitButtonClicked(object sender, EventArgs e)
            {
                AnswerService.SendAnswers();
            }

            CameraButton.Clicked += CameraButton_Clicked;

            if (App.IsUserLoggedIn && App.User != null)
            {
                var client = ServiceUtils.GetHttpClient();

                QuestionnaireService httpService1 = RestService.For <QuestionnaireService>(client);
                Task <JObject>       questions    = httpService1.GetQuestions(App.User.id, App.User.quUserSession);
                questions.Wait();
                System.Console.WriteLine(questions.Result.ToString());
                NativeListView.Items = DataSource.GetList(questions.Result);
            }
        }
示例#20
0
        /// <summary>
        /// this is the main function in the class. It returns the DICOM image data wrapped inside a PNG image
        /// </summary>
        /// <param name="authenticationCookie"></param>
        /// <param name="studyInstanceUID"></param>
        /// <param name="seriesInstanceUID"></param>
        /// <param name="sopInstanceUID"></param>
        /// <param name="frame"></param>
        /// <param name="userData"></param>
        /// <returns></returns>
        public Stream GetDicomImageDataAsPNG(string authenticationCookie, string studyInstanceUID, string seriesInstanceUID, string sopInstanceUID, int frame, string userData)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            //must get the encoding accepted by the browser before encoding it. if browser doesn't support some encoding then do not encode
            string acceptEncoding = "Accept-Encoding";
            string encoding       = WebOperationContext.Current.IncomingRequest.Headers[acceptEncoding];


            HttpStatusCode statusCode        = HttpStatusCode.OK;
            string         statusDescription = "";
            Stream         outStream         = null;
            Exception      error             = null;

            try
            {
                if (string.IsNullOrEmpty(sopInstanceUID))
                {
                    statusCode        = System.Net.HttpStatusCode.BadRequest;
                    statusDescription = "Invalid SOPInstanceUID";
                }

                if (frame <= 0)
                {
                    frame = 1;
                }

                if (statusCode == HttpStatusCode.OK)
                {
                    ObjectUID uid = new ObjectUID();
                    uid.StudyInstanceUID  = studyInstanceUID;
                    uid.SeriesInstanceUID = seriesInstanceUID;
                    uid.SOPInstanceUID    = sopInstanceUID;

                    //returns the raw image data as PNG
                    byte[] data = AddinsFactory.CreateObjectRetrieveAddin().GetBinaryDicomImageDataAsPNG(uid, frame);

                    if (null != data)
                    {
                        outStream = new MemoryStream(data);
                    }

                    if (null != outStream && outStream.Length > 0)
                    {
                        //add the right content type so the browser won't try to mess with the data
                        WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
                    }
                    else
                    {
                        statusCode        = System.Net.HttpStatusCode.NotFound;
                        statusDescription = "No data was found";

                        outStream = null;
                    }
                }

                return(outStream);
            }
            catch (Exception ex)
            {
                statusCode        = System.Net.HttpStatusCode.InternalServerError;
                statusDescription = ex.Message;
                error             = ex;
                return(null);
            }
            finally
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode        = statusCode;
                WebOperationContext.Current.OutgoingResponse.StatusDescription = statusDescription;

                if (error != null || statusCode != HttpStatusCode.OK)
                {
                    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";


                    if (error == null)
                    {
                        throw new ApplicationException(statusDescription);
                    }
                    else
                    {
                        throw error;
                    }
                }
            }
        }
示例#21
0
 private static void Uninstall()
 {
     ServiceUtils.Uninstall(IntegrityCheckerService.ServiceNameConst);
 }
示例#22
0
        public Layout GetSeriesLayout(string authenticationCookie, string seriesInstanceUID, string userData)
        {
            var userName = ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetSeriesLayout(userName, seriesInstanceUID, new Lazy <IStoreAddin>(() => AddinsFactory.CreateStoreAddin()), userData));
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            var methodName       = this.txbMethod.Text;
            var triggerName      = this.txbTrigger.Text;
            var jobName          = this.txbJob.Text;
            var url              = this.txbAddress.Text;
            var method           = this.comboBoxMethod.Text;
            var parameters       = this.txbParameters.Text;
            var contentType      = this.cmbContentType.Text;
            var cron             = this.txbCron.Text;
            var isAuthentication = this.cbIsOData.Checked;
            var userName         = this.txbUserName.Text;
            var password         = this.txbPassword.Text;
            var description      = this.txbDescription.Text;
            var groupName        = this.txbGroupName.Text;

            if (string.IsNullOrEmpty(methodName))
            {
                MessageBoxEx.Show(this, "Method name is required and unique", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(triggerName))
            {
                MessageBoxEx.Show(this, "Trigger name is required and unique", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(jobName))
            {
                MessageBoxEx.Show(this, "JOB identification is required and unique!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(url))
            {
                MessageBoxEx.Show(this, "URL address is required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(method))
            {
                MessageBoxEx.Show(this, "Method is Required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(groupName))
            {
                MessageBoxEx.Show(this, "Group name is Required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(contentType))
            {
                MessageBoxEx.Show(this, "Content-Type is required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(cron))
            {
                MessageBoxEx.Show(this, "Cron expression is required!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!Utils.IsValidExpression(cron))
            {
                MessageBoxEx.Show(this, "Cron expression is not valid!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (isAuthentication)
            {
                if (string.IsNullOrEmpty(userName))
                {
                    MessageBoxEx.Show(this, "Username is required when authentication is selected!", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrEmpty(password))
                {
                    MessageBoxEx.Show(this, "Password is required when authentication is selected", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (!rbWebService.Checked && !rbRestful.Checked)
            {
                MessageBoxEx.Show(this, "Webservice or restful is required", "Remind Infomation", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var ruleConfig = new RuleConfig();

            ruleConfig.ServiceName      = methodName;
            ruleConfig.Cron             = cron;
            ruleConfig.Description      = description;
            ruleConfig.TriggerName      = triggerName;
            ruleConfig.JobName          = jobName;
            ruleConfig.Method           = method;
            ruleConfig.PostBody         = parameters;
            ruleConfig.ContentType      = contentType;
            ruleConfig.IsAuthentication = isAuthentication ? 1 : 0;
            ruleConfig.UserName         = userName;
            ruleConfig.Password         = password;
            ruleConfig.GroupName        = groupName;
            ruleConfig.Address          = url;
            ruleConfig.Status           = (int)BasicStatus.效;
            ruleConfig.RunStatus        = (int)RunStatus.停用;
            ruleConfig.IsWebService     = rbWebService.Checked ? (int)YesOrNo.是 : (int)YesOrNo.否;
            this.IsLoading = true;
            var msg = ServiceUtils.InsertRule(ruleConfig);

            MessageBoxEx.Show(this, msg.Message);
            this.IsLoading = true;
        }
示例#24
0
        public StudyLayout GetStudyLayout(string authenticationCookie, string studyInstanceUID, string userData)
        {
            var userName = ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetStudyLayout(userName, studyInstanceUID, userData));
        }
示例#25
0
 public void Basics()
 {
     _tm      = new TestModels();
     _service = new ServiceUtils(_tm.RunnerRepositoryFake);
 }
示例#26
0
        public int[] GetMinMaxValues(string authenticationCookie, string sopInstanceUID, int frameNumber, string userData)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetMinMaxValues(sopInstanceUID, frameNumber));
        }
 private ServiceInformation GetServiceInformation()
 {
     return(ServiceUtils.GetServiceInformation(null, Service,
                                               false).GetResultOrDefault(new ServiceInformation(null, Service)));
 }
示例#28
0
        public List <StackItem> GetSeriesStacks(string authenticationCookie, string seriesInstanceUID, string userData)
        {
            ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanRetrieve);

            return(AddinsFactory.CreateObjectRetrieveAddin().GetSeriesStacks(seriesInstanceUID));
        }
示例#29
0
        private void ReadAppSettings()
        {
            StorageServerServicePath = ServiceUtils.MapConfigPath(ConfigurationManager.AppSettings.Get("storageServerServicePath"));

            {
                ClientConnection = new PACSConnection();

                //the client AE/IP/port used for connecting to remote PACS for query
                ClientConnection.AETitle = ConfigurationManager.AppSettings.Get("ClientAe");
                if (string.IsNullOrEmpty(ClientConnection.AETitle))
                {
                    ClientConnection.AETitle = "LTCLIENT19";
                }
                ClientConnection.IPAddress = ConfigurationManager.AppSettings.Get("ClientIP");
                if (string.IsNullOrEmpty(ClientConnection.IPAddress))
                {
                    ClientConnection.IPAddress = ServiceUtils.GetLocalIPAddressesV4();
                }

                ClientConnection.Port = ParseTools.Int(ConfigurationManager.AppSettings.Get("ClientPort"), ServiceUtils.GetFreeIPPort());
            }

            {
                StorageServerConnection           = new PACSConnection();
                StorageServerConnection.AETitle   = ConfigurationManager.AppSettings.Get("ServerAe");
                StorageServerConnection.IPAddress = ConfigurationManager.AppSettings.Get("ServerIP");
                StorageServerConnection.Port      = ParseTools.Int(ConfigurationManager.AppSettings.Get("ServerPort"), -1);

                //read default storage server dicom connection settings
                if (!string.IsNullOrEmpty(StorageServerServicePath) &&
                    (string.IsNullOrEmpty(StorageServerConnection.AETitle) ||
                     string.IsNullOrEmpty(StorageServerConnection.IPAddress) ||
                     StorageServerConnection.Port <= 0))
                {
                    try
                    {
                        var settingsFile = Path.Combine(StorageServerServicePath, "settings.xml");
                        var doc          = XDocument.Load(settingsFile);
                        {
                            StorageServerConnection.Port      = ParseTools.Int(doc.Descendants("Port").First().Value, -1);
                            StorageServerConnection.IPAddress = doc.Descendants("IpAddress").First().Value;
                            StorageServerConnection.AETitle   = doc.Descendants("AETitle").First().Value;
                        }
                    }
                    catch
                    {
                    }
                }

                if (string.IsNullOrEmpty(StorageServerConnection.AETitle))
                {
                    StorageServerConnection.AETitle = "LTSTORAGESERVER";
                }
            }
        }
示例#30
0
        public INakedObjectAdapter GetServiceAdapter(object service)
        {
            IOid oid = GetOidForService(ServiceUtils.GetId(service), service.GetType().FullName);

            return(AdapterForService(oid, service));
        }