public void Execute()
        {
            SvcI = SvcBase.Service;

            config = GetK2CRMConfig(SvcI.ServiceConfiguration.ServiceAuthentication.UserName, SvcI.ServiceConfiguration.ServiceAuthentication.Password, GetConfigPropertyValue("RESTServiceURL"));

            ServiceObject so = SvcI.ServiceObjects[0];
            string methodName = so.Methods[0].Name;
            switch (methodName.ToLower())
            {
                case "changeowner":
                    ChangeOwner(ref so);
                    break;
                case "setstatestatus":
                    SetStateStatus(ref so);
                    break;
                case "getentities":
                    GetEntities(ref so);
                    break;
                case "bulkactiontasks":
                    BulkActionTasks(ref so);
                    break;
                case "createtask":
                    CreateTask(ref so);
                    break;
                case "getcrmuser":
                    GetCRMUser(ref so);
                    break;
            }
        }
        public DynamicServiceObjectHelper(ServiceAssemblyBase svcBase)
        {
            //when an instance of this class is created set the internal variables to 
            //the base class
            SvcBase = svcBase;
            SvcI = svcBase.Service;

        }
Example #3
0
        void AttachToInstance(ServiceInstance instance)
        {
            Instance = instance;
            Instance.StateChanged          += new EventHandler <ServiceStateChangedEventArgs>(Instance_StateChanged);
            Instance.OutcomeReported       += new EventHandler(Instance_OutcomeReported);
            Instance.ProgressReported      += new EventHandler(Instance_ProgressReported);
            Instance.ChildServiceRequested += new EventHandler <ServiceRequestedEventArgs>(Instance_ChildServiceRequested);

            NotifyPropertyChanged("Status");
            NotifyPropertyChanged("Progress");
        }
        void UpdateServiceProperties()
        {
            ServiceInstance.Reload();

            NotifyOfPropertyChange("Status");
            NotifyOfPropertyChange("AllowStop");
            NotifyOfPropertyChange("AllowStart");
            NotifyOfPropertyChange("IsRunning");
            NotifyOfPropertyChange("IsStopped");
            NotifyOfPropertyChange("InMaintenanceMode");
        }
Example #5
0
 private IService GetInstance(ServiceInstance service, List <IService> instanceList)
 {
     for (var i = 0; i < instanceList.Count; i++)
     {
         if (instanceList[i].ServiceId == service.ServiceID)
         {
             return(instanceList[i]);
         }
     }
     return(null);
 }
        public static string DebugInfo(this ServiceInstance instance)
        {
            if (instance == null || instance.Configuration == null)
            {
                return(String.Empty);
            }

            return(String.Format("Service={0}, profile={1}, singnature={2}",
                                 instance.Configuration.ServiceName,
                                 instance.Configuration.Profile != null ? instance.Configuration.Profile.Name : String.Empty,
                                 InstanceRequestCollection.GetSignature(instance)));
        }
        public static ServiceInstance GetServiceInstance(ServiceInstanceSettings serviceInstanceSettings)
        {
            serviceInstanceSettings.ThrowIfNull("serviceInstanceSettings");

            var connection = WrapperFactory.Instance.GetSmartObjectManagementServerWrapper(null);

            using (connection.BaseAPIServer?.Connection)
            {
                var serviceInstance = ServiceInstance.Create(connection.GetServiceInstance(serviceInstanceSettings.Guid, ServiceExplorerLevel.ServiceObject));
                return(serviceInstance);
            }
        }
Example #8
0
        public void UpdateCustomer_NullEntity_StatusFalse()
        {
            var expextedResult = new CustomerServiceResponse
            {
                Status  = false,
                Message = "Customer entity cannot be null"
            };

            var actualResult = ServiceInstance.UpdateCustomer(null);

            Assert.AreEqual(expextedResult.Status, actualResult.Status);
            Assert.AreEqual(expextedResult.Message, actualResult.Message);
        }
        public ProgressState GetProgress(int sessionID)
        {
            int           totalExecutionSteps;
            ProgressState progressState = new ProgressState();

            try
            {
                ServiceInstance serviceExecutorsContainer = ExecuterSteps[sessionID][0].ParentInstance;
                if (serviceExecutorsContainer.Outcome != ServiceOutcome.Unspecified)
                {
                    return(new ProgressState()
                    {
                        OverAllProgess = 1f
                    });
                }
                //Get the count of executors step from configuration
                totalExecutionSteps = serviceExecutorsContainer.Configuration.ExecutionSteps.Count;
                foreach (ServiceInstance executionStep in ExecuterSteps[sessionID])
                {
                    if (executionStep.State != ServiceState.Ended)
                    {
                        if (progressState.CurrentRuningStepsState == null)
                        {
                            progressState.CurrentRuningStepsState = new Dictionary <string, float>();
                        }
                        progressState.CurrentRuningStepsState.Add(executionStep.Configuration.Name, executionStep.Progress);
                    }
                    else
                    {
                        if (progressState.CurrentRuningStepsState == null)
                        {
                            progressState.CurrentRuningStepsState = new Dictionary <string, float>();
                        }
                        progressState.CurrentRuningStepsState.Add(executionStep.Configuration.Name, (float)1);
                    }
                }
                //Find overall progress
                float existingStepsProgress = 0;
                foreach (float progress in progressState.CurrentRuningStepsState.Values)
                {
                    existingStepsProgress += progress;
                }
                progressState.OverAllProgess = existingStepsProgress / totalExecutionSteps;
                progressState.text           = GetStateInfo(sessionID);
            }
            catch (Exception ex)
            {
                throw new Exception("Problem when trying to locate the service by session");
            }
            return(progressState);
        }
        public async void LoadCharacteristics()
        {
            IEnumerable <ICharacteristic> characteristics = await ServiceInstance.GetCharacteristicsAsync();

            foreach (ICharacteristic characteristic in characteristics)
            {
                if (characteristic.Id == MagnetometerCharacteristicId)
                {
                    characteristic.ValueUpdated += (sender, e) =>
                    {
                        byte[] rawBytes = e.Characteristic.Value;
                        if (rawBytes.Length != 6)
                        {
                            throw new InvalidDataException("Magnetometer characteristic should have 6 bytes");
                        }

                        short rawX = ConversionHelpers.ByteArrayToShort16BitLittleEndian(new byte[] { rawBytes[0], rawBytes[1] });
                        short rawY = ConversionHelpers.ByteArrayToShort16BitLittleEndian(new byte[] { rawBytes[2], rawBytes[3] });
                        short rawZ = ConversionHelpers.ByteArrayToShort16BitLittleEndian(new byte[] { rawBytes[4], rawBytes[5] });

                        X = ((double)rawX) / 1000.0;
                        Y = ((double)rawY) / 1000.0;
                        Z = ((double)rawZ) / 1000.0;
                    };
                    MarkCharacteristicForUpdate(characteristic);
                }
                else if (characteristic.Id == MagnetometerBearingCharacteristicId)
                {
                    characteristic.ValueUpdated += (sender, e) =>
                    {
                        byte[] rawBytes = e.Characteristic.Value;
                        if (rawBytes.Length != 2)
                        {
                            throw new InvalidDataException("Magnetometer Bearing characteristic should have 2 bytes");
                        }

                        MagnetometerBearing = ConversionHelpers.ByteArrayToShort16BitLittleEndian(rawBytes);
                    };
                    MarkCharacteristicForUpdate(characteristic);
                }
                else if (characteristic.Id == MagnetometerPeriodCharacteristicId)
                {
                    byte[] val = await characteristic.ReadAsync();

                    int period = ConversionHelpers.ByteArrayToShort16BitLittleEndian(val);
                    MagnetometerPeriod = period;
                }
            }

            StartUpdates();
        }
Example #11
0
        public static ProductInstance GetRandomDerived()
        {
            var i = GetRandom.Int32() % 3;

            if (i == 1)
            {
                return(ServiceInstance.Random());
            }
            if (i == 2)
            {
                return(PackageInstance.Random());
            }
            return(ProductInstance.Random());
        }
Example #12
0
        public void GetCustomer_NullEntity_StatusFalse()
        {
            var expextedResult = new CustomerServiceResponse
            {
                Status  = false,
                Message = "Customer not found"
            };

            var actualResult = ServiceInstance.GetCustomer(Guid.NewGuid().ToString());

            Assert.AreEqual(expextedResult.Status, actualResult.Status);
            Assert.AreEqual(expextedResult.Message, actualResult.Message);
            Assert.IsNull(actualResult.Customer);
        }
Example #13
0
        static void Main(string[] args)
        {
            //Configure configuration file
            IConfiguration Configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                           .Build();

            //Read configurarion sections
            var authSection          = Configuration.GetSection("Authentication");
            var dataFileSection      = Configuration.GetSection("DataStore");
            var configurationSection = Configuration.GetSection("Configuration");

            //Create a file to keep track of last used twitter id
            StorageSettings storageSettings = new StorageSettings()
            {
                Datafolder    = dataFileSection["DataFolder"],
                FilePrefix    = dataFileSection["DataFilePrefix"],
                OverlayFolder = dataFileSection["OverlayFolder"]
            };
            DataStorage dataStorage = new DataStorage(storageSettings);

            //Create authentication object
            AuthToken authToken = new AuthToken()
            {
                AccessToken       = authSection["AccessToken"],
                AccessTokenSecret = authSection["AccessTokenSecret"],
                ConsumerKey       = authSection["ConsumerKey"],
                ConsumerKeySecret = authSection["ConsumerKeySecret"]
            };

            //Create configuration object
            BotConfiguration configuration = new BotConfiguration
            {
                BaseHashTag = configurationSection["BaseHashTag"],
                AuthToken   = authToken,
                DataStorage = dataStorage
            };

            //Create a twitter service instance
            ServiceInstance serviceInstance = new ServiceInstance(configuration);

            //Create action handler and make sure it gets called
            foreach (var capability in Capabilities.GetAll())
            {
                ActionHandler actionHandler = new ActionHandler(serviceInstance);
                string        result        = actionHandler.RunAction(capability);

                Console.WriteLine(result);
            }
        }
Example #14
0
        public void GetCustomer_EmptyId_StatusFalse()
        {
            var expextedResult = new CustomerServiceResponse
            {
                Status  = false,
                Message = "Id cannot be null or empty"
            };

            var actualResult = ServiceInstance.GetCustomer(string.Empty);

            Assert.AreEqual(expextedResult.Status, actualResult.Status);
            Assert.AreEqual(expextedResult.Message, actualResult.Message);
            Assert.IsNull(actualResult.Customer);
        }
Example #15
0
 private void RemoveService(Guid guid)
 {
     if (this.services != null)
     {
         ServiceInstance serviceInstance = this.services[guid];
         if (serviceInstance != null)
         {
             services.Remove(guid);
             if (serviceInstance.shouldDispose && serviceInstance.service is IDisposable)
             {
                 ((IDisposable)(serviceInstance.service)).Dispose();
             }
         }
     }
 }
        /// <summary>
        /// Configure a service instance, which supports one or more receive endpoints, all of which are managed by conductor.
        /// </summary>
        /// <param name="configurator"></param>
        /// <param name="configure"></param>
        public static void ServiceInstance(this IInMemoryBusFactoryConfigurator configurator,
                                           Action <IServiceInstanceConfigurator <IInMemoryReceiveEndpointConfigurator> > configure)
        {
            var instanceId           = NewId.Next();
            var instanceEndpointName = ServiceEndpointNameFormatter.Instance.EndpointName(instanceId);

            configurator.ReceiveEndpoint(instanceEndpointName, endpointConfigurator =>
            {
                var instance = new ServiceInstance(instanceId, endpointConfigurator);

                var instanceConfigurator = new InMemoryServiceInstanceConfigurator(configurator, instance);

                configure?.Invoke(instanceConfigurator);
            });
        }
        /// <summary>
        /// Configure a service instance for use with the job service
        /// </summary>
        /// <param name="configurator"></param>
        /// <param name="options"></param>
        /// <param name="configure"></param>
        public static void ServiceInstance <TEndpointConfigurator>(this IBusFactoryConfigurator <TEndpointConfigurator> configurator,
                                                                   ServiceInstanceOptions options, Action <IServiceInstanceConfigurator <TEndpointConfigurator> > configure)
            where TEndpointConfigurator : IReceiveEndpointConfigurator
        {
            var instance = new ServiceInstance();

            var definition = new InstanceEndpointDefinition(instance);

            configurator.ReceiveEndpoint(definition, options.EndpointNameFormatter, endpointConfigurator =>
            {
                var instanceConfigurator = new ServiceInstanceConfigurator <TEndpointConfigurator>(configurator, options, endpointConfigurator);

                configure?.Invoke(instanceConfigurator);
            });
        }
Example #18
0
 private void RunLimitedService(ServiceInstance service, ref int serviceSlotsCounter)
 {
     // Check if there is empty slot to run the service.
     if (serviceSlotsCounter < this[service.Configuration.Name].ServiceMaxSlots)
     {
         // Activate the service
         RunService(service);
         ++serviceSlotsCounter;
     }
     //else // Can't activate another service.
     //{
     //    // Write to log an information log.
     //    Log.Write(String.Format("The service {0} with RuntimeID {1} can't run now because there are no free instance to run the service. The service will try to activate in the next cycle."
     //        , service.Configuration.Name, service.InstanceID), LogMessageType.Information);
     //}
 }
Example #19
0
        /*=========================*/
        #endregion

        #region Public Methods
        /*=========================*/

        /// <summary>
        /// Add the service to the relevent service List and if the list don't exist
        /// we creates it.
        /// </summary>
        /// <param name="service">ServiceInstance to add to queue.</param>
        public void AddService(ServiceInstance service)
        {
            // Create new service list if needed.
            if (!this.ContainsKey(service.Configuration.Name))
            {
                this.Add(service.Configuration.Name, new ServiceList(service.Configuration));
            }
            if (!this[service.Configuration.Name].Contains(service))
            {
                this[service.Configuration.Name].Add(service);                //, false);
            }
            else
            {
                // dune: log me
            }
        }
        /*=========================*/

        #endregion

        #region Events handlers
        /*=========================*/

        static string Header(ServiceInstance instance)
        {
            string output = string.Format("{0} {1} - {2,3} - ",
                                          DateTime.Now.ToString("dd/MM"),
                                          DateTime.Now.ToShortTimeString(),
                                          instance.AccountID);

            for (ServiceInstance parent = instance.ParentInstance; parent != null; parent = parent.ParentInstance)
            {
                output += "    ";
            }

            output += instance.ToString();

            return(output);
        }
Example #21
0
        public void AddCustomer_NullLastName_StatusFalse()
        {
            var expextedResult = new CustomerServiceResponse
            {
                Status  = false,
                Message = "FirstName or LastName cannot be null or empty"
            };

            var actualResult = ServiceInstance.AddCustomer(new Customer
            {
                FirstName = "Test",
                LastName  = null
            });

            Assert.AreEqual(expextedResult.Status, actualResult.Status);
            Assert.AreEqual(expextedResult.Message, actualResult.Message);
        }
Example #22
0
        public async void LoadCharacteristics()
        {
            IEnumerable <ICharacteristic> characteristics = await ServiceInstance.GetCharacteristicsAsync();

            foreach (ICharacteristic characteristic in characteristics)
            {
                if (characteristic.Id == LedTextCharacteristicId)
                {
                    _ledTextCharacteristic         = characteristic;
                    LedTextCharacteristicAvailable = true;
                }
                else if (characteristic.Id == LedMatrixStateCharacteristicId)
                {
                    _ledMatrixCharacteristic         = characteristic;
                    LedMatrixCharacteristicAvailable = true;
                }
            }
        }
Example #23
0
        /// <summary>
        /// Write a warning to the log that the service pass its max Deviation
        /// time and remove it from the list.
        /// </summary>
        /// <param name="serviceList">The service list the sevice belong to.</param>
        /// <param name="service">The service that Pass Its Max Deviation time.</param>
        private void ServicePassItsMaxDeviation(ServiceList serviceList, ServiceInstance service)
        {
            // Write to log the warning.
            Log.Write(String.Format("The service {0} for account {1} can't run because it has passed its MaxDeviation.", service, service.AccountID), LogMessageType.Warning);

            // Remove service from queue.
            serviceList.Remove(service);

            //if (service.InstanceType == ServiceInstanceType.Normal)
            //{
            //    // Inform parent service that the service could not be scheduled.
            //    if (service.ParentInstance != null)
            //    {
            //        // Raise the event that will tune the parent.
            //        service.Outcome = ServiceOutcome.CouldNotBeScheduled;
            //    }
            //}
        }
Example #24
0
        private void UpdateExistingRoutes(IService instance, ServiceInstance info)
        {
            var routes = ServiceUtils.RoutesFromTags(info.ServiceTags);

            if (instance.Routes.SequenceEqual(routes))
            {
                return;
            }
            foreach (var newTag in routes.Except(instance.Routes))
            {
                _router.AddServiceToRoute(newTag, instance);
            }
            foreach (var oldTag in instance.Routes.Except(routes))
            {
                _router.RemoveServiceFromRoute(oldTag, instance);
            }
            instance.UpdateRoutes(routes);
        }
Example #25
0
        public void AddCustomer_CorrectResult_StatusTrue()
        {
            var expextedResult = new CustomerServiceResponse
            {
                Status  = true,
                Message = "Customer added"
            };

            var actualResult = ServiceInstance.AddCustomer(new Customer
            {
                FirstName = "Test FirstName",
                LastName  = "Test LastName"
            });

            Assert.AreEqual(expextedResult.Status, actualResult.Status);
            Assert.AreEqual(expextedResult.Message, actualResult.Message);
            Assert.IsNotNull(actualResult.Customer);
        }
Example #26
0
 public static PostResponseModel _QueryClass(PostInparamModel value)
 {
     try
     {
         using (ServiceInstance server = FrameCorex.RecoverService(value.Token, (c) => { Debug.WriteLine("Container Token not found Token: " + c); }))
         {
             if (!FrameCorex.ServiceInstanceInfo(server).IsLogin)
             {
                 server.UserLogin(value.LID, value.PWD);
                 FrameCorex.ServiceInstanceInfo(server).DisposeInfo = false;
             }
             var user     = FrameCorex.ServiceInstanceInfo(server).User;
             var tarclass = user.GetProjectInfo(value.Params["projectname"]);
             if (tarclass == null)
             {
                 throw new FPException("获取课程不存在");
             }
             return(new PostResponseModel()
             {
                 Message = "获取课程",
                 Result = Enums.APIResult.Success,
                 ExtResult =
                 {
                     { "课程ID",   tarclass.Key                                 },
                     { "课程日程",   tarclass.DayofWeek.ToString()                },
                     { "课程名称",   tarclass.ProjectName                         },
                     { "课程描述",   tarclass.Subtitle                            },
                     { "课程开始时间", tarclass.StartTime.Value.ToShortTimeString() },
                     { "课程结束时间", tarclass.EndTime.Value.ToShortTimeString()   }
                 },
                 UserLoginToken = FrameCorex.ServiceInstanceInfo(server).LoginHashToken
             });
         }
     }
     catch (FPException ex)
     {
         return(new PostResponseModel()
         {
             Message = ex.Message,
             Result = Enums.APIResult.Error
         });
     }
 }
Example #27
0
            public static PostResponseModel _AppendFace(FaceAPIControllerData value)
            {
                try
                {
                    using (ServiceInstance server = FrameCorex.RecoverService(value.LoginToken, (c) => { Debug.WriteLine("Container Token not found Token: " + c); }))
                        using (var tempfilepath = ("Emgu\\Temp\\" + server.HashMark.ConvertBase64StringFormat()).ToTempFilePath())
                        {
                            if (!FrameCorex.ServiceInstanceInfo(server).IsLogin)
                            {
                                server.UserLogin(value.Lid, value.Pwd);
                                FrameCorex.ServiceInstanceInfo(server).DisposeInfo = false;
                            }
                            var user = FrameCorex.ServiceInstanceInfo(server).User;

                            using (var fs = new FileStream(tempfilepath, FileMode.OpenOrCreate))
                            {
                                value.Image.CopyTo(fs);
                                fs.Flush();
                            }

                            user.SaveFaceRcognizer(tempfilepath);
                            user.Infos.HasFaceData = true;



                            return(new PostResponseModel()
                            {
                                Message = "成功",
                                Result = Enums.APIResult.Success,
                                ExtResult = { { "Name", user.Infos.Name } },
                                UserLoginToken = FrameCorex.ServiceInstanceInfo(server).LoginHashToken
                            });
                        }
                }
                catch (FPException ex)
                {
                    return(new PostResponseModel()
                    {
                        Message = ex.Message,
                        Result = Enums.APIResult.Error
                    });
                }
            }
Example #28
0
        public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)
        {
            ppvObject = (IntPtr)0;
            int hr = VSConstants.S_OK;

            ServiceInstance serviceInstance = null;

            if (services != null && services.ContainsKey(guidService))
            {
                serviceInstance = services[guidService];
            }

            if (serviceInstance == null)
            {
                return(VSConstants.E_NOINTERFACE);
            }

            // Now check to see if the user asked for an IID other than
            // IUnknown.  If so, we must do another QI.
            //
            if (riid.Equals(VSConstants.IID_IUnknown))
            {
                ppvObject = Marshal.GetIUnknownForObject(serviceInstance.service);
            }
            else
            {
                IntPtr pUnk = IntPtr.Zero;
                try
                {
                    pUnk = Marshal.GetIUnknownForObject(serviceInstance.service);
                    hr   = Marshal.QueryInterface(pUnk, ref riid, out ppvObject);
                }
                finally
                {
                    if (pUnk != IntPtr.Zero)
                    {
                        Marshal.Release(pUnk);
                    }
                }
            }

            return(hr);
        }
        private bool CheckAndCleanupPreviousService()
        {
            if (minerConfig.UpdatedInstanceType == null)
            {
                // Nothing to be updated.
                logger.Trace("UpdatedInstanceType is null, no need to update.");
                return(false);
            }

            // Uninstall the previous service instance
            MinerConfig.InstanceTypes instanceType = minerConfig.InstanceType;
            int instanceId = minerConfig.InstanceId;

            logger.Trace($"Try to find service with InstanceType=[{instanceType}] InstanceId=[{instanceId}].");
            ServiceProvider serviceProvider = ComposeServiceProvider(minerConfig.InstanceType);
            ServiceInstance serviceInstance = serviceProvider.AquaireInstance(minerConfig.InstanceId);

            if (serviceInstance.IsServiceExist())
            {
                logger.Trace("IsServiceExist is true, try uninstalling the previous service.");

                try
                {
                    serviceProvider.UninstallService(instanceId);
                }
                catch (Exception ex)
                {
                    // Will continue when uninstalling is failed.
                    logger.Error("Got error while uninstalling: " + ex.ToString());
                }
            }

            // If the uninsallation is successful, update the config file
            minerConfig.InstanceType        = minerConfig.UpdatedInstanceType.Value;
            minerConfig.InstanceId          = minerConfig.UpdatedInstanceId ?? 0;
            minerConfig.UpdatedInstanceType = null;
            minerConfig.UpdatedInstanceId   = null;

            minerConfig.SaveToFile();
            logger.Trace("Updated miner config file.");

            return(true);
        }
Example #30
0
        public async Task<NullableValue> RegisterServiceInstanceAsync(ServiceInstanceRequest serviceInstanceRequest,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (!_connectionManager.Ready)
            {
                return NullableValue.Null;
            }

            var connection = _connectionManager.GetConnection();
            return await new Call(_logger, _connectionManager).Execute(async () =>
                {
                    var client = new Register.RegisterClient(connection);
                    var instance = new ServiceInstance
                    {
                        ServiceId = serviceInstanceRequest.ServiceId,
                        InstanceUUID = serviceInstanceRequest.InstanceUUID,
                        Time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                    };

                    instance.Properties.Add(new KeyStringValuePair
                        {Key = OS_NAME, Value = serviceInstanceRequest.Properties.OsName});
                    instance.Properties.Add(new KeyStringValuePair
                        {Key = HOST_NAME, Value = serviceInstanceRequest.Properties.HostName});
                    instance.Properties.Add(new KeyStringValuePair
                        {Key = PROCESS_NO, Value = serviceInstanceRequest.Properties.ProcessNo.ToString()});
                    instance.Properties.Add(new KeyStringValuePair
                        {Key = LANGUAGE, Value = serviceInstanceRequest.Properties.Language});
                    foreach (var ip in serviceInstanceRequest.Properties.IpAddress)
                        instance.Properties.Add(new KeyStringValuePair
                            {Key = IPV4, Value = ip});

                    var serviceInstances = new ServiceInstances();
                    serviceInstances.Instances.Add(instance);
                    var mapping = await client.doServiceInstanceRegisterAsync(serviceInstances,
                        _config.GetMeta(), _config.GetTimeout(), cancellationToken);
                    foreach (var serviceInstance in mapping.ServiceInstances)
                        if (serviceInstance.Key == serviceInstanceRequest.InstanceUUID)
                            return new NullableValue(serviceInstance.Value);
                    return NullableValue.Null;
                },
                () => NullableValue.Null,
                () => ExceptionHelpers.RegisterServiceInstanceError);
        }
Example #31
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .UseSystemd()
        .ConfigureServices((hostContext, services) =>
        {
            //Add configurations
            IConfiguration configuration = hostContext.Configuration;
            DaemonOptions options        = configuration.GetSection("Daemon").Get <DaemonOptions>();

            //Create a file to keep track of last used twitter id
            StorageSettings storageSettings = new StorageSettings()
            {
                Datafolder    = options.DataStore.DataFolder,
                FilePrefix    = options.DataStore.DataFilePrefix,
                OverlayFolder = options.DataStore.OverlayFolder
            };
            DataStorage dataStorage = new DataStorage(storageSettings);

            //Create authentication object
            AuthToken authToken = new AuthToken()
            {
                AccessToken       = options.Authentication.AccessToken,
                AccessTokenSecret = options.Authentication.AccessTokenSecret,
                ConsumerKey       = options.Authentication.ConsumerKey,
                ConsumerKeySecret = options.Authentication.ConsumerKeySecret
            };

            //Create configuration object
            BotConfiguration botConfiguration = new BotConfiguration
            {
                BaseHashTag = options.BaseHashTag,
                AuthToken   = authToken,
                DataStorage = dataStorage,
                Interval    = options.Interval
            };

            //Create a twitter service instance and add it as singleton
            ServiceInstance serviceInstance = new ServiceInstance(botConfiguration);
            services.AddSingleton(serviceInstance);

            //Add worker
            services.AddHostedService <Worker>();
        });
Example #32
0
            public static PostResponseModel _SelectClass(PostInparamModel value)
            {
                try
                {
                    using (ServiceInstance server = FrameCorex.RecoverService(value.Token, (c) => { Debug.WriteLine("Container Token not found Token: " + c); }))
                    {
                        if (!FrameCorex.ServiceInstanceInfo(server).IsLogin)
                        {
                            server.UserLogin(value.LID, value.PWD);
                            FrameCorex.ServiceInstanceInfo(server).DisposeInfo = false;
                        }
                        var user = FrameCorex.ServiceInstanceInfo(server).User;

                        if (value.Params.ContainsKey("projectid"))
                        {
                            user.SelectProject(int.Parse(value.Params["projectid"]));
                        }
                        else if (value.Params.ContainsKey("projectname"))
                        {
                            user.SelectProject(value.Params["projectname"]);
                        }
                        else
                        {
                            throw new FPException("未指定选择的课程");
                        }
                        return(new PostResponseModel()
                        {
                            Message = "添加课程成功",
                            Result = Enums.APIResult.Success,
                            UserLoginToken = FrameCorex.ServiceInstanceInfo(server).LoginHashToken
                        });
                    }
                }
                catch (FPException ex)
                {
                    return(new PostResponseModel()
                    {
                        Message = ex.Message,
                        Result = Enums.APIResult.Error
                    });
                }
            }
        private void SaveService()
        {
            SocialTFSEntities db = new SocialTFSEntities();
            Service service = new Service();
            int id = Int32.Parse(Request.Params["ctl00$MainContent$ServiceSE"]);
            try
            {
                service = db.Service.Where(s => s.pk_id == id).Single();
            }
            catch
            {
                ErrorPA.Style.Remove("display");
            }

            IService iService = ServiceFactory.getService(service.name);
            ServiceInstance serviceInstance = new ServiceInstance();
            if (!iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance))
            {
                PreregisteredService preser = db.PreregisteredService.Where(ps => ps.service == service.pk_id).Single();

                serviceInstance.name = preser.name;
                serviceInstance.host = preser.host;
                serviceInstance.fk_service = preser.service;
                serviceInstance.consumerKey = preser.consumerKey;
                serviceInstance.consumerSecret = preser.consumerSecret;
                db.ServiceInstance.AddObject(serviceInstance);
            }
            else
            {
                string consumerKey = null, consumerSecret = null;
                string host = Request.Params["ctl00$MainContent$HostTB"];

                if (host.EndsWith(@"/"))
                    host = host.Remove(host.Length - 1);

                if (iService.GetPrivateFeatures().Contains(FeaturesType.OAuth1))
                {
                    consumerKey = Request.Params["ctl00$MainContent$ConsumerKeyTB"];
                    consumerSecret = Request.Params["ctl00$MainContent$ConsumerSecretTB"];
                }

                serviceInstance.name = Request.Params["ctl00$MainContent$NameTB"];
                serviceInstance.host = host;
                serviceInstance.Service = service;
                serviceInstance.consumerKey = consumerKey;
                serviceInstance.consumerSecret = consumerSecret;

                db.ServiceInstance.AddObject(serviceInstance);
            }

            db.SaveChanges();

            if (iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
            {
                iService.Get(FeaturesType.Labels, Request.Params["ctl00$MainContent$GitHubLabelTB"]);
            }

            foreach (FeaturesType featureType in iService.GetScoredFeatures())
            {
                db.FeatureScore.AddObject(new FeatureScore()
                {

                    pk_fk_serviceInstance = serviceInstance.pk_id,
                    pk_fk_feature = featureType.ToString(),
                    score = 1
                });
            }
            //TODO update the new version (leave comment from the next line)
            //dbService.version = newServiceVersion;
            db.SaveChanges();

            Response.Redirect("Services.aspx");
        }
        public void Execute()
        {
            SvcI = SvcBase.Service;

            config = GetK2CRMConfig(SvcI.ServiceConfiguration.ServiceAuthentication.UserName, SvcI.ServiceConfiguration.ServiceAuthentication.Password, GetConfigPropertyValue("RESTServiceURL"));
            crmconfig = new CRMConfig
            {
                CRMURL = GetConfigPropertyValue("CRMURL"),
                CRMOrganization = GetConfigPropertyValue("CRMOrganization")
            };


            ServiceObject so = SvcI.ServiceObjects[0];
            string methodName = so.Methods[0].Name;
            switch (methodName.ToLower())
            {
                case "changeowner":
                    ChangeOwner(ref so);
                    break;
                case "setstatestatus":
                    SetStateStatus(ref so);
                    break;
                case "getentities":
                    GetEntities(ref so);
                    break;
                case "bulkactiontasks":
                    BulkActionTasks(ref so);
                    break;
                case "createtask":
                    CreateTask(ref so);
                    break;
                case "getcrmuser":
                    GetCRMUser(ref so);
                    break;
                case "startcrmworkflow":
                    StartCRMWorkflow(ref so);
                    break;
                case "getentitymetadata":
                    GetEntityMetadata(ref so);
                    break;
                case "bulkactiontaskssetcriteria":
                    BulkActionTasksSetCriteria(ref so);
                    break;
                case "retrievemultiple":
                    RetrieveMultiple(ref so);
                    break;
                case "getallentities":
                    GetAllEntities(ref so);
                    break;
                case "getentityattributes":
                    GetEntityAttributes(ref so);
                    break;
                case "getpicklist":
                    GetPicklist(ref so);
                    break;
                case "getstatestatuspicklist":
                    GetStateStatusPicklist(ref so);
                    break;
                    
            }
        }
        private void SaveService()
        {
            ConnectorDataContext db = new ConnectorDataContext();
            Service service = new Service();
            try
            {
                Stopwatch w3 = Stopwatch.StartNew();
                service = db.Services.Where(s => s.id == Int32.Parse(Request.Params["ctl00$MainContent$ServiceSE"])).Single();
                w3.Stop();
                ILog log3 = LogManager.GetLogger("QueryLogger");
                log3.Info(" Elapsed time: " + w3.Elapsed + ", select the service to save it");
            }
            catch
            {
                ErrorPA.Style.Remove("display");
            }

            IService iService = ServiceFactory.getService(service.name);
            ServiceInstance serviceInstance = new ServiceInstance();
            if (!iService.GetPrivateFeatures().Contains(FeaturesType.MoreInstance))
            {
                Stopwatch w4 = Stopwatch.StartNew();
                PreregisteredService preser = db.PreregisteredServices.Where(ps => ps.service == service.id).Single();
                w4.Stop();
                ILog log4 = LogManager.GetLogger("QueryLogger");
                log4.Info(" Elapsed time: " + w4.Elapsed + ", select the preregistered service to save the service");

                serviceInstance.name = preser.name;
                serviceInstance.host = preser.host;
                serviceInstance.service = preser.service;
                serviceInstance.consumerKey = preser.consumerKey;
                serviceInstance.consumerSecret = preser.consumerSecret;

                Stopwatch w5 = Stopwatch.StartNew();
                db.ServiceInstances.InsertOnSubmit(serviceInstance);
                w5.Stop();
                ILog log5 = LogManager.GetLogger("QueryLogger");
                log5.Info(" Elapsed time: " + w5.Elapsed + ", insert the service instance in a pending state");
            }
            else
            {
                string consumerKey = null, consumerSecret = null;
                string host = Request.Params["ctl00$MainContent$HostTB"];

                if (host.EndsWith(@"/"))
                    host = host.Remove(host.Length - 1);

                if (iService.GetPrivateFeatures().Contains(FeaturesType.OAuth1))
                {
                    consumerKey = Request.Params["ctl00$MainContent$ConsumerKeyTB"];
                    consumerSecret = Request.Params["ctl00$MainContent$ConsumerSecretTB"];
                }

                serviceInstance.name = Request.Params["ctl00$MainContent$NameTB"];
                serviceInstance.host = host;
                serviceInstance.service = service.id;
                serviceInstance.consumerKey = consumerKey;
                serviceInstance.consumerSecret = consumerSecret;

                Stopwatch w6 = Stopwatch.StartNew();
                db.ServiceInstances.InsertOnSubmit(serviceInstance);
                w6.Stop();
                ILog log6 = LogManager.GetLogger("QueryLogger");
                log6.Info(" Elapsed time: " + w6.Elapsed + ", insert the service instance in a pending state");
            }

            Stopwatch w7 = Stopwatch.StartNew();
            db.SubmitChanges();
            w7.Stop();
            ILog log7 = LogManager.GetLogger("QueryLogger");
            log7.Info(" Elapsed time: " + w7.Elapsed + ", insert the service ");

            if (iService.GetPrivateFeatures().Contains(FeaturesType.Labels))
            {
                iService.Get(FeaturesType.Labels, Request.Params["ctl00$MainContent$GitHubLabelTB"]);
            }

            foreach (FeaturesType featureType in iService.GetScoredFeatures())
            {
                Stopwatch w8 = Stopwatch.StartNew();
                db.FeatureScores.InsertOnSubmit(new FeatureScore()
                {
                    serviceInstance = serviceInstance.id,
                    feature = featureType.ToString(),
                    score = 1
                });
                w8.Stop();
                ILog log8 = LogManager.GetLogger("QueryLogger");
                log8.Info(" Elapsed time: " + w8.Elapsed + ", insert the relative feature score in a pending state");
            }
            //TODO update the new version (leave comment from the next line)
            //dbService.version = newServiceVersion;
            Stopwatch w9 = Stopwatch.StartNew();
            db.SubmitChanges();
            w9.Stop();
            ILog log9 = LogManager.GetLogger("QueryLogger");
            log9.Info(" Elapsed time: " + w9.Elapsed + ", insert the feature score");

            Response.Redirect("Services.aspx");
        }
        /// <summary>
        /// Loads all methods from interfaces and assigns an identifier
        /// to each. These are later synchronized with the client.
        /// </summary>
        private void CreateMethodMap()
        {
            _serviceInstance = new ServiceInstance()
            {
                KeyIndex = 0, //only one per intercepted interface
                InterfaceType = _serviceType,
                InterfaceMethods = new ConcurrentDictionary<int, MethodInfo>(),
                MethodParametersByRef = new ConcurrentDictionary<int, bool[]>(),
                SingletonInstance = _interceptPoint.Target
            };

            var currentMethodIdent = 0;
            if (_serviceType.IsInterface)
            {
                var methodInfos = _serviceType.GetMethods();
                foreach (var mi in methodInfos)
                {
                    _serviceInstance.InterfaceMethods.TryAdd(currentMethodIdent, mi);
                    var parameterInfos = mi.GetParameters();
                    var isByRef = new bool[parameterInfos.Length];
                    for (int i = 0; i < isByRef.Length; i++)
                        isByRef[i] = parameterInfos[i].ParameterType.IsByRef;
                    _serviceInstance.MethodParametersByRef.TryAdd(currentMethodIdent, isByRef);
                    currentMethodIdent++;
                }
            }

            var interfaces = _serviceType.GetInterfaces();
            foreach (var interfaceType in interfaces)
            {
                var methodInfos = interfaceType.GetMethods();
                foreach (var mi in methodInfos)
                {
                    _serviceInstance.InterfaceMethods.TryAdd(currentMethodIdent, mi);
                    var parameterInfos = mi.GetParameters();
                    var isByRef = new bool[parameterInfos.Length];
                    for (int i = 0; i < isByRef.Length; i++)
                        isByRef[i] = parameterInfos[i].ParameterType.IsByRef;
                    _serviceInstance.MethodParametersByRef.TryAdd(currentMethodIdent, isByRef);
                    currentMethodIdent++;
                }
            }

            //Create a list of sync infos from the dictionary
            var syncSyncInfos = new List<MethodSyncInfo>();
            foreach (var kvp in _serviceInstance.InterfaceMethods)
            {
                var parameters = kvp.Value.GetParameters();
                var parameterTypes = new Type[parameters.Length];
                for (var i = 0; i < parameters.Length; i++)
                    parameterTypes[i] = parameters[i].ParameterType;
                syncSyncInfos.Add(new MethodSyncInfo
                {
                    MethodIdent = kvp.Key,
                    MethodName = kvp.Value.Name,
                    ParameterTypes = parameterTypes
                });
            }

            var serviceSyncInfo = new ServiceSyncInfo
            {
                ServiceKeyIndex = 0,
                CompressionThreshold = 131072,
                UseCompression = false,
                MethodInfos = syncSyncInfos.ToArray()
            };
            _serviceInstance.ServiceSyncInfo = serviceSyncInfo;
        }
Example #37
0
 public Receiver(string name)
 {
     this.instance = new ServiceInstance();
     this.host = new ServiceHost(this.instance, new Uri("net.pipe://localhost/" + name));
     this.host.AddServiceEndpoint(typeof(IClient), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), string.Empty);
 }
        public void Execute()
        {
            SvcI = SvcBase.Service;

            //config = GetK2CRMConfig(SvcI.ServiceConfiguration.ServiceAuthentication.UserName, SvcI.ServiceConfiguration.ServiceAuthentication.Password, GetConfigPropertyValue("RESTServiceURL"));
            crmconfig = new CRMConfig
            {
                CRMURL = GetConfigPropertyValue("CRMURL"),
                CRMOrganization = GetConfigPropertyValue("CRMOrganization")
            };

            if (!SvcI.ServiceConfiguration.ServiceAuthentication.Impersonate && !string.IsNullOrEmpty(SvcI.ServiceConfiguration.ServiceAuthentication.UserName.Trim()) && !string.IsNullOrEmpty(SvcI.ServiceConfiguration.ServiceAuthentication.Password.Trim()))
            {
                // Static credentials
                if (SvcI.ServiceConfiguration.ServiceAuthentication.UserName.Contains("\\"))
                {
                    char[] sp = { '\\' };
                    string[] user = SvcI.ServiceConfiguration.ServiceAuthentication.UserName.Split(sp);
                    crmconfig.CRMDomain = user[0].Trim();
                    crmconfig.CRMUsername = user[1].Trim();
                }
                else
                {
                    crmconfig.CRMUsername = SvcI.ServiceConfiguration.ServiceAuthentication.UserName.Trim();
                }
                crmconfig.CRMPassword = SvcI.ServiceConfiguration.ServiceAuthentication.Password;
            }

            CRMFunctions = new Functions.CRMFunctions(crmconfig);

            ServiceObject so = SvcI.ServiceObjects[0];
            string methodName = so.Methods[0].Name;
            switch (methodName.ToLower())
            {
                case "changeowner":
                    ChangeOwner(ref so);
                    break;
                case "setstatestatus":
                    SetStateStatus(ref so);
                    break;
                case "getentities":
                    GetEntities(ref so);
                    break;
                case "bulkactiontasks":
                    BulkActionTasks(ref so);
                    break;
                case "createtask":
                    CreateTask(ref so);
                    break;
                case "getcrmuser":
                    GetCRMUser(ref so);
                    break;
                case "startcrmworkflow":
                    StartCRMWorkflow(ref so);
                    break;
                case "getentitymetadata":
                    GetEntityMetadata(ref so);
                    break;
                case "bulkactiontaskssetcriteria":
                    BulkActionTasksSetCriteria(ref so);
                    break;
                case "retrievemultiple":
                    RetrieveMultiple(ref so);
                    break;
                case "getallentities":
                    GetAllEntities(ref so);
                    break;
                case "getentityattributes":
                    GetEntityAttributes(ref so);
                    break;
                case "getpicklist":
                    GetPicklist(ref so);
                    break;
                case "getstatestatuspicklist":
                    GetStateStatusPicklist(ref so);
                    break;
                    
            }
        }