public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var body = new
            {
                items = new[] {
                    new {
                        name = "Product 1",
                        value = 1000,
                        amount = 2
                    }
                },
                shippings = new[] {
                    new {
                        name = "Default Shipping Cost",
                        value = 100
                    }
                }
            };

            try
            {
                var response = endpoints.CreateCharge(null, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                id = 1001
            };

            var body = new
            {
                notification_url = "http://yourdomain.com",
                custom_id = "my_new_id"
            };

            try
            {
                var response = endpoints.UpdateCarnetMetadata(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                id = 1000
            };

            var body = new
            {
                billet_discount = 0,
                card_discount = 0,
                message = "",
                expire_at = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd"),
                request_delivery_address = false,
                payment_method = "all"
            };

            try
            {
                var response = endpoints.LinkCharge(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                id = 1001,
                parcel = 2
            };

            var body = new
            {
                email = "*****@*****.**"
            };

            try
            {
                var response = endpoints.ResendParcel(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                id = 1174
            };

            var body = new
            {
                expire_at = "2020-12-20"
            };

            try
            {
                var response = endpoints.UpdateBillet(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new {
                id = 1001
            };

            var body = new
            {
                description = "This carnet is about a service"
            };


            try
            {
                var response = endpoints.CreateCarnetHistory(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
 public Configuration(Environments environment, string terminalToken, string apiLogin, string apiPassword, X509Certificate certificate, Endpoints endpoint)
 {
     Environment = environment;
     TerminalToken = terminalToken;
     ApiLogin = apiLogin;
     ApiPassword = apiPassword;
     Certificate = certificate;
     Endpoint = endpoint;
 }
        public override void TestFixtureSetUp()
        {
            base.TestFixtureSetUp();
#if DEBUG
            QueueStatsCollector.InitializeIdleDetection();
#else 
            throw new NotSupportedException("These tests require DEBUG conditional");
#endif

            _nodeEndpoints[0] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
            _nodeEndpoints[1] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
            _nodeEndpoints[2] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));

            PortsHelper.GetAvailablePort(IPAddress.Loopback);

            _nodes[0] = CreateNode(0, 
                _nodeEndpoints[0], new IPEndPoint[] {_nodeEndpoints[1].InternalHttp, _nodeEndpoints[2].InternalHttp});
            _nodes[1] = CreateNode(1, 
                _nodeEndpoints[1], new IPEndPoint[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[2].InternalHttp });
            
            _nodes[2] = CreateNode(2, 
                _nodeEndpoints[2], new IPEndPoint[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[1].InternalHttp });
            

            _nodes[0].Start();
            _nodes[1].Start();
            _nodes[2].Start();

            WaitHandle.WaitAll(new[] { _nodes[0].StartedEvent, _nodes[1].StartedEvent, _nodes[2].StartedEvent });
            QueueStatsCollector.WaitIdle(waitForNonEmptyTf: true);
            _conn = EventStoreConnection.Create(_nodes[0].ExternalTcpEndPoint);
            _conn.ConnectAsync().Wait();

            _manager = new ProjectionsManager(
                new ConsoleLogger(),
                _nodes[0].ExternalHttpEndPoint,
                TimeSpan.FromMilliseconds(10000));

            if (GivenStandardProjectionsRunning())
                EnableStandardProjections();
            QueueStatsCollector.WaitIdle();
            Given();
            When();
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);
            
            var param = new
            {
                id = 1000
            };

            var body = new
            {
                payment = new
                {
                    credit_card = new
                    {
                        installments = 1,
                        payment_token = "6426f3abd8688639c6772963669bbb8e0eb3c319",
                        billing_address = new
                        {
                            street = "Av. JK",
                            number = 909,
                            neighborhood = "Bauxita",
                            zipcode = "35400000",
                            city = "Ouro Preto",
                            state = "MG"
                        },
                        customer = new
                        {
                            name = "Gorbadoc Oldbuck",
                            email = "*****@*****.**",
                            cpf = "04267484171",
                            birth = "1977-01-15",
                            phone_number = "5144916523"
                        }
                    }
                }
            };

            try
            {
                var response = endpoints.PayCharge(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                token = "46dab29b-ccf3-4c9a-8c39-254033fe06bc"
            };

            try
            {
                var response = endpoints.GetNotification(param);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                id = 0
            };

            try
            {
                var response = endpoints.CancelCharge(param);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                brand = "visa",
                total = 2500
            };

            try
            {
                var response = endpoints.GetInstallments(param);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                id = 1000
            };

            var body = new
            {
                payment = new
                {
                    banking_billet = new
                    {
                        expire_at = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"),
                        customer = new
                        {
                            name = "Gorbadoc Oldbuck",
                            email = "*****@*****.**",
                            cpf = "04267484171",
                            birth = "1977-01-15",
                            phone_number = "5144916523"
                        }
                    }
                }
            };

            try
            {
                var response = endpoints.PayCharge(param, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
Example #14
0
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var param = new
            {
                // name = "My Plan",
                limit = 20,
                offset = 0
            };

            try
            {
                var response = endpoints.GetPlans(param);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var body = new
            {
                name = "My first plan",
                repeats = 24,
                interval = 2
            };
            
            try
            {
                var response = endpoints.CreatePlan(null, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var planBody = new {
                name = "My first plan",
                repeats = 24,
                interval = 2
            };
            
            var subscriptionBody = new
            {
                items = new[] {
                    new {
                        name = "Product 1",
                        value = 1000,
                        amount = 2
                    }
                }
            };

            try
            {
                var planResponse = endpoints.CreatePlan(null, planBody);

                var subscriptionParam = new {
                    id = planResponse.data.plan_id
                };
                var subscriptionResponse = endpoints.CreateSubscription(subscriptionParam, subscriptionBody);
                Console.WriteLine(subscriptionResponse);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var body = new
            {
                items = new[] {
                    new {
                        name = "Carnet Item 1",
                        value = 1000,
                        amount = 2
                    }
                },
                customer = new
                {
                    name = "Gorbadoc Oldbuck",
                    email = "*****@*****.**",
                    cpf = "04267484171",
                    birth = "1977-01-15",
                    phone_number = "5144916523"
                },
                repeats = 12,
                split_items = false,
                expire_at = DateTime.Now.AddDays(5).ToString("yyyy-MM-dd")
            };

            try
            {
                var response = endpoints.CreateCarnet(null, body);
                Console.WriteLine(response);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
Example #18
0
 public LciServiceDal(IHttpService httpService, Endpoints endpoints)
 {
     this.httpService = httpService;
     this.endpoints   = endpoints;
 }
Example #19
0
 /// <summary> Subscribe to the event of a particular endpoint message 
 /// being received.  This enables subscribing to any endpoint, 
 /// including those that have yet to be discovered.
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="handler"></param>
 public void RegisterEndpointCallback(Endpoints endpoint, EventHandler<MessageReceivedEventArgs> handler)
 {
     if (handler == null)
     {
         throw new ArgumentNullException("handler");
     }
     if (endpointEvents.ContainsKey(endpoint) && endpointEvents[endpoint] != null)
     {
         endpointEvents[endpoint] += handler;
     }
     else
     {
         endpointEvents[endpoint] = new EventHandler<MessageReceivedEventArgs>((o, m) => { });
         endpointEvents[endpoint] += handler;
     }
 }
Example #20
0
        public override void Configure(IHostEnvironment hosting, IConfiguration config)
        {
            var connectionString = config.GetConnectionString("azureservicebus");

            Endpoints.ConfigureAzureServiceBus(connectionString);
        }
Example #21
0
 public void AddEndpoint(KnownEndpoint endpoint, IBucketer bucketer)
 {
     Endpoints.Add(endpoint);
     Bucketers.Add(endpoint.Request.OriginalEndpoint, bucketer);
 }
Example #22
0
 public ControlMain()
 {
     database  = LocalDatabase.GetInstance();
     endpoints = new Endpoints();
 }
        /// <summary>
        /// Applies required configuration for enabling cache in SDK 1.8.0 version by:
        /// * Add MemcacheShim runtime installation.
        /// * Add startup task to install memcache shim on the client side.
        /// * Add default memcache internal endpoint.
        /// * Add cache diagnostic to local resources.
        /// * Add ClientDiagnosticLevel setting to service configuration.
        /// * Adjust web.config to enable auto discovery for the caching role.
        /// </summary>
        /// <param name="cloudServiceProject">The azure service instance</param>
        /// <param name="webRole">The web role to enable caching on</param>
        /// <param name="isWebRole">Flag indicating if the provided role is web or not</param>
        /// <param name="cacheWorkerRole">The memcache worker role name</param>
        /// <param name="startup">The role startup</param>
        /// <param name="endpoints">The role endpoints</param>
        /// <param name="localResources">The role local resources</param>
        /// <param name="configurationSettings">The role configuration settings</param>
        private void Version180Configuration(
            CloudServiceProject cloudServiceProject,
            string roleName,
            bool isWebRole,
            string cacheWorkerRole,
            Startup startup,
            Endpoints endpoints,
            LocalResources localResources,
            ref DefinitionConfigurationSetting[] configurationSettings)
        {
            if (isWebRole)
            {
                // Generate cache scaffolding for web role
                cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WebRole.ToString()),
                                                        roleName, new Dictionary <string, object>());

                // Adjust web.config to enable auto discovery for the caching role.
                string webCloudConfigPath = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebCloudConfig);
                string webConfigPath      = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebConfigTemplateFileName);

                UpdateWebConfig(roleName, cacheWorkerRole, webCloudConfigPath);
                UpdateWebConfig(roleName, cacheWorkerRole, webConfigPath);
            }
            else
            {
                // Generate cache scaffolding for worker role
                Dictionary <string, object> parameters = new Dictionary <string, object>();
                parameters[ScaffoldParams.RoleName] = cacheWorkerRole;

                cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WorkerRole.ToString()),
                                                        roleName, parameters);
            }

            // Add default memcache internal endpoint.
            InternalEndpoint memcacheEndpoint = new InternalEndpoint
            {
                name     = Resources.MemcacheEndpointName,
                protocol = InternalProtocol.tcp,
                port     = Resources.MemcacheEndpointPort
            };

            endpoints.InternalEndpoint = GeneralUtilities.ExtendArray <InternalEndpoint>(endpoints.InternalEndpoint, memcacheEndpoint);

            // Enable cache diagnostic
            LocalStore localStore = new LocalStore
            {
                name = Resources.CacheDiagnosticStoreName,
                cleanOnRoleRecycle = false
            };

            localResources.LocalStorage = GeneralUtilities.ExtendArray <LocalStore>(localResources.LocalStorage, localStore);

            DefinitionConfigurationSetting diagnosticLevel = new DefinitionConfigurationSetting {
                name = Resources.CacheClientDiagnosticLevelAssemblyName
            };

            configurationSettings = GeneralUtilities.ExtendArray <DefinitionConfigurationSetting>(configurationSettings, diagnosticLevel);

            // Add ClientDiagnosticLevel setting to service configuration.
            AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetCloudConfigRole(roleName));
            AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetLocalConfigRole(roleName));
        }
 private bool DoesEndpointExist(string sip)
 {
     return(Endpoints.Any(x => x.Sip.Equals(sip, StringComparison.InvariantCultureIgnoreCase)));
 }
 public void ClearEndpoints()
 {
     SelectedEndpoint = null;
     Endpoints.Clear();
     ShowNoResultsMessage = true;
 }
 public void AddEndpoint(DeviceEndpoint endpoint)
 {
     Endpoints.Add(endpoint);
     ShowNoResultsMessage = false;
 }
 public Task <Tracking> Tracking(string packageNumber) => GetAsync <Tracking>(Endpoints.Tracking(packageNumber));
Example #28
0
 public OperationsService(ILogger <OperationsService> logger, IUserContext userContext, IPubSubService pubSubService, Endpoints endpoints)
 {
     _logger      = logger;
     _userContext = userContext;
     _hubUrl      = endpoints.Push;
     pubSubService.Subscribe <LoginSuccesfulEvent>(LoginSuccesful);
 }
        public void InitializeJob(JobRequestMessage message, CancellationToken token)
        {
            // Validation
            Trace.Entering();
            ArgUtil.NotNull(message, nameof(message));
            ArgUtil.NotNull(message.Environment, nameof(message.Environment));
            ArgUtil.NotNull(message.Environment.SystemConnection, nameof(message.Environment.SystemConnection));
            ArgUtil.NotNull(message.Environment.Endpoints, nameof(message.Environment.Endpoints));
            ArgUtil.NotNull(message.Environment.Variables, nameof(message.Environment.Variables));
            ArgUtil.NotNull(message.Plan, nameof(message.Plan));

            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);

            // Features
            Features = ApiUtil.GetFeatures(message.Plan);

            // Endpoints
            Endpoints = message.Environment.Endpoints;
            Endpoints.Add(message.Environment.SystemConnection);

            // SecureFiles
            SecureFiles = message.Environment.SecureFiles;

            // Variables (constructor performs initial recursive expansion)
            List <string> warnings;

            Variables = new Variables(HostContext, message.Environment.Variables, message.Environment.MaskHints, out warnings);

            // Proxy variables
            var proxyConfiguration = HostContext.GetService <IProxyConfiguration>();

            if (!string.IsNullOrEmpty(proxyConfiguration.ProxyUrl))
            {
                Variables.Set(Constants.Variables.Agent.ProxyUrl, proxyConfiguration.ProxyUrl);
                Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY", string.Empty);

                if (!string.IsNullOrEmpty(proxyConfiguration.ProxyUsername))
                {
                    Variables.Set(Constants.Variables.Agent.ProxyUsername, proxyConfiguration.ProxyUsername);
                    Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY_USERNAME", string.Empty);
                }

                if (!string.IsNullOrEmpty(proxyConfiguration.ProxyPassword))
                {
                    Variables.Set(Constants.Variables.Agent.ProxyPassword, proxyConfiguration.ProxyPassword, true);
                    Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY_PASSWORD", string.Empty);
                }
            }

            // Job timeline record.
            InitializeTimelineRecord(
                timelineId: message.Timeline.Id,
                timelineRecordId: message.JobId,
                parentTimelineRecordId: null,
                recordType: ExecutionContextType.Job,
                name: message.JobName,
                order: 1); // The job timeline record must be at order 1.

            // Logger (must be initialized before writing warnings).
            _logger = HostContext.CreateService <IPagingLogger>();
            _logger.Setup(_mainTimelineId, _record.Id);

            // Log warnings from recursive variable expansion.
            warnings?.ForEach(x => this.Warning(x));

            // Verbosity (from system.debug).
            WriteDebug = Variables.System_Debug ?? false;

            // Hook up JobServerQueueThrottling event, we will log warning on server tarpit.
            _jobServerQueue.JobServerQueueThrottling += JobServerQueueThrottling_EventReceived;
        }
Example #30
0
        public void InitializeJob(JobRequestMessage message, CancellationToken token)
        {
            // Validation
            Trace.Entering();
            ArgUtil.NotNull(message, nameof(message));
            ArgUtil.NotNull(message.Environment, nameof(message.Environment));
            ArgUtil.NotNull(message.Environment.SystemConnection, nameof(message.Environment.SystemConnection));
            ArgUtil.NotNull(message.Environment.Endpoints, nameof(message.Environment.Endpoints));
            ArgUtil.NotNull(message.Environment.Variables, nameof(message.Environment.Variables));
            ArgUtil.NotNull(message.Plan, nameof(message.Plan));

            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(token);

            // Features
            Features = ApiUtil.GetFeatures(message.Plan);

            // Endpoints
            Endpoints = message.Environment.Endpoints;
            Endpoints.Add(message.Environment.SystemConnection);

            // SecureFiles
            SecureFiles = message.Environment.SecureFiles;

            // Variables (constructor performs initial recursive expansion)
            List <string> warnings;

            Variables = new Variables(HostContext, message.Environment.Variables, message.Environment.MaskHints, out warnings);

            // Prepend Path
            PrependPath = new List <string>();

            // Docker
            Container = new ContainerInfo()
            {
                ContainerImage = Variables.Get("_PREVIEW_VSTS_DOCKER_IMAGE"),
                ContainerName  = $"VSTS_{Variables.System_HostType.ToString()}_{message.JobId.ToString("D")}",
            };

            // Proxy variables
            var agentWebProxy = HostContext.GetService <IVstsAgentWebProxy>();

            if (!string.IsNullOrEmpty(agentWebProxy.ProxyAddress))
            {
                Variables.Set(Constants.Variables.Agent.ProxyUrl, agentWebProxy.ProxyAddress);
                Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY", string.Empty);

                if (!string.IsNullOrEmpty(agentWebProxy.ProxyUsername))
                {
                    Variables.Set(Constants.Variables.Agent.ProxyUsername, agentWebProxy.ProxyUsername);
                    Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY_USERNAME", string.Empty);
                }

                if (!string.IsNullOrEmpty(agentWebProxy.ProxyPassword))
                {
                    Variables.Set(Constants.Variables.Agent.ProxyPassword, agentWebProxy.ProxyPassword, true);
                    Environment.SetEnvironmentVariable("VSTS_HTTP_PROXY_PASSWORD", string.Empty);
                }

                if (agentWebProxy.ProxyBypassList.Count > 0)
                {
                    Variables.Set(Constants.Variables.Agent.ProxyBypassList, JsonUtility.ToString(agentWebProxy.ProxyBypassList));
                }
            }

            // Job timeline record.
            InitializeTimelineRecord(
                timelineId: message.Timeline.Id,
                timelineRecordId: message.JobId,
                parentTimelineRecordId: null,
                recordType: ExecutionContextType.Job,
                displayName: message.JobName,
                refName: message.JobRefName,
                order: null); // The job timeline record's order is set by server.

            // Logger (must be initialized before writing warnings).
            _logger = HostContext.CreateService <IPagingLogger>();
            _logger.Setup(_mainTimelineId, _record.Id);

            // Log warnings from recursive variable expansion.
            warnings?.ForEach(x => this.Warning(x));

            // Verbosity (from system.debug).
            WriteDebug = Variables.System_Debug ?? false;

            // Hook up JobServerQueueThrottling event, we will log warning on server tarpit.
            _jobServerQueue.JobServerQueueThrottling += JobServerQueueThrottling_EventReceived;
        }
Example #31
0
 public HttpProduct(HttpClient client, Endpoints endpoints)
 {
     _client            = client;
     client.BaseAddress = new Uri(endpoints.GetEndpoint(Endpoints.EndpointKey.Produtos));
 }
Example #32
0
 public PetSteps(Settings settings, Endpoints endpoints)
 {
     this.settings  = settings;
     this.endpoints = endpoints;
 }
Example #33
0
        public ActionResult AppIntegration()
        {
            var endpoints = Endpoints.Create(
                HttpContext.Request.Headers["Host"],
                HttpContext.Request.ApplicationPath,
                Configuration.Global.HttpPort,
                Configuration.Global.HttpsPort);

            var list = new Dictionary <string, string>();

            // federation metadata
            if (Configuration.FederationMetadata.Enabled)
            {
                list.Add("WS-Federation metadata", endpoints.WSFederationMetadata.AbsoluteUri);
            }

            // ws-federation
            if (Configuration.WSFederation.Enabled)
            {
                if (Configuration.WSFederation.EnableAuthentication)
                {
                    list.Add("WS-Federation", endpoints.WSFederation.AbsoluteUri);
                }
                if (Configuration.WSFederation.EnableFederation)
                {
                    list.Add("WS-Federation HRD", endpoints.WSFederationHRD.AbsoluteUri);
                    list.Add("OAuth2 Callback", endpoints.OAuth2Callback.AbsoluteUri);
                }
            }

            // ws-trust
            if (Configuration.WSTrust.Enabled)
            {
                list.Add("WS-Trust metadata", endpoints.WSTrustMex.AbsoluteUri);

                if (Configuration.WSTrust.EnableMessageSecurity)
                {
                    list.Add("WS-Trust message security (user name)", endpoints.WSTrustMessageUserName.AbsoluteUri);

                    if (Configuration.WSTrust.EnableClientCertificateAuthentication)
                    {
                        list.Add("WS-Trust message security (client certificate)", endpoints.WSTrustMessageCertificate.AbsoluteUri);
                    }
                }

                if (Configuration.WSTrust.EnableMixedModeSecurity)
                {
                    list.Add("WS-Trust mixed mode security (user name)", endpoints.WSTrustMixedUserName.AbsoluteUri);

                    if (Configuration.WSTrust.EnableClientCertificateAuthentication)
                    {
                        list.Add("WS-Trust mixed mode security (client certificate)", endpoints.WSTrustMixedCertificate.AbsoluteUri);
                    }
                }
            }

            // openid connect
            if (Configuration.OpenIdConnect.Enabled)
            {
                list.Add("OpenID Connect Authorize", endpoints.OidcAuthorize.AbsoluteUri);
                list.Add("OpenID Connect Token", endpoints.OidcToken.AbsoluteUri);
                list.Add("OpenID Connect UserInfo", endpoints.OidcUserInfo.AbsoluteUri);
            }

            // oauth2
            if (Configuration.OAuth2.Enabled)
            {
                if (Configuration.OAuth2.EnableImplicitFlow)
                {
                    list.Add("OAuth2 Authorize", endpoints.OAuth2Authorize.AbsoluteUri);
                }
                if (Configuration.OAuth2.EnableResourceOwnerFlow)
                {
                    list.Add("OAuth2 Token", endpoints.OAuth2Token.AbsoluteUri);
                }
            }

            // adfs integration
            if (Configuration.AdfsIntegration.Enabled)
            {
                if (Configuration.AdfsIntegration.UsernameAuthenticationEnabled ||
                    Configuration.AdfsIntegration.SamlAuthenticationEnabled ||
                    Configuration.AdfsIntegration.JwtAuthenticationEnabled)
                {
                    list.Add("ADFS Integration", endpoints.AdfsIntegration.AbsoluteUri);
                }
            }

            // simple http
            if (Configuration.SimpleHttp.Enabled)
            {
                list.Add("Simple HTTP", endpoints.SimpleHttp.AbsoluteUri);
            }

            return(View(list));
        }
Example #34
0
 public PublisherApp()
 {
     Endpoints.ListenAtPort(2211);
 }
 public bool IsEndpointSet(AzureEnvironment.Endpoint endpoint)
 {
     return(Endpoints.IsPropertySet(endpoint));
 }
 public AuthenticatedHttpClientHandler(Endpoints endpoints, NetworkCredential credentials)
 {
     credentials_ = credentials;
     endpoints_   = endpoints;
 }
Example #37
0
 public CountriesApi(Endpoints endPoints, IApiClient apiClient, IJsonSerializer serializer, Credentials credentials)
     : base(apiClient, serializer, credentials, endPoints.LoggedIn)
 {
     this.endPoints = endPoints.Countries;
 }
 private MiniClusterNode CreateNode(int index, Endpoints endpoints, IPEndPoint[] gossipSeeds)
 {
     _projections = new ProjectionsSubsystem(1, runProjections: ProjectionType.All, developmentMode: false);
     var node = new MiniClusterNode(
         PathName, index, endpoints.InternalTcp, endpoints.InternalTcpSec, endpoints.InternalHttp, endpoints.ExternalTcp,
         endpoints.ExternalTcpSec, endpoints.ExternalHttp, skipInitializeStandardUsersCheck: false,
         subsystems: new ISubsystem[] {_projections}, gossipSeeds: gossipSeeds);
     WaitIdle();
     return node;
 }
Example #39
0
 /// <summary>
 /// Returns a text representation of the existing values segment.
 /// </summary>
 /// <returns>A representation of the existing values segment.</returns>
 public override string ToString()
 {
     return string.Format(
         "Existing Values: {0}",
         string.Join(" and ", Endpoints.Select(x => x.ToString())));
 }
Example #40
0
            public TheIsAvailableMethod()
            {
                var endpoints = new Endpoints(ApiEnvironment.Staging);

                statusApi = new StatusApi(endpoints, apiClient);
            }
        /// <summary>
        /// Factory method to apply memcache required configuration based on the installed SDK version.
        /// </summary>
        /// <param name="azureService">The azure service instance</param>
        /// <param name="webRole">The web role to enable caching on</param>
        /// <param name="isWebRole">Flag indicating if the provided role is web or not</param>
        /// <param name="cacheWorkerRole">The memcache worker role name</param>
        /// <param name="startup">The role startup</param>
        /// <param name="endpoints">The role endpoints</param>
        /// <param name="localResources">The role local resources</param>
        /// <param name="configurationSettings">The role configuration settings</param>
        /// <param name="sdkVersion">The current SDK version</param>
        private void CachingConfigurationFactoryMethod(
            AzureService azureService,
            string roleName,
            bool isWebRole,
            string cacheWorkerRole,
            Startup startup,
            Endpoints endpoints,
            LocalResources localResources,
            ref DefConfigurationSetting[] configurationSettings,
            string sdkVersion)
        {
            switch (sdkVersion)
            {
                case SDKVersion.Version180:
                    Version180Configuration(
                        azureService,
                        roleName,
                        isWebRole,
                        cacheWorkerRole,
                        startup,
                        endpoints,
                        localResources,
                        ref configurationSettings);
                    break;

                default:
                    throw new Exception(string.Format(Resources.AzureSdkVersionNotSupported,
                        Resources.MinSupportAzureSdkVersion, Resources.MaxSupportAzureSdkVersion));
            }
        }
        public override async Task TestFixtureSetUp()
        {
            await base.TestFixtureSetUp();

#if (!DEBUG)
            Assert.Ignore("These tests require DEBUG conditional");
#else
            _nodeEndpoints[0] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
            _nodeEndpoints[1] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
            _nodeEndpoints[2] = new Endpoints(
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
                PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));

            _nodes[0] = CreateNode(0,
                                   _nodeEndpoints[0], new[] { _nodeEndpoints[1].InternalHttp, _nodeEndpoints[2].InternalHttp });
            _nodes[1] = CreateNode(1,
                                   _nodeEndpoints[1], new[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[2].InternalHttp });
            _nodes[2] = CreateNode(2,
                                   _nodeEndpoints[2], new[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[1].InternalHttp });
            WaitIdle();

            var projectionsStarted = _projections.Select(p => SystemProjections.Created(p.MasterMainBus)).ToArray();

            foreach (var node in _nodes)
            {
                node.Start();
                node.WaitIdle();
            }

            await Task.WhenAll(_nodes.Select(x => x.Started)).WithTimeout(TimeSpan.FromSeconds(30));

            _conn = EventStoreConnection.Create(_nodes[0].ExternalTcpEndPoint);
            await _conn.ConnectAsync().WithTimeout();

            _manager = new ProjectionsManager(
                new ConsoleLogger(),
                _nodes.Single(x => x.NodeState == VNodeState.Master).ExternalHttpEndPoint,
                TimeSpan.FromMilliseconds(10000));

            if (GivenStandardProjectionsRunning())
            {
                await Task.WhenAny(projectionsStarted).WithTimeout(TimeSpan.FromSeconds(10));
                await EnableStandardProjections().WithTimeout(TimeSpan.FromMinutes(2));
            }

            WaitIdle();

            try {
                await Given().WithTimeout();
            } catch (Exception ex) {
                throw new Exception("Given Failed", ex);
            }

            try {
                await When().WithTimeout();
            } catch (Exception ex) {
                throw new Exception("When Failed", ex);
            }
#endif
        }
Example #43
0
        public static void Execute()
        {
            dynamic endpoints = new Endpoints(Credentials.Default.ClientId, Credentials.Default.ClientSecret, Credentials.Default.Sandbox);

            var chargeBody = new {
                items = new[] {
                    new {
                        name = "Product 1",
                        value = 1000,
                        amount = 2
                    }
                },
                shippings = new[] {
                    new {
                        name = "Default Shipping Cost",
                        value = 100
                    },
                    new {
                        name = "Adicional Shipping Cost",
                        value = 150
                    }
                }
            };

            var paymentBody = new {
                payment = new {
                    credit_card = new {
                        installments = 1,
                        payment_token = "8c888fe1e7d96112020cf9fcf5e4db5b9dba5cf6",
                        billing_address = new {
                            street = "Av. JK",
                            number = 909,
                            neighborhood = "Bauxita",
                            zipcode = "35400000",
                            city = "Ouro Preto",
                            state = "MG"
                        },
                        customer = new {
                            name = "Gorbadoc Oldbuck",
                            email = "*****@*****.**",
                            cpf = "04267484171",
                            birth = "1977-01-15",
                            phone_number = "5144916523"
                        }
                    }
                }
            };

            try
            {
                var chargeResponse = endpoints.CreateCharge(null, chargeBody);
                Console.WriteLine(chargeResponse);

                var paymentResponse = endpoints.PayCharge(new {
                    id = chargeResponse.data.charge_id
                }, paymentBody);
                Console.WriteLine(paymentResponse);
            }
            catch (GnException e)
            {
                Console.WriteLine(e.ErrorType);
                Console.WriteLine(e.Message);
            }
        }
Example #44
0
 /// <summary> Deregister a given callback for a given function. </summary>
 /// <param name="endpoint"></param>
 /// <param name="handler"></param>
 public void DeregisterEndpointCallback(Endpoints endpoint, EventHandler<MessageReceivedEventArgs> handler)
 {
     if (endpointEvents.ContainsKey(endpoint)
         && endpointEvents[endpoint] != null)
     {
         endpointEvents[endpoint] -= handler;
     }
 }
Example #45
0
 public static Uri GetUri(Endpoints endpoint, params object[] args)
 {
     Uri retval;
     var type = typeof(Endpoints);
     var memInfo = type.GetMember(endpoint.ToString());
     var attributes = memInfo[0].GetCustomAttributes(typeof(EndPointUrlAttribute),
         false);
     var endpointString = ((EndPointUrlAttribute)attributes[0]).EndpointString;
     return Uri.TryCreate(String.Format(endpointString, args), UriKind.RelativeOrAbsolute, out retval) ? retval : null;
 }
Example #46
0
 /// <summary> Send a message to the connected Pebble.  
 /// The payload should at most be 2048 bytes large.
 /// </summary>
 /// <remarks>
 /// Yes, the docs at developers.getpebble.com say 4 kB.  I've received some errors from the Pebble that indicated 2 kB
 /// and that's what I'll assume for the time being.
 /// </remarks>
 /// <param name="endpoint"></param>
 /// <param name="payload"></param>
 /// <exception cref="ArgumentOutOfRangeException">Passed on when the payload is too large.</exception>
 void sendMessage(Endpoints endpoint, byte[] payload)
 {
     try
     {
         pebbleProt.sendMessage((ushort)endpoint, payload);
     }
     catch (TimeoutException e)
     {
         Disconnect();
     }
 }
Example #47
0
 public SteamGamesService(IOptions <Endpoints> endpoints)
 {
     _endpoints = endpoints.Value;
 }
Example #48
0
 public ProjectsApi(Endpoints endPoints, IApiClient apiClient, IJsonSerializer serializer, Credentials credentials)
     : base(apiClient, serializer, credentials, endPoints.LoggedIn)
 {
     this.endPoints        = endPoints.Projects;
     this.reportsEndPoints = endPoints.ReportsEndpoints.Projects;
 }
Example #49
0
        public AccountService(HttpClient client, ITokenStorageService tokenStorage, ILogger <AccountService> logger, Endpoints endpoints)
        {
            _tokenStorage      = tokenStorage;
            _logger            = logger;
            client.BaseAddress = new System.Uri(endpoints.Identity);
            if (_tokenStorage.Token != null)
            {
                _isAuthHeaderSet = true;
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_tokenStorage.Token.RawToken}");
            }

            Client = client;
        }
 static LocalSubscriptionCache()
 {
     Endpoints = new Endpoints();
 }
 public void RemoveEndpoint(Endpoint endpoint)
 {
     endpoint.AssignDefenceAdvocate(null);
     Endpoints.Remove(endpoint);
     UpdatedDate = DateTime.UtcNow;
 }
 public WSFederationMetadataGenerator(Endpoints endpoints, IConfigurationRepository configurationRepository, IUserRepository userRepository)
 {
     _endpoints = endpoints;
     _configurationRepository = configurationRepository;
     _userRepository = userRepository;
 }
Example #53
0
 public void OnEndpoints(IApplicationBuilder app) => Endpoints?.Invoke(app);
        private static void CacheClientCommonConfiguration(
            CloudServiceProject cloudServiceProject,
            string roleName,
            bool isWebRole,
            string cacheWorkerRole,
            Startup startup,
            Endpoints endpoints,
            LocalResources localResources,
            ref DefinitionConfigurationSetting[] configurationSettings)
        {
            if (isWebRole)
            {
                // Generate cache scaffolding for web role
                cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WebRole.ToString()),
                    roleName, new Dictionary<string, object>());

                // Adjust web.config to enable auto discovery for the caching role.
                string webCloudConfigPath = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebCloudConfig);
                string webConfigPath = Path.Combine(cloudServiceProject.Paths.RootPath, roleName, Resources.WebConfigTemplateFileName);

                UpdateWebConfig(roleName, cacheWorkerRole, webCloudConfigPath);
                UpdateWebConfig(roleName, cacheWorkerRole, webConfigPath);
            }
            else
            {
                // Generate cache scaffolding for worker role
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters[ScaffoldParams.RoleName] = cacheWorkerRole;

                cloudServiceProject.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WorkerRole.ToString()),
                    roleName, parameters);
            }

            // Add default memcache internal endpoint.
            InternalEndpoint memcacheEndpoint = new InternalEndpoint
            {
                name = Resources.MemcacheEndpointName,
                protocol = InternalProtocol.tcp,
                port = Resources.MemcacheEndpointPort
            };
            endpoints.InternalEndpoint = GeneralUtilities.ExtendArray<InternalEndpoint>(endpoints.InternalEndpoint, memcacheEndpoint);

            // Enable cache diagnostic
            LocalStore localStore = new LocalStore
            {
                name = Resources.CacheDiagnosticStoreName,
                cleanOnRoleRecycle = false
            };
            localResources.LocalStorage = GeneralUtilities.ExtendArray<LocalStore>(localResources.LocalStorage, localStore);

            DefinitionConfigurationSetting diagnosticLevel = new DefinitionConfigurationSetting { name = Resources.CacheClientDiagnosticLevelAssemblyName };
            configurationSettings = GeneralUtilities.ExtendArray<DefinitionConfigurationSetting>(configurationSettings, diagnosticLevel);

            // Add ClientDiagnosticLevel setting to service configuration.
            AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetCloudConfigRole(roleName));
            AddClientDiagnosticLevelToConfig(cloudServiceProject.Components.GetLocalConfigRole(roleName));
        }
 internal StorageAccountData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, IDictionary <string, string> tags, AzureLocation location, Models.Sku sku, Kind?kind, ManagedServiceIdentity identity, ExtendedLocation extendedLocation, ProvisioningState?provisioningState, Endpoints primaryEndpoints, string primaryLocation, AccountStatus?statusOfPrimary, DateTimeOffset?lastGeoFailoverTime, string secondaryLocation, AccountStatus?statusOfSecondary, DateTimeOffset?creationTime, CustomDomain customDomain, SasPolicy sasPolicy, KeyPolicy keyPolicy, KeyCreationTime keyCreationTime, Endpoints secondaryEndpoints, Encryption encryption, AccessTier?accessTier, AzureFilesIdentityBasedAuthentication azureFilesIdentityBasedAuthentication, bool?enableHttpsTrafficOnly, NetworkRuleSet networkRuleSet, bool?isSftpEnabled, bool?isLocalUserEnabled, bool?isHnsEnabled, GeoReplicationStats geoReplicationStats, bool?failoverInProgress, LargeFileSharesState?largeFileSharesState, IReadOnlyList <PrivateEndpointConnectionData> privateEndpointConnections, RoutingPreference routingPreference, BlobRestoreStatus blobRestoreStatus, bool?allowBlobPublicAccess, MinimumTlsVersion?minimumTlsVersion, bool?allowSharedKeyAccess, bool?enableNfsV3, bool?allowCrossTenantReplication, bool?defaultToOAuthAuthentication, PublicNetworkAccess?publicNetworkAccess, ImmutableStorageAccount immutableStorageWithVersioning, AllowedCopyScope?allowedCopyScope) : base(id, name, type, systemData, tags, location)
 {
     Sku                 = sku;
     Kind                = kind;
     Identity            = identity;
     ExtendedLocation    = extendedLocation;
     ProvisioningState   = provisioningState;
     PrimaryEndpoints    = primaryEndpoints;
     PrimaryLocation     = primaryLocation;
     StatusOfPrimary     = statusOfPrimary;
     LastGeoFailoverTime = lastGeoFailoverTime;
     SecondaryLocation   = secondaryLocation;
     StatusOfSecondary   = statusOfSecondary;
     CreationTime        = creationTime;
     CustomDomain        = customDomain;
     SasPolicy           = sasPolicy;
     KeyPolicy           = keyPolicy;
     KeyCreationTime     = keyCreationTime;
     SecondaryEndpoints  = secondaryEndpoints;
     Encryption          = encryption;
     AccessTier          = accessTier;
     AzureFilesIdentityBasedAuthentication = azureFilesIdentityBasedAuthentication;
     EnableHttpsTrafficOnly     = enableHttpsTrafficOnly;
     NetworkRuleSet             = networkRuleSet;
     IsSftpEnabled              = isSftpEnabled;
     IsLocalUserEnabled         = isLocalUserEnabled;
     IsHnsEnabled               = isHnsEnabled;
     GeoReplicationStats        = geoReplicationStats;
     FailoverInProgress         = failoverInProgress;
     LargeFileSharesState       = largeFileSharesState;
     PrivateEndpointConnections = privateEndpointConnections;
     RoutingPreference          = routingPreference;
     BlobRestoreStatus          = blobRestoreStatus;
     AllowBlobPublicAccess      = allowBlobPublicAccess;
     MinimumTlsVersion          = minimumTlsVersion;
     AllowSharedKeyAccess       = allowSharedKeyAccess;
     EnableNfsV3 = enableNfsV3;
     AllowCrossTenantReplication    = allowCrossTenantReplication;
     DefaultToOAuthAuthentication   = defaultToOAuthAuthentication;
     PublicNetworkAccess            = publicNetworkAccess;
     ImmutableStorageWithVersioning = immutableStorageWithVersioning;
     AllowedCopyScope = allowedCopyScope;
 }
        /// <summary>
        /// Applies required configuration for enabling cache in SDK 1.8.0 version by:
        /// * Add MemcacheShim runtime installation.
        /// * Add startup task to install memcache shim on the client side.
        /// * Add default memcache internal endpoint.
        /// * Add cache diagnostic to local resources.
        /// * Add ClientDiagnosticLevel setting to service configuration.
        /// * Adjust web.config to enable auto discovery for the caching role.
        /// </summary>
        /// <param name="azureService">The azure service instance</param>
        /// <param name="webRole">The web role to enable caching on</param>
        /// <param name="isWebRole">Flag indicating if the provided role is web or not</param>
        /// <param name="cacheWorkerRole">The memcache worker role name</param>
        /// <param name="startup">The role startup</param>
        /// <param name="endpoints">The role endpoints</param>
        /// <param name="localResources">The role local resources</param>
        /// <param name="configurationSettings">The role configuration settings</param>
        private void Version180Configuration(
            AzureService azureService,
            string roleName,
            bool isWebRole,
            string cacheWorkerRole,
            Startup startup,
            Endpoints endpoints,
            LocalResources localResources,
            ref DefConfigurationSetting[] configurationSettings)
        {
            if (isWebRole)
            {
                // Generate cache scaffolding for web role
                azureService.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WebRole.ToString()),
                    roleName, new Dictionary<string, object>());

                // Adjust web.config to enable auto discovery for the caching role.
                string webCloudConfigPath = Path.Combine(azureService.Paths.RootPath, roleName, Resources.WebCloudConfig);
                string webConfigPath = Path.Combine(azureService.Paths.RootPath, roleName, Resources.WebConfigTemplateFileName);

                UpdateWebConfig(roleName, cacheWorkerRole, webCloudConfigPath);
                UpdateWebConfig(roleName, cacheWorkerRole, webConfigPath);
            }
            else
            {
                // Generate cache scaffolding for worker role
                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters[ScaffoldParams.RoleName] = cacheWorkerRole;

                azureService.GenerateScaffolding(Path.Combine(Resources.CacheScaffolding, RoleType.WorkerRole.ToString()),
                    roleName, parameters);
            }

            // Add startup task to install memcache shim on the client side.
            string cacheRuntimeUri = CloudRuntimeCollection.GetRuntimeUrl(Resources.CacheRuntimeValue, CacheRuntimeVersion);
            Debug.Assert(!string.IsNullOrEmpty(cacheRuntimeUri));
            Variable emulated = new Variable { name = Resources.EmulatedKey, RoleInstanceValue = new RoleInstanceValueElement { xpath = "/RoleEnvironment/Deployment/@emulated" } };
            Variable[] env = { emulated, new Variable { name = Resources.CacheRuntimeUrl, value = cacheRuntimeUri } };
            Task shimStartupTask = new Task { Environment = env, commandLine = Resources.CacheStartupCommand, executionContext = ExecutionContext.elevated };
            startup.Task = CloudServiceUtilities.ExtendArray<Task>(startup.Task, shimStartupTask);

            // Add default memcache internal endpoint.
            InternalEndpoint memcacheEndpoint = new InternalEndpoint
            {
                name = Resources.MemcacheEndpointName,
                protocol = InternalProtocol.tcp,
                port = Resources.MemcacheEndpointPort
            };
            endpoints.InternalEndpoint = CloudServiceUtilities.ExtendArray<InternalEndpoint>(endpoints.InternalEndpoint, memcacheEndpoint);

            // Enable cache diagnostic
            LocalStore localStore = new LocalStore
            {
                name = Resources.CacheDiagnosticStoreName,
                cleanOnRoleRecycle = false
            };
            localResources.LocalStorage = CloudServiceUtilities.ExtendArray<LocalStore>(localResources.LocalStorage, localStore);

            DefConfigurationSetting diagnosticLevel = new DefConfigurationSetting { name = Resources.CacheClientDiagnosticLevelAssemblyName };
            configurationSettings = CloudServiceUtilities.ExtendArray<DefConfigurationSetting>(configurationSettings, diagnosticLevel);

            // Add ClientDiagnosticLevel setting to service configuration.
            AddClientDiagnosticLevelToConfig(azureService.Components.GetCloudConfigRole(roleName));
            AddClientDiagnosticLevelToConfig(azureService.Components.GetLocalConfigRole(roleName));
        }
Example #57
0
        /// <summary>
        /// Initializes a new instance of the ConnectViewModel class.
        /// </summary>
        public ConnectViewModel()
        {
            _dialogHandler = new DialogHandler();
            Endpoints      = new ObservableCollection <ConfigurationWithId>(GlobalStore.Endpoints);
            SelectedIndex  = Endpoints.IndexOf(Endpoints.FirstOrDefault(ep => ep.Equals(GlobalStore.SelectedEndpoint)));
            SelectCommand  = new RelayCommand(async() =>
            {
                if (SelectedIndex < 0)
                {
                    return;
                }
                ClientResponseWithObject <Status> response = null;
                bool IsSuccessFul = false;
                await
                _dialogHandler.Show(new ProgressDialog(), "ConnectDialog",
                                    async(object s, DialogOpenedEventArgs arg) =>
                {
                    try
                    {
                        var statusManager = new StatusManager(Endpoints[SelectedIndex]);
                        response          = await statusManager.GetStatusAsync();
                        IsSuccessFul      = response.IsSuccessful;
                    }
                    catch (Exception exception)
                    {
                        IsSuccessFul = false;
                    }
                    finally
                    {
                        arg.Session.Close();
                    }
                });


                if (IsSuccessFul)
                {
                    var tauVersion        = Assembly.GetExecutingAssembly().GetName().Version;
                    var apiVersion        = Version.Parse(response.ApiVersion);
                    var isVersionMismatch = tauVersion.Major != apiVersion.Major || tauVersion.Minor != apiVersion.Minor;
                    object result         = null;
                    if (isVersionMismatch)
                    {
                        result = await _dialogHandler.Show(new CommonDialog
                        {
                            DataContext =
                                new CommonDialogViewModel
                            {
                                Buttons = ButtonsEnum.YesNo,
                                Header  = "Warning! Version mismatch.",
                                Content = new Message($"Api version: {apiVersion}{Environment.NewLine}Tau version:{tauVersion}.{Environment.NewLine}Would you like to continue?")
                            }
                        }, "ConnectDialog");
                    }
                    if (!isVersionMismatch || (CommonDialogResult)result == CommonDialogResult.Yes)
                    {
                        GlobalStore.SelectedEndpoint = Endpoints[SelectedIndex];
                        await((ViewModelLocator)App.Current.Resources["Locator"]).EndpointUpdate();
                        var mainVindow         = new MainWindow();
                        var connectWindow      = App.Current.MainWindow;
                        App.Current.MainWindow = mainVindow;
                        mainVindow.Show();
                        connectWindow.Close();
                    }
                }
                else
                {
                    await
                    _dialogHandler.Show(
                        new CommonDialog
                    {
                        DataContext =
                            new CommonDialogViewModel
                        {
                            Header  = "Warning!",
                            Content = new Message(
                                $"Failed to connect to selected endpoint.{Environment.NewLine}{(response?.Errors == null ? "" : string.Join(Environment.NewLine, response.Errors.Errors))}"),
                            Buttons = ButtonsEnum.Ok
                        }
                    }, "ConnectDialog");
                }
            });
            NewCommand = new RelayCommand(async() =>
            {
                var context = new CommonDialogViewModel
                {
                    Buttons = ButtonsEnum.OkCancel,
                    Header  = "Create new endpoint",
                    Content = new JContent(new { ApiBaseEndpoint = new Uri("https://europe.slamby.com/"), ApiSecret = "", ParallelLimit = 0, BulkSize = 1000 })
                };
                var view = new CommonDialog {
                    DataContext = context
                };
                var canClose = false;
                var result   = await _dialogHandler.Show(view, "ConnectDialog",
                                                         async(object sender, DialogClosingEventArgs args) =>
                {
                    if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Ok)
                    {
                        args.Cancel();
                        args.Session.UpdateContent(new ProgressDialog());
                        var IsSuccessFul = false;
                        var errorMessage = "";
                        try
                        {
                            var statusManager = new StatusManager(((JContent)context.Content).GetJToken().ToObject <Configuration>());
                            var response      = await statusManager.GetStatusAsync();
                            IsSuccessFul      = response.IsSuccessful;
                        }
                        catch (Exception exception)
                        {
                            IsSuccessFul = false;
                            errorMessage = exception is JsonReaderException ? exception.Message : "Failed to connect to selected endpoint!";
                        }
                        finally
                        {
                            if (!IsSuccessFul)
                            {
                                context.ErrorMessage = string.IsNullOrEmpty(errorMessage) ? "Failed to connect to selected endpoint!" : errorMessage;
                                context.ShowError    = true;
                                args.Session.UpdateContent(view);
                            }
                            else
                            {
                                canClose = true;
                                args.Session.Close((CommonDialogResult)args.Parameter);
                            }
                        }
                    }
                });
                if ((CommonDialogResult)result == CommonDialogResult.Ok)
                {
                    var newEndpoint = ((JContent)context.Content).GetJToken().ToObject <ConfigurationWithId>();
                    Endpoints.Add(newEndpoint);
                    GlobalStore.Endpoints = Endpoints.ToList();
                }
            });
            EditCommand = new RelayCommand(async() =>
            {
                if (SelectedIndex < 0)
                {
                    return;
                }
                var isSelectedInUse = Endpoints[SelectedIndex].Equals(GlobalStore.SelectedEndpoint);
                var context         = new CommonDialogViewModel
                {
                    Buttons = ButtonsEnum.OkCancel,
                    Header  = "Create new endpoint",
                    Content = new JContent(new { Endpoints[SelectedIndex].ApiBaseEndpoint, Endpoints[SelectedIndex].ApiSecret, Endpoints[SelectedIndex].ParallelLimit, Endpoints[SelectedIndex].BulkSize })
                };
                var view = new CommonDialog {
                    DataContext = context
                };
                var canClose = false;
                var result   = await _dialogHandler.Show(view, "ConnectDialog",
                                                         async(object sender, DialogClosingEventArgs args) =>
                {
                    if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Ok)
                    {
                        args.Cancel();
                        args.Session.UpdateContent(new ProgressDialog());
                        var IsSuccessFul = false;
                        try
                        {
                            var statusManager = new StatusManager(((JContent)context.Content).GetJToken().ToObject <Configuration>());
                            var response      = await statusManager.GetStatusAsync();
                            IsSuccessFul      = response.IsSuccessful;
                        }
                        catch (Exception)
                        {
                            IsSuccessFul = false;
                        }
                        finally
                        {
                            if (!IsSuccessFul)
                            {
                                context.ErrorMessage = "Failed to connect to selected endpoint!";
                                context.ShowError    = true;
                                args.Session.UpdateContent(view);
                            }
                            else
                            {
                                canClose = true;
                                args.Session.Close((CommonDialogResult)args.Parameter);
                            }
                        }
                    }
                });
                if ((CommonDialogResult)result == CommonDialogResult.Ok)
                {
                    var modifiedEndpoint     = ((JContent)context.Content).GetJToken().ToObject <ConfigurationWithId>();
                    modifiedEndpoint.Id      = Endpoints[SelectedIndex].Id;
                    Endpoints[SelectedIndex] = modifiedEndpoint;
                    Endpoints             = new ObservableCollection <ConfigurationWithId>(Endpoints);
                    SelectedIndex         = Endpoints.IndexOf(modifiedEndpoint);
                    GlobalStore.Endpoints = Endpoints.ToList();
                    if (isSelectedInUse)
                    {
                        GlobalStore.SelectedEndpoint = Endpoints[SelectedIndex];
                        await((ViewModelLocator)App.Current.Resources["Locator"]).EndpointUpdate();
                        var mainVindow         = new MainWindow();
                        var connectWindow      = App.Current.MainWindow;
                        App.Current.MainWindow = mainVindow;
                        mainVindow.Show();
                        connectWindow.Close();
                    }
                }
            });
            DeleteCommand = new RelayCommand(async() =>
            {
                if (SelectedIndex < 0)
                {
                    return;
                }
                var context = new CommonDialogViewModel
                {
                    Buttons = ButtonsEnum.YesNo,
                    Header  = "Delete endpoint",
                    Content = new Message("Are you sure to delete the selected endpoint?")
                };
                var result = await _dialogHandler.Show(new CommonDialog {
                    DataContext = context
                }, "ConnectDialog");
                if ((CommonDialogResult)result == CommonDialogResult.Yes)
                {
                    Endpoints.RemoveAt(SelectedIndex);
                    SelectedIndex         = 0;
                    GlobalStore.Endpoints = Endpoints.ToList();
                }
            });
        }
 public WSFederationMetadataGenerator(Endpoints endpoints)
 {
     _endpoints = endpoints;
     Container.Current.SatisfyImportsOnce(this);
 }
Example #59
0
 public override Task AddOrUpdate(MusicEndpoint endpoint)
 {
     return(Endpoints.SaveChanges(endpoint));
 }