Пример #1
0
        public static IGroupAppService CreateGroupAppService()
        {
            var builder = new ServiceUriBuilder(AppName_EnterpriseContact, ServiceName_EnterpriseContactService);

            return(proxyFactory.CreateServiceProxy <IGroupAppService>(
                       builder.ToUri(), listenerName: ListenerName_GroupAppService));
        }
Пример #2
0
        public static IControlAppService CreateGroupFileControlAppService()
        {
            var builder = new ServiceUriBuilder(AppName_GroupFile, ServiceName_GroupFileService);

            return(proxyFactory.CreateServiceProxy <IControlAppService>(
                       builder.ToUri(), listenerName: ListenerName_ControlAppService));
        }
Пример #3
0
        public async Task <HttpResponseMessage> Join(int clusterId, [FromBody] JoinClusterRequest user)
        {
            try
            {
                if (user == null || String.IsNullOrWhiteSpace(user.UserEmail) || String.IsNullOrWhiteSpace(user.CaptchaResponse))
                {
                    return(this.Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               new BadRequestViewModel("MissingInput", messageResources.Manager.GetString("MissingInput"), "Missing input.")));
                }

                // validate captcha.
                bool captchaValid = await this.captcha.VerifyAsync(user.CaptchaResponse);

                if (!captchaValid)
                {
                    return(this.Request.CreateResponse(
                               HttpStatusCode.Forbidden,
                               new BadRequestViewModel("InvalidCaptcha", messageResources.Manager.GetString("InvalidCaptcha"), "Invalid parameter: captcha")));
                }

                ServiceUriBuilder builder        = new ServiceUriBuilder("ClusterService");
                IClusterService   clusterService = ServiceProxy.Create <IClusterService>(builder.ToUri(), new ServicePartitionKey(1));

                await clusterService.JoinClusterAsync(clusterId, user.UserEmail);

                return(this.Request.CreateResponse(HttpStatusCode.Accepted));
            }
            catch (AggregateException ae)
            {
                ArgumentException argumentEx = ae.InnerException as ArgumentException;
                if (argumentEx != null)
                {
                    return(this.Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               new BadRequestViewModel("InvalidEmail", messageResources.Manager.GetString("InvalidEmail"), argumentEx.Message)));
                }

                JoinClusterFailedException joinFailedEx = ae.InnerException as JoinClusterFailedException;
                if (joinFailedEx != null)
                {
                    return(this.Request.CreateResponse(
                               HttpStatusCode.BadRequest,
                               new BadRequestViewModel(
                                   joinFailedEx.Reason.ToString(),
                                   messageResources.Manager.GetString(joinFailedEx.Reason.ToString()),
                                   joinFailedEx.Message)));
                }

                return(this.Request.CreateResponse(
                           HttpStatusCode.InternalServerError,
                           new BadRequestViewModel("ServerError", messageResources.Manager.GetString("ServerError"), ae.InnerException.Message)));
            }
            catch (Exception e)
            {
                return(this.Request.CreateResponse(
                           HttpStatusCode.InternalServerError,
                           new BadRequestViewModel("ServerError", messageResources.Manager.GetString("ServerError"), e.Message)));
            }
        }
Пример #4
0
        private async Task TryGetUser(ClaimsPrincipal subject, Func <UserItemDto, Task> process)
        {
            var sub = subject?.GetSubjectId();

            if (sub == null)
            {
                throw new Exception("No sub claim present");
            }

            var builder = new ServiceUriBuilder(Sso.Remoting.Constants.ServiceName_ProfileStateService);

            var itemId = new ItemId(new Guid(sub));

            UserItemDto user = null;
            await StopwatchLog.TrackFuncAsync(async() => user = await _remoteServiceClient.CreateUserAppService(itemId).FindByIdAsync(itemId));

            if (user == null)
            {
                ServiceEventSource.Current.Message("No user found matching subject Id: {0}", sub);
            }
            else
            {
                await process(user);
            }
        }
Пример #5
0
        public IResourceAppService CreateResourceAppService()
        {
            var builder = new ServiceUriBuilder(Constants.ServiceName_ConfigService);

            return(proxyFactory.CreateServiceProxy <IResourceAppService>(builder.ToUri(),
                                                                         listenerName: Constants.ListenerName_ResourceAppService));
        }
Пример #6
0
        public static IBizSystemAppService CreateBizSystemAppService()
        {
            var builder = new ServiceUriBuilder(AppName_ConfigMgmt, ServiceName_SystemConfigStateService);

            return(proxyFactory.CreateServiceProxy <IBizSystemAppService>(
                       builder.ToUri(), listenerName: ListenerName_TodoCenterAppService));
        }
Пример #7
0
        public IPersistedGrantAppService CreatePersistedGrantAppService()
        {
            var builder = new ServiceUriBuilder(Constants.ServiceName_ConfigService);

            return(proxyFactory.CreateServiceProxy <IPersistedGrantAppService>(builder.ToUri(),
                                                                               listenerName: Constants.ListenerName_PersistedGrantAppService));
        }
Пример #8
0
        public IScanLoginNotifyAppService CreateScanLoginNotifyAppService()
        {
            var builder = new ServiceUriBuilder(Constants.ScanLoginServiceName);

            return(proxyFactory.CreateServiceProxy <IScanLoginNotifyAppService>(builder.ToUri(),
                                                                                listenerName: Constants.ListenerName_ScanLoginNotifyAppService));
        }
Пример #9
0
        public static IConversationMsgAppService CreateConversationMsgAppService(Guid conversationId)
        {
            var builder = new ServiceUriBuilder(AppName_InstantMessage, ServiceName_ConversationMsgStateService);

            return(proxyFactory.CreateServiceProxy <IConversationMsgAppService>(builder.ToUri(),
                                                                                new ItemId(conversationId).GetPartitionKey()));
        }
Пример #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc().AddJsonOptions(jsonOptions =>
            {
                jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });

            //this is the ASP.NET default DI framework. Allows you to inject implementations of interfaces (or concrete classes) into the constructor
            // of your service, so long as ASP.NET is the one handling the instantiation of those services. I'm just using transient scoped classes for everything,
            //but you can inject objects with many different lifecycle options
            services.AddTransient <IRetryStrategy, BasicRetryPattern>();
            services.AddTransient <ISurfReportsService>(ctx =>
            {
                var snurfUri = new ServiceUriBuilder("SnurfReportService");
                return(ServiceProxy.Create <ISurfReportsService>(snurfUri.ToUri(), new ServicePartitionKey(0)));
            });
            services.AddTransient <ISnowReportsService>(ctx =>
            {
                return(ServiceProxy.Create <ISnowReportsService>(new Uri("fabric:/GoodVibesSurfing/SnurfReportService"), new ServicePartitionKey(0)));
            });
            services.AddTransient <ISnurfReportValidationService>(ctx =>
            {
                return(ServiceProxy.Create <ISnurfReportValidationService>(new Uri("fabric:/GoodVibesSurfing/ValidationService"), new ServicePartitionKey(0)));
            });
            services.AddTransient <ISASKeyProvider>(ctx =>
            {
                var valetKeyUri = new ServiceUriBuilder("ValetAccessManager");
                return(ServiceProxy.Create <ISASKeyProvider>(valetKeyUri.ToUri()));
            });
        }
Пример #11
0
        public static IConversationCtrlAppService CreateConversationCtrlAppService()
        {
            var builder = new ServiceUriBuilder(AppName_InstantMessage, ServiceName_ConversationCtrlStateService);

            return(proxyFactory.CreateServiceProxy <IConversationCtrlAppService>(
                       builder.ToUri()));
        }
        public async Task <Guid> PostCheckout(string orderId)
        {
            ServiceEventSource.Current.Message("Now printing cart for POSTCHECKOUT...");

            Guid orderIdGuid          = Guid.Parse(orderId);
            ServiceUriBuilder builder = new ServiceUriBuilder(CustomerOrderServiceName);

            //We create a unique Guid that is associated with a customer order, as well as with the actor that represents that order's state.
            ICustomerOrderActor customerOrder = ActorProxy.Create <ICustomerOrderActor>(new ActorId(orderIdGuid), builder.ToUri());

            try
            {
                await customerOrder.SubmitOrderAsync();

                ServiceEventSource.Current.Message("Customer order submitted successfully. ActorOrderID: {0} created", orderId);
            }
            catch (InvalidOperationException ex)
            {
                ServiceEventSource.Current.Message("Web Service: Actor rejected {0}: {1}", customerOrder, ex);
                throw;
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.Message("Web Service: Exception {0}: {1}", customerOrder, ex);
                throw;
            }

            return(orderIdGuid);
        }
Пример #13
0
        public async Task <Guid> PostItem(string orderId, CustomerOrderItem item)
        {
            ServiceEventSource.Current.Message("Guid {0}, quantity {1}", item.ItemId.ToString(), item.Quantity.ToString());

            Guid orderIdGuid          = Guid.Parse(orderId);
            ServiceUriBuilder builder = new ServiceUriBuilder(CustomerOrderServiceName);

            //We create a unique Guid that is associated with a customer order, as well as with the actor that represents that order's state.
            ICustomerOrderActor customerOrder = ActorProxy.Create <ICustomerOrderActor>(new ActorId(orderIdGuid), builder.ToUri());

            try
            {
                await customerOrder.AddItemToOrderAsync(item);

                ServiceEventSource.Current.Message("Customer order submitted successfully. ActorOrderID: {0} created", orderId);
            }
            catch (InvalidOperationException ex)
            {
                ServiceEventSource.Current.Message("Web Service: Actor rejected {0}: {1}", customerOrder, ex);
                throw;
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.Message("Web Service: Exception {0}: {1}", customerOrder, ex);
                throw;
            }

            return(orderIdGuid);
        }
Пример #14
0
        public async Task <Guid> PostCheckout(List <CustomerOrderItem> cart)
        {
            cart.Add(new CustomerOrderItem(new InventoryItemId(), 2));

            ServiceEventSource.Current.Message("Now printing cart for POSTCHECKOUT...");
            foreach (var item in cart)
            {
                ServiceEventSource.Current.Message("Guid {0}, quantity {1}", item.ItemId.ToString(), item.Quantity.ToString());
            }

            var orderId = Guid.NewGuid();
            var builder = new ServiceUriBuilder(CustomerOrderServiceName);

            //We create a unique Guid that is associated with a customer order, as well as with the actor that represents that order's state.
            var customerOrder = ActorProxy.Create <ICustomerOrderActor>(new ActorId(orderId), builder.ToUri());

            try
            {
                await customerOrder.SubmitOrderAsync(cart);

                ServiceEventSource.Current.Message("Customer order submitted successfully. ActorOrderID: {0} created", orderId);
            }
            catch (InvalidOperationException ex)
            {
                ServiceEventSource.Current.Message("Web Service: Actor rejected {0}: {1}", customerOrder, ex);
                throw;
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.Message("Web Service: Exception {0}: {1}", customerOrder, ex);
                throw;
            }

            return(orderId);
        }
Пример #15
0
        private IMyBackend GetServiceClientWithTransportSettings()
        {
            var builder = new ServiceUriBuilder(BackendServiceName);

            //var x509Credentials = new X509Credentials
            //{
            //    FindType = X509FindType.FindByThumbprint,
            //    FindValue = "053a87f6c1e3d08ec7fc28522a2cf1921c9daa5e",
            //    StoreLocation = StoreLocation.LocalMachine,
            //    StoreName = "My",
            //    ProtectionLevel = ProtectionLevel.EncryptAndSign
            //};
            //x509Credentials.RemoteCommonNames.Add("jacksch.westus.cloudapp.azure.com");

            //var transportSettings = new FabricTransportSettings
            //{
            //    SecurityCredentials = x509Credentials,
            //    MaxMessageSize = 10000000
            //};

            var serviceProxyFactory = new ServiceProxyFactory((c) =>
                                                              new FabricTransportServiceRemotingClientFactory());

            return(serviceProxyFactory.CreateServiceProxy <IMyBackend>(builder.ToUri()));
        }
        public Task<IEnumerable<ClusterView>> Get()
        {
            ServiceUriBuilder builder = new ServiceUriBuilder("ClusterService");
            IClusterService clusterService = ServiceProxy.Create<IClusterService>(1, builder.ToUri());

            return clusterService.GetClusterListAsync();
        }
Пример #17
0
        public static async Task <object> ExecuteFabricGETForEntity(Type targetObjectType, string targetServiceType, string servicePathAndQuery, string entityName, ServiceContext serviceContext, HttpClient httpClient, CancellationToken cancellationToken, IServiceEventSource serviceEventSource = null)
        {
            object objRet = null;
            ServiceEventSourceHelper serviceEventSourceHelper = new ServiceEventSourceHelper(serviceEventSource);

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(targetServiceType);
            Uri  serviceUri = uriBuilder.Build();
            long targetSiteServicePartitionKey = HashUtil.Hash(entityName);
            Uri  getUrl = new HttpServiceUriBuilder()
                          .SetServiceName(serviceUri)
                          .SetPartitionKey(targetSiteServicePartitionKey)
                          .SetServicePathAndQuery(servicePathAndQuery)
                          .Build();

            HttpResponseMessage response = await httpClient.GetAsync(getUrl, cancellationToken);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                serviceEventSourceHelper.ServiceMessage(serviceContext, $"On Execute Fabric GET - Service returned result[{response.StatusCode}] for entity[{entityName}] request[{servicePathAndQuery}]");
                objRet = response;
            }
            else
            {
                JsonSerializer serializer = new JsonSerializer();
                using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                {
                    using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                    {
                        objRet = serializer.Deserialize(jsonReader, targetObjectType);
                    }
                }
            }

            return(objRet);
        }
Пример #18
0
        public async Task <IActionResult> GetQueueLengthAsync()
        {
            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(TenantDataServiceName);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate the queue lengths from each partition
            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            HttpClient httpClient = new HttpClient(new HttpServiceClientHandler());

            long count = 0;

            foreach (Partition partition in partitions)
            {
                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery($"/api/devices/queue/length")
                             .Build();

                HttpResponseMessage response = await httpClient.GetAsync(getUrl, this.cancellationSource.Token);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    return(this.StatusCode((int)response.StatusCode));
                }

                string result = await response.Content.ReadAsStringAsync();

                count += Int64.Parse(result);
            }

            return(this.Ok(count));
        }
Пример #19
0
        public static IAttachmentAppService CreateAttachmentAppService(string itemId)
        {
            var builder = new ServiceUriBuilder(AppName_Attachment, ServiceName_AttachmentStateService);

            return(proxyFactory.CreateServiceProxy <IAttachmentAppService>(builder.ToUri(),
                                                                           new ServicePartitionKey(HashUtil.getLongHashCode(itemId))));
        }
Пример #20
0
        public async Task OnGetAsync()
        {
            Message = "Your contact page.";

            var builder = new ServiceUriBuilder("SampleState");

            //use native serialization
            //var proxy = ServiceProxy.Create<ISampleRemotingService>(builder.ToUri());

            //use bson serialization
            var proxyFactory = new ServiceProxyFactory((c) =>
            {
                return(new FabricTransportServiceRemotingClientFactory(
                           serializationProvider: new BsonSerializationProvider()));
            });
            var proxy = proxyFactory.CreateServiceProxy <ISampleRemotingService>(builder.ToUri());

            Peoples = await proxy.GetPeoplesAsync(new FilterDto { Search = "abc", Page = 5 });

            var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri("rabbitmq://localhost"), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });
            });
            await bus.Publish(new FilterDto { Search = "abc", Page = 5 });
        }
        public async Task <HttpResponseMessage> Post(string dictionaryName, int id, string referenceData)
        {
            if (string.IsNullOrEmpty(dictionaryName))
            {
                ServiceEventSource.Current.Message("Please specify a reference data dictionary to access data");
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden));
            }

            if (id < 1)
            {
                ServiceEventSource.Current.Message("Please pass in an appropriate id value");
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden));
            }

            try
            {
                ServiceUriBuilder             builder = new ServiceUriBuilder("ReferenceDataStatefulService");
                IReferenceDataStatefulService referenceDataService = ServiceProxy.Create <IReferenceDataStatefulService>(builder.ToUri(), new ServicePartitionKey(0));

                await referenceDataService.SetReferenceDataAsync(dictionaryName, id, referenceData);

                return(this.Request.CreateResponse(HttpStatusCode.Accepted));
            }
            catch (Exception)
            {
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }
Пример #22
0
        public static IWorkbenchAppService CreateWorkbenchAppService()
        {
            var builder = new ServiceUriBuilder(AppName_ConfigMgmt, ServiceName_SystemConfigStateService);

            return(proxyFactory.CreateServiceProxy <IWorkbenchAppService>(
                       builder.ToUri(), listenerName: ListenerName_WorkbenchAppService));
        }
        public async Task<HttpResponseMessage> Join(int clusterId, [FromBody] JoinClusterRequest user)
        {
            try
            {
                if (user == null || String.IsNullOrWhiteSpace(user.UserEmail) || String.IsNullOrWhiteSpace(user.CaptchaResponse))
                {
                    return this.Request.CreateResponse(
                        HttpStatusCode.BadRequest,
                        new BadRequestViewModel("MissingInput", messageResources.Manager.GetString("MissingInput"), "Missing input."));
                }

                // validate captcha.
                bool captchaValid = await this.captcha.VerifyAsync(user.CaptchaResponse);
                if (!captchaValid)
                {
                    return this.Request.CreateResponse(
                        HttpStatusCode.Forbidden,
                        new BadRequestViewModel("InvalidCaptcha", messageResources.Manager.GetString("InvalidCaptcha"), "Invalid parameter: captcha"));
                }

                ServiceUriBuilder builder = new ServiceUriBuilder("ClusterService");
                IClusterService clusterService = ServiceProxy.Create<IClusterService>(builder.ToUri(), new ServicePartitionKey(1));

                await clusterService.JoinClusterAsync(clusterId, user.UserEmail);

                return this.Request.CreateResponse(HttpStatusCode.Accepted);
            }
            catch (AggregateException ae)
            {
                ArgumentException argumentEx = ae.InnerException as ArgumentException;
                if (argumentEx != null)
                {
                    return this.Request.CreateResponse(
                        HttpStatusCode.BadRequest,
                        new BadRequestViewModel("InvalidEmail", messageResources.Manager.GetString("InvalidEmail"), argumentEx.Message));
                }

                JoinClusterFailedException joinFailedEx = ae.InnerException as JoinClusterFailedException;
                if (joinFailedEx != null)
                {
                    return this.Request.CreateResponse(
                        HttpStatusCode.BadRequest,
                        new BadRequestViewModel(
                            joinFailedEx.Reason.ToString(),
                            messageResources.Manager.GetString(joinFailedEx.Reason.ToString()),
                            joinFailedEx.Message));
                }

                return this.Request.CreateResponse(
                    HttpStatusCode.InternalServerError,
                    new BadRequestViewModel("ServerError", messageResources.Manager.GetString("ServerError"), ae.InnerException.Message));
            }
            catch (Exception e)
            {
                return this.Request.CreateResponse(
                    HttpStatusCode.InternalServerError,
                    new BadRequestViewModel("ServerError", messageResources.Manager.GetString("ServerError"), e.Message));
            }
        }
Пример #24
0
        public static IUserSettingAppService CreateUserSettingAppService(Guid userId)
        {
            var builder = new ServiceUriBuilder(AppName_ConfigMgmt, ServiceName_UserConfigStateService);

            return(proxyFactory.CreateServiceProxy <IUserSettingAppService>(
                       builder.ToUri(), new ItemId(userId).GetPartitionKey(),
                       listenerName: ListenerName_UserSettingAppService));
        }
Пример #25
0
        public HomeController(FabricClient fabricClient, HttpClient httpClient, IApplicationLifetime appLifetime)
        {
            this.httpClient     = httpClient;
            applicationLifetime = appLifetime;

            var uriBuilder = new ServiceUriBuilder("Back");

            backServiceUri = uriBuilder.Build();
        }
Пример #26
0
        public async Task <JsonResult> GetTransactions()
        {
            ServiceUriBuilder   builder            = new ServiceUriBuilder("TransactionService");
            ITransactionService transactionService = ServiceProxy.Create <ITransactionService>(builder.ToUri(), new ServicePartitionKey(0));

            var transactions = await transactionService.GetAllSavedTransactionsAsync();

            return(Json(transactions));
        }
        public async Task <JsonResult> SearchDevicesHistoryByPage(string deviceId = null, int batchIndex = 1, int batchSize = 200, string startTimestamp = null)
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri     = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);
            DeviceMessageList     deviceMessages = new DeviceMessageList(batchIndex, batchSize);

            ServiceUriBuilder uriBuilder = new ServiceUriBuilder(Names.InsightDataServiceName);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate the queue lengths from each partition
            ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            foreach (Partition partition in partitions)
            {
                string pathAndQuery = $"/api/devices/history/batchIndex/{batchIndex}/batchSize/{batchSize}";

                if (startTimestamp != null)
                {
                    pathAndQuery = $"/api/devices/history/batchIndex/{batchIndex}/batchSize/{batchSize}/startingAt/{startTimestamp}";
                    deviceMessages.SearchStartTimestamp = DateTimeOffset.Parse(startTimestamp).ToUniversalTime();
                }

                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery(pathAndQuery)
                             .Build();

                HttpResponseMessage response = await httpClient.GetAsync(getUrl, appLifetime.ApplicationStopping);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    JsonSerializer serializer = new JsonSerializer();
                    using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    {
                        using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                        {
                            DeviceMessageList resultDeviceEventSeriesList = serializer.Deserialize <DeviceMessageList>(jsonReader);

                            foreach (DeviceMessage row in resultDeviceEventSeriesList.Rows)
                            {
                                deviceMessages.AddRow(row);
                            }
                            deviceMessages.TotalCount += resultDeviceEventSeriesList.TotalCount;

                            if (deviceMessages.SearchStartTimestamp.ToUnixTimeMilliseconds() < 1000)
                            {
                                deviceMessages.SearchStartTimestamp = resultDeviceEventSeriesList.SearchStartTimestamp;
                            }
                        }
                    }
                }
            }

            return(this.Json(deviceMessages));
        }
Пример #28
0
        public async Task <JsonResult> GetListings()
        {
            ServiceUriBuilder builder        = new ServiceUriBuilder("ListingService");
            IListingService   listingService = ServiceProxy.Create <IListingService>(builder.ToUri(), new ServicePartitionKey(0));

            var listings = await listingService.GetAllListingsAsync();

            return(Json(listings));
        }
        public async Task <IActionResult> Post([FromRoute] string name, [FromBody] EventsProcessorApplicationParams parameters)
        {
            // Determine the number of IoT Hub partitions.
            // The events processing service will be created with the same number of partitions.
            EventHubClient             eventHubClient = EventHubClient.CreateFromConnectionString(parameters.IotHubConnectionString, "messages/events");
            EventHubRuntimeInformation eventHubInfo   = await eventHubClient.GetRuntimeInformationAsync();

            // Application parameters are passed to the Events Processing application instance.
            NameValueCollection appInstanceParameters = new NameValueCollection();

            appInstanceParameters["IotHubConnectionString"]        = parameters.IotHubConnectionString;
            appInstanceParameters["IotHubProcessOnlyFutureEvents"] = parameters.IotHubProcessOnlyFutureEvents;
            appInstanceParameters["PublishDataServiceURLs"]        = parameters.PublishDataServiceURLs;

            ApplicationDescription application = new ApplicationDescription(
                new Uri($"{Names.EventsProcessorApplicationPrefix}/{name}"),
                Names.EventsProcessorApplicationTypeName,
                parameters.Version,
                appInstanceParameters);

            // Create a named application instance
            await this.fabricClient.ApplicationManager.CreateApplicationAsync(application, this.operationTimeout, this.appLifetime.ApplicationStopping);

            // Next, create named instances of the services that run in the application.
            ServiceUriBuilder serviceNameUriBuilder = new ServiceUriBuilder(application.ApplicationName.ToString(), Names.EventsProcessorRouterServiceName);

            StatefulServiceDescription service = new StatefulServiceDescription()
            {
                ApplicationName            = application.ApplicationName,
                HasPersistedState          = true,
                MinReplicaSetSize          = 3,
                TargetReplicaSetSize       = 3,
                PartitionSchemeDescription = new UniformInt64RangePartitionSchemeDescription(eventHubInfo.PartitionCount, 0, eventHubInfo.PartitionCount - 1),
                ServiceName     = serviceNameUriBuilder.Build(),
                ServiceTypeName = Names.EventsProcessorRouterServiceTypeName
            };

            await this.fabricClient.ServiceManager.CreateServiceAsync(service, this.operationTimeout, this.appLifetime.ApplicationStopping);

            if (parameters.PublishDataServiceURLs != null && parameters.PublishDataServiceURLs.Length > 0)
            {
                // Next, create named instances of the services that run in the application.
                serviceNameUriBuilder = new ServiceUriBuilder(application.ApplicationName.ToString(), Names.EventsProcessorExtenderServiceName);

                StatelessServiceDescription extenderService = new StatelessServiceDescription()
                {
                    ApplicationName            = application.ApplicationName,
                    InstanceCount              = 1,
                    PartitionSchemeDescription = new SingletonPartitionSchemeDescription(),
                    ServiceName     = serviceNameUriBuilder.Build(),
                    ServiceTypeName = Names.EventsProcessorExtenderServiceTypeName
                };

                await this.fabricClient.ServiceManager.CreateServiceAsync(extenderService, this.operationTimeout, this.appLifetime.ApplicationStopping);
            }
            return(this.Ok());
        }
Пример #30
0
        public Task <HttpResponseMessage> GetNationalStats()
        {
            ServiceUriBuilder serviceUri = new ServiceUriBuilder(this.GetSetting("NationalServiceInstanceName"));
            HttpClient        client     = new HttpClient();

            return(client.SendToServiceAsync(
                       serviceUri.ToUri(),
                       () => new HttpRequestMessage(HttpMethod.Get, "/national/stats")));
        }
Пример #31
0
        public Task <HttpResponseMessage> GetCountyHealth(int countyId)
        {
            ServiceUriBuilder serviceUri = new ServiceUriBuilder(this.GetSetting("CountyServiceInstanceName"));
            HttpClient        client     = new HttpClient();

            return(client.SendToServiceAsync(
                       serviceUri.ToUri(),
                       countyId,
                       () => new HttpRequestMessage(HttpMethod.Get, "/county/health/" + countyId)));
        }
        public static async Task <List <DeviceMessage> > GetDevicesDataAsync(string deviceId, HttpClient httpClient, FabricClient fabricClient, IApplicationLifetime appLifetime)
        {
            List <DeviceMessage> deviceEventSeriesList = new List <DeviceMessage>();
            ServiceUriBuilder    uriBuilder            = new ServiceUriBuilder(Names.InsightDataServiceName);
            Uri serviceUri = uriBuilder.Build();

            // service may be partitioned.
            // this will aggregate device IDs from all partitions
            ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

            foreach (Partition partition in partitions)
            {
                Uri getUrl = new HttpServiceUriBuilder()
                             .SetServiceName(serviceUri)
                             .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                             .SetServicePathAndQuery($"/api/devices")
                             .Build();

                HttpResponseMessage response = await httpClient.GetAsync(getUrl, appLifetime.ApplicationStopping);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    return(deviceEventSeriesList);
                }

                JsonSerializerSettings jsonSettings = new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.Objects
                };

                string jsonObj = await response.Content.ReadAsStringAsync();

                List <DeviceMessage> result = JsonConvert.DeserializeObject <List <DeviceMessage> >(jsonObj, jsonSettings);

                if (result != null)
                {
                    if (deviceId == null)
                    {
                        deviceEventSeriesList.AddRange(result);
                    }
                    else
                    {
                        foreach (DeviceMessage deviceEventSeries in result)
                        {
                            if (deviceEventSeries.DeviceId.Equals(deviceId, StringComparison.InvariantCultureIgnoreCase))
                            {
                                deviceEventSeriesList.Add(deviceEventSeries);
                            }
                        }
                    }
                }
            }

            return(deviceEventSeriesList);
        }
        public async Task<IHttpActionResult> Get()
        {
            ServiceUriBuilder builder = new ServiceUriBuilder("ClusterService");
            IClusterService clusterService = ServiceProxy.Create<IClusterService>(1, builder.ToUri());

            IEnumerable<ClusterView> clusters = await clusterService.GetClusterListAsync();

            return Ok(clusters.Select(x => new
            {
                ClusterId = x.ClusterId,
                Name = GetClusterName(x.ClusterId),
                ApplicationCount = x.ApplicationCount,
                ServiceCount = x.ServiceCount,
                Capacity = GetUserCapacity(x.UserCount, x.MaxUsers),
                UserCount = x.UserCount,
                MaxUsers = x.MaxUsers,
                TimeRemaining = x.TimeRemaining > TimeSpan.Zero
                    ? String.Format("{0:hh\\:mm\\:ss}", x.TimeRemaining)
                    : "expired"
            }));
        }