Example #1
0
        public async Task CountCalls_ShutDownWithCancel()
        {
            var mockProvider = new Mock <IHostedServiceProvider>();

            mockProvider.SetupGet(o => o.Delay).Returns(1000); // call provider every second

            var fakeLogger = NUnitOutputLogger.Create <IHostedServiceProvider>();

            var subject = new HostedService <IHostedServiceProvider>(mockProvider.Object, fakeLogger);

            var tokenSource = new CancellationTokenSource();

            tokenSource.CancelAfter(4150);

            await Task.Run(() =>
            {
                subject.StartAsync(tokenSource.Token);
                tokenSource.Token.WaitHandle.WaitOne();
            });

            await Task.Delay(250);

            mockProvider.Verify(o => o.StartupAsync(), Times.Exactly(1));
            mockProvider.Verify(o => o.DoPeriodicWorkAsync(), Times.Exactly(5));
            mockProvider.Verify(o => o.StopAsync(It.IsAny <CancellationToken>()), Times.Never);
        }
Example #2
0
        /// <summary>
        /// Generate a DPWSHostedService source file from a Wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateHostedService(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string hostedServiceClassName = serviceDesc.Name;
            string hostedServiceNs = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "HostedService.cs";

            HostedServices hostedServices = new HostedServices(hostedServiceNs);

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                HostedService hostedService = new HostedService(portType.Name, hostedServiceNs, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction = serviceDesc.TargetNamespace + "/" + operation.Name + "Request";
                    string outAction = serviceDesc.TargetNamespace + "/" + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    hostedService.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    hostedService.Messages.Add(message);
                }
            }

            HostedServiceGenerator hostedServiceGen = new HostedServiceGenerator();
            hostedServiceGen.GenerateCode(filename, hostedServices);
        }
        public void InitialDeployment(string user)
        {
            HostedService service = CreateNewAppDomain();

            current = service;
            service.InitialDeployment(user);
        }
        public IActionResult ResponseHpp()
        {
            // configure client & request settings
            var service = new HostedService(new GatewayConfig
            {
                MerchantId   = "addonnettest",
                AccountId    = "api",
                SharedSecret = "secret",
                ServiceUrl   = "https://hpp.sandbox.addonpayments.com/pay"
            });

            var responseJson = Request.Form["hppResponse"];

            try {
                // Obtenemos la respuesta
                Transaction response = service.ParseResponse(responseJson, true);

                var orderId           = response.OrderId;                         // GTI5Yxb0SumL_TkDMCAxQA
                var responseCode      = response.ResponseCode;                    // 00
                var responseMessage   = response.ResponseMessage;                 // [ test system ] Authorised
                var responseValues    = response.ResponseValues;                  // get values accessible by key
                var fraudFilterResult = responseValues["HPP_FRAUDFILTER_RESULT"]; // PASS


                return(Content(responseJson));
            }

            catch (ApiException exce) {
                RespuestaError respuesta = new RespuestaError {
                    resultado = "Error en el envĂ­o de datos <br><br>" + exce
                };
                return(BadRequest(respuesta));
            }
        }
Example #5
0
        public HostedService GetHostedService(String subscriptionId, List <Byte> certificateBytes, String serviceName)
        {
            HostedService azureService = null;

            try
            {
                String uri = String.Format(getServiceOperationFormat, subscriptionId, serviceName);

                ServiceManagementOperation operation = new ServiceManagementOperation(certificateBytes);

                XDocument hostedServiceProperties = operation.Invoke(uri);

                XmlSerializer serializer = new XmlSerializer(typeof(Bermuda.AdminLibrary.Models.HostedService));

                MemoryStream memStream = new MemoryStream();

                XmlWriter writer = XmlWriter.Create(memStream);

                hostedServiceProperties.Save(writer);

                writer.Close();

                memStream.Seek(0, SeekOrigin.Begin);

                azureService = (HostedService)serializer.Deserialize(memStream);
            }
            catch (Exception ex)
            {
                Logger.Write(string.Format("Error in GetHostedService()  Error: {0}", ex.Message));

                azureService = null;
            }

            return(azureService);
        }
        public IEnumerable <HostedService> GetHostedServices()
        {
            if (reader?.NameTable == null)
            {
                return(Enumerable.Empty <HostedService>());
            }

            var namespaceManager = new XmlNamespaceManager(reader.NameTable);

            namespaceManager.AddNamespace("azure", AzureNamespace);

            var data         = XElement.Load(reader);
            var nameElements = data.XPathSelectElements("//azure:ServiceName", namespaceManager)
                               .ToList();

            var hostedServices = new List <HostedService>();

            foreach (var nameElement in nameElements)
            {
                var resourceLocationElement = nameElement.XPathSelectElement("../azure:HostedServiceProperties/azure:ExtendedProperties/azure:ExtendedProperty[azure:Name = \"ResourceLocation\"]/azure:Value", namespaceManager);
                var resourceGroupElement    = nameElement.XPathSelectElement("../azure:HostedServiceProperties/azure:ExtendedProperties/azure:ExtendedProperty[azure:Name = \"ResourceGroup\"]/azure:Value", namespaceManager);
                var hostedService           = new HostedService(nameElement.Value, resourceLocationElement.Value, resourceGroupElement.Value);
                hostedServices.Add(hostedService);
            }

            return(hostedServices);
        }
        private void AddHostedServiceRoles(HostedService hostedService, string environment)
        {
            var deployment = service.GetDeployment(hostedService.ServiceName, environment, true);

            if ((deployment != null) && !string.IsNullOrEmpty(deployment.Name))
            {
                foreach (var role in deployment.RoleList)
                {
                    if (role == null)
                    {
                        continue;
                    }
                    this.MainView.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                         new Action(
                                                             () =>
                                                             this.MainView.Items.Add(
                                                                 new
                    {
                        HostedServiceName = hostedService.ServiceName,
                        Environment       = deployment.DeploymentSlot,
                        RoleName          = role.RoleName,
                        Role = role
                    })));
                }
            }
        }
        /// <summary>
        /// Determine if a service already exists.
        /// </summary>
        /// <returns>
        /// A value indicating whether the service already exists.
        /// </returns>
        /// <remarks>
        /// Service names are unique across Azure.
        /// </remarks>
        private bool ServiceExists()
        {
            Debug.Assert(
                !string.IsNullOrEmpty(_hostedServiceName),
                "_hostedServiceName cannot be null or empty.");
            Debug.Assert(
                !string.IsNullOrEmpty(subscriptionId),
                "subscriptionId cannot be null or empty.");
            Debug.Assert(
                !string.IsNullOrEmpty(_deploymentSettings.ServiceSettings.Slot),
                "Slot cannot be null.");

            SafeWriteObjectWithTimestamp(Resources.PublishConnectingMessage);

            // Check whether there's an existing service with the desired
            // name in the desired slot accessible from our subscription

            try
            {
                HostedService existingService = RetryCall(subscription => Channel.GetHostedServiceWithDetails(subscription, _hostedServiceName, true));
            }
            catch (EndpointNotFoundException)
            {
                return(false);
            }

            return(true);
        }
Example #9
0
        public IActionResult DccHpp()
        {
            // configure client & request settings
            var service = new HostedService(new GatewayConfig
            {
                MerchantId          = "addonnettest",
                AccountId           = "dcc",
                SharedSecret        = "secret",
                ServiceUrl          = "https://hpp.sandbox.addonpayments.com/pay",
                HostedPaymentConfig = new HostedPaymentConfig
                {
                    Version = "2",
                    DynamicCurrencyConversionEnabled = true
                }
            });

            try {
                // process an auto-capture authorization
                var hppJson = service.Charge(10.01m)
                              .WithCurrency("EUR")
                              .Serialize();


                return(Content(hppJson));
            }

            catch (ApiException exce) {
                RespuestaError respuesta = new RespuestaError {
                    resultado = "Error en el envĂ­o de datos <br><br>" + exce
                };
                return(BadRequest(respuesta));
            }
        }
Example #10
0
        private List <IPEndPoint> GetServiceEndpoints()
        {
            ClientOutputMessageInspector messageInspector;
            IServiceManagement           serviceProxy = ServiceInitializer.Get(this._cert, out messageInspector);

            WriteObject(String.Format(CultureInfo.InvariantCulture, Resources.FetchingEndpoints, ServiceName));
            HostedService hostedService = serviceProxy.GetHostedServiceProperties(this._subscriptionId, this.ServiceName);

            List <IPEndPoint> endPointsToTest = new List <IPEndPoint>();

            if (hostedService.Deployments != null && hostedService.Deployments.Length != 0)
            {
                foreach (Deployment eachDeployment in hostedService.Deployments)
                {
                    if (eachDeployment.RoleList != null && eachDeployment.RoleList.Length != 0)
                    {
                        foreach (Role eachRole in eachDeployment.RoleList)
                        {
                            if (eachRole.ConfigurationSets != null && eachRole.ConfigurationSets.Length != 0)
                            {
                                foreach (ConfigurationSet eachConfigSet in eachRole.ConfigurationSets)
                                {
                                    NetworkConfigurationSet networkConfigset = eachConfigSet as NetworkConfigurationSet;
                                    if (networkConfigset != null && networkConfigset.InputEndpoints != null && networkConfigset.InputEndpoints.Length != 0)
                                    {
                                        endPointsToTest.AddRange(networkConfigset.InputEndpoints.Select(eachEndpoint => new IPEndPoint(IPAddress.Parse(eachEndpoint.Vip), eachEndpoint.Port)));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(endPointsToTest);
        }
Example #11
0
        public ActionResult <HostedService> CreateService(HostedService service)
        {
            _dbContext.Services.Add(service);
            _dbContext.SaveChanges();

            return(CreatedAtRoute("GetById", new { id = service.Id }, service));
        }
Example #12
0
        /// <summary>
        /// Generate a DPWSHostedService source file from a Wsdl service description.
        /// </summary>
        /// <param name="serviceDesc">A valid wsdl service description.</param>
        public void GenerateHostedService(ServiceDescription serviceDesc, TargetPlatform platform)
        {
            // Well here's a nasty used in an attempt to make up a name
            string hostedServiceClassName = serviceDesc.Name;
            string hostedServiceNs        = CodeGenUtils.GenerateDotNetNamespace(serviceDesc.TargetNamespace);
            string filename = serviceDesc.Name + "HostedService.cs";

            HostedServices hostedServices = new HostedServices(hostedServiceNs);

            foreach (PortType portType in serviceDesc.PortTypes)
            {
                HostedService hostedService = new HostedService(portType.Name, hostedServiceNs, platform);
                foreach (Operation operation in portType.Operations)
                {
                    // Create action names
                    // Apply special naming rules if this is a notification (event) operation
                    string inAction  = serviceDesc.TargetNamespace + "/" + operation.Name + "Request";
                    string outAction = serviceDesc.TargetNamespace + "/" + operation.Name + ((operation.Messages.Flow == OperationFlow.Notification) ? "" : "Response");
                    hostedService.AddOperation(operation, inAction, outAction);
                }

                foreach (Message message in serviceDesc.Messages)
                {
                    hostedService.Messages.Add(message);
                }
            }

            HostedServiceGenerator hostedServiceGen = new HostedServiceGenerator();

            hostedServiceGen.GenerateCode(filename, hostedServices);
        }
Example #13
0
 public static void Main(string[] args)
 {
     HostedService.Create <Startup>(args)
     .UseRabbitMq()
     .Build()
     .RunAsync();
 }
Example #14
0
        static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            var configuration = BuildConfiguration();

            await HostedService.RunHostedService <ProcessMyJob>(s => s.ConfigureService(configuration), isService);
        }
Example #15
0
 public static void Main(string[] args)
 {
     HostedService.Create <Startup>(args)
     .UseRabbitMq()
     .SubscribeToEvent <ActivityCreated>()
     .Build()
     .Run();
 }
        public IActionResult FraudHpp()
        {
            // configure client & request settings
            var service = new HostedService(new GatewayConfig
            {
                MerchantId          = "addonnettest",
                AccountId           = "api",
                SharedSecret        = "secret",
                ServiceUrl          = "https://hpp.sandbox.addonpayments.com/pay",
                HostedPaymentConfig = new HostedPaymentConfig
                {
                    Version         = "2",
                    FraudFilterMode = FraudFilterMode.PASSIVE
                }
            });

            // Datos que deben transferirseal servidor de Addon Payments junto con las opciones de nivel de transacciĂłn
            var hostedPaymentData = new HostedPaymentData
            {
                CustomerNumber = "E8953893489",
                ProductId      = "SID9838383"
            };

            var billingAddress = new Address
            {
                Country    = "726",
                PostalCode = "50001|Flat 123"
            };

            var shippingAddress = new Address
            {
                Country    = "726",
                PostalCode = "654|123"
            };

            var variableReference = "Car Part HV";

            try {
                // process an auto-capture authorization
                var hppJson = service.Charge(19.99m)
                              .WithCurrency("EUR")
                              .WithHostedPaymentData(hostedPaymentData)
                              .WithAddress(billingAddress, AddressType.Billing)
                              .WithAddress(shippingAddress, AddressType.Shipping)
                              .WithClientTransactionId(variableReference)
                              .Serialize();


                return(Content(hppJson));
            }

            catch (ApiException exce) {
                RespuestaError respuesta = new RespuestaError {
                    resultado = "Error en el envĂ­o de datos <br><br>" + exce
                };
                return(BadRequest(respuesta));
            }
        }
Example #17
0
        public async Task AddNewHostedService(string serviceName)
        {
            var svc = new HostedService()
            {
                Name = serviceName
            };

            await _hostedServiceRepository.AddAsync(svc);
        }
        public static void Main(string[] args)
        {
            new Person();

            using (var server = new HostedService())
            {
                Console.ReadLine();
            }
        }
Example #19
0
        /// <summary>
        /// Removes all deployments in the given cloud service and the service itself.
        /// </summary>
        /// <param name="name">The cloud service name</param>
        public void RemoveCloudService(string name)
        {
            HostedService cloudService = GetCloudService(name);

            DeleteDeploymentIfExists(cloudService.ServiceName, DeploymentSlotType.Production);
            DeleteDeploymentIfExists(cloudService.ServiceName, DeploymentSlotType.Staging);

            WriteVerboseWithTimestamp(string.Format(Resources.RemoveAzureServiceWaitMessage, cloudService.ServiceName));
            CallSync(() => ServiceManagementChannel.DeleteHostedService(subscriptionId, cloudService.ServiceName));
        }
Example #20
0
        public void IncorrectSharedSecret()
        {
            var service = new HostedService(new GpEcomConfig {
                MerchantId   = "MerchantId",
                AccountId    = "internet",
                SharedSecret = "SharedSecret",
            });

            var responseJson = "{ \"MERCHANT_ID\": \"MerchantId\", \"ACCOUNT\": \"internet\", \"ORDER_ID\": \"GTI5Yxb0SumL_TkDMCAxQA\", \"AMOUNT\": \"1999\", \"TIMESTAMP\": \"20170725154824\", \"SHA1HASH\": \"841680654f377bfa845387fdbace35acc9d95778\", \"RESULT\": \"00\",  \"MERCHANT_RESPONSE_URL\": \"https://www.example.com/response\", \"AUTHCODE\": \"12345\", \"CARD_PAYMENT_BUTTON\": \"Place Order\", \"AVSADDRESSRESULT\": \"M\", \"AVSPOSTCODERESULT\": \"M\", \"BATCHID\": \"445196\", \"MESSAGE\": \"[ test system ] Authorised\", \"PASREF\": \"15011597872195765\", \"CVNRESULT\": \"M\"}";
            var response     = service.ParseResponse(responseJson, false);
        }
Example #21
0
        public void IncorrectEncodedResponse()
        {
            var service = new HostedService(new GpEcomConfig {
                MerchantId   = "MerchantId",
                AccountId    = "internet",
                SharedSecret = "secret",
            });

            var responseJson = "{ \"MERCHANT_ID\": \"TWVyY2hhbnRJZA==\", \"ACCOUNT\": \"aW50ZXJuZXQ=\", \"ORDER_ID\": \"R1RJNVl4YjBTdW1MX1RrRE1DQXhRQQ==\", \"AMOUNT\": \"MTk5OQ==\", \"TIMESTAMP\": \"MjAxNzA3MjUxNTQ4MjQ=\", \"SHA1HASH\": \"ODQzNjgwNjU0ZjM3N2JmYTg0NTM4N2ZkYmFjZTM1YWNjOWQ5NTc3OA==\", \"RESULT\": \"MDA=\",  \"MERCHANT_RESPONSE_URL\": \"aHR0cHM6Ly93d3cuZXhhbXBsZS5jb20vcmVzcG9uc2U=\", \"AUTHCODE\": \"MTIzNDU=\", \"CARD_PAYMENT_BUTTON\": \"UGxhY2UgT3JkZXI=\", \"AVSADDRESSRESULT\": \"TQ==\", \"AVSPOSTCODERESULT\": \"TQ==\", \"BATCHID\": \"NDQ1MTk2\", \"MESSAGE\": \"WyB0ZXN0IHN5c3RlbSBdIEF1dGhvcmlzZWQ=\", \"PASREF\": \"MTUwMTE1OTc4NzIxOTU3NjU=\", \"CVNRESULT\": \"TQ==\"}";
            var response     = service.ParseResponse(responseJson, false);
        }
Example #22
0
 public static void Main(string[] args)
 {
     HostedService.Create <Startup>(args)
     .UseRabbitMq()
     .SubscribeToCommand <CreateUser>()
     .SubscribeToCommand <AuthenticateUser>()
     .SubscribeToCommand <ResetPasswordCommand>()
     .SubscribeToCommand <AuthenticateUser>()
     .Build()
     .RunAsync();
 }
Example #23
0
        public void IncorrectOrderId()
        {
            var service = new HostedService(new GatewayConfig {
                MerchantId   = "MerchantId",
                AccountId    = "internet",
                SharedSecret = "secret",
                ServiceUrl   = "https://pay.sandbox.realexpayments.com/pay",
            });

            var responseJson = "{ \"MERCHANT_ID\": \"MerchantId\", \"ACCOUNT\": \"internet\", \"ORDER_ID\": \"N6qsk4kYRZihmPrTXWYS6g\", \"AMOUNT\": \"1999\", \"TIMESTAMP\": \"20170725154824\", \"SHA1HASH\": \"841680654f377bfa845387fdbace35acc9d95778\", \"RESULT\": \"00\",  \"MERCHANT_RESPONSE_URL\": \"https://www.example.com/response\", \"AUTHCODE\": \"54321\", \"CARD_PAYMENT_BUTTON\": \"Place Order\", \"AVSADDRESSRESULT\": \"M\", \"AVSPOSTCODERESULT\": \"M\", \"BATCHID\": \"445196\", \"MESSAGE\": \"[ test system ] Authorised\", \"PASREF\": \"15011597872195765\", \"CVNRESULT\": \"M\"}";
            var response     = service.ParseResponse(responseJson, false);
        }
Example #24
0
        public IEnumerable <HostedService> GetHostedServiceProcess(out Operation operation)
        {
            IEnumerable <HostedService>      hostedServices;
            Func <string, HostedService>     func            = null;
            Func <string, HostedServiceList> func1           = null;
            IEnumerable <HostedService>      hostedServices1 = null;

            operation = null;
            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    if (this.ServiceName == null)
                    {
                        GetAzureServiceCommand getAzureServiceCommand = this;
                        if (func1 == null)
                        {
                            func1 = (string s) => base.Channel.ListHostedServices(s);
                        }
                        hostedServices1 = ((CmdletBase <IServiceManagement>)getAzureServiceCommand).RetryCall <HostedServiceList>(func1);
                    }
                    else
                    {
                        HostedService[]        hostedServiceArray  = new HostedService[1];
                        HostedService[]        hostedServiceArray1 = hostedServiceArray;
                        int                    num = 0;
                        GetAzureServiceCommand getAzureServiceCommand1 = this;
                        if (func == null)
                        {
                            func = (string s) => base.Channel.GetHostedService(s, this.ServiceName);
                        }
                        hostedServiceArray1[num] = ((CmdletBase <IServiceManagement>)getAzureServiceCommand1).RetryCall <HostedService>(func);
                        hostedServices1          = hostedServiceArray;
                    }
                    operation = base.WaitForOperation(base.CommandRuntime.ToString());
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    if (communicationException as EndpointNotFoundException == null || base.IsVerbose())
                    {
                        this.WriteErrorDetails(communicationException);
                    }
                    else
                    {
                        hostedServices = null;
                        return(hostedServices);
                    }
                }
                return(hostedServices1);
            }
            return(hostedServices);
        }
Example #25
0
        internal static void LogObject(HostedService hostedService)
        {
            if (hostedService == null)
                return;

            if (!string.IsNullOrEmpty(hostedService.ServiceName))
                Console.WriteLine("HostedService Name:{0}", hostedService.ServiceName);

            Console.WriteLine("HostedService Url:{0}", hostedService.Url.ToString());
            LogObject(hostedService.HostedServiceProperties);
            LogObject(hostedService.Deployments);
        }
Example #26
0
 public GpEcomHppResponseTests()
 {
     _client  = new RealexHppClient("https://pay.sandbox.realexpayments.com/pay", "secret");
     _service = new HostedService(new GpEcomConfig {
         MerchantId          = "heartlandgpsandbox",
         AccountId           = "hpp",
         SharedSecret        = "secret",
         HostedPaymentConfig = new HostedPaymentConfig {
             Language    = "GB",
             ResponseUrl = "http://requestb.in/10q2bjb1"
         }
     });
 }
Example #27
0
 /// <summary>
 /// Connect to an Azure subscription and obtain service properties.
 /// </summary>
 protected override void AzureExecute()
 {
     try
     {
         HostedService hostedService = this.RetryCall(s => this.Channel.GetHostedService(s, this.ServiceName.Get(this.ActivityContext)));
         this.ServiceProperties.Set(this.ActivityContext, hostedService.HostedServiceProperties);
     }
     catch (EndpointNotFoundException ex)
     {
         this.LogBuildMessage(ex.Message);
         this.ServiceProperties.Set(this.ActivityContext, null);
     }
 }
Example #28
0
        /// <summary>
        /// Check if the deployment exists for given cloud service.
        /// </summary>
        /// <param name="name">The cloud service name</param>
        /// <param name="slot">The deployment slot name</param>
        /// <returns>Flag indicating the deployment exists or not</returns>
        public bool DeploymentExists(string name = null, string slot = null)
        {
            HostedService cloudService = GetCloudService(name);

            try
            {
                VerifyDeploymentExists(cloudService, slot);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #29
0
        public async Task AfterSelectedJourneysShouldAddJourneysToReadModel()
        {
            //Arrange
            var selectJourneysScenario = new SelectJourneysScenario(CommandBus);

            //Act
            await HostedService.StartAsync(CancellationToken.None);

            await selectJourneysScenario.Execute();

            await HostedService.StopAsync(CancellationToken.None);

            var bookingId = selectJourneysScenario.BookingId;
        }
Example #30
0
        protected override void OnStart(string[] args)
        {
            var exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            Directory.SetCurrentDirectory(exeDirectory);

            _stopEvent = new ManualResetEvent(false);

            _service = new HostedService(HostServices.Log, _stopEvent);

            _service.Start(null);

            base.OnStart(args);
        }
Example #31
0
        /// <summary>
        /// Checks if a cloud service exists or not.
        /// </summary>
        /// <param name="name">The cloud service name</param>
        /// <returns>True if exists, false otherwise</returns>
        public bool CloudServiceExists(string name)
        {
            HostedService cloudService = null;

            try
            {
                cloudService = ServiceManagementChannel.GetHostedServiceWithDetails(subscriptionId, name, true);
            }
            catch
            {
                return(false);
            }

            return(cloudService != null);
        }
Example #32
0
        private void SetCloudServiceState(string name, string slot, CloudServiceState state)
        {
            HostedService cloudService = GetCloudService(name);

            slot = GetSlot(slot);
            VerifyDeploymentExists(cloudService, slot);
            ServiceManagementChannel.UpdateDeploymentStatusBySlot(
                subscriptionId,
                cloudService.ServiceName,
                slot,
                new UpdateDeploymentStatusInput()
            {
                Status = state == CloudServiceState.Start ? DeploymentStatus.Running : DeploymentStatus.Suspended
            }
                );
        }
Example #33
0
 public void Start()
 {
     HostedService service = CreateNewAppDomain();
     current = service;
     try
     {
         service.Start();
     }
     catch (ReflectionTypeLoadException e)
     {
         var sb = new StringBuilder();
         foreach (var exception in e.LoaderExceptions)
         {
             sb.AppendLine(exception.ToString());
         }
         throw new TypeLoadException(sb.ToString(), e);
     }
 }
 /// <summary>
 /// Initials the deployment.
 /// </summary>
 /// <param name="user">The user.</param>
 public void InitialDeployment(string user)
 {
     _current = CreateNewAppDomain();
     _current.InitialDeployment(user);
 }
Example #35
0
 public void InitialDeployment(string user)
 {
     HostedService service = CreateNewAppDomain();
     current = service;
     service.InitialDeployment(user);
 }
 /// <summary>
 /// Starts this instance.
 /// </summary>
 /// <exception cref="System.TypeLoadException"></exception>
 public void Start()
 {
     _current = CreateNewAppDomain();
     try { _current.Start(); }
     catch (ReflectionTypeLoadException e)
     {
         var sb = new StringBuilder();
         foreach (var exception in e.LoaderExceptions)
             sb.AppendLine(exception.ToString());
         throw new TypeLoadException(sb.ToString(), e);
     }
 }
        public void Start()
        {
            HostedService service = CreateNewAppDomain();
            var watcher = new FileSystemWatcher(path);
            bool wasCalled = false;
            var @lock = new object();
            FileSystemEventHandler handler = (sender, e) =>
            {
                string extension = Path.GetExtension(e.FullPath);
                if (extension != ".dll" && extension != ".config" && extension != ".exe")
                    return;
                watcher.Dispose();
                lock (@lock)
                {
                    if (wasCalled)
                        return;
                    wasCalled = true;

                    logger.WarnFormat("Got change request for {0}, disposing current AppDomain",
                                      e.Name);
                    service.Stop();

                    Thread.Sleep(500); //allow for other events to happen
                    logger.Warn("Restarting...");
                    Start();
                }
            };
            watcher.Deleted += handler;
            watcher.Changed += handler;
            watcher.Created += handler;

            watcher.EnableRaisingEvents = true;

            current = service;

            try
            {
                service.Start();
            }
            catch (ReflectionTypeLoadException e)
            {
                var sb = new StringBuilder();
                foreach (var exception in e.LoaderExceptions)
                {
                    sb.AppendLine(exception.ToString());
                }
                throw new TypeLoadException(sb.ToString(), e);
            }
        }
Example #38
0
        /// <summary>
        /// CreateSourceFiles - Parse Wsdl Schema and generate DataContract, DataContractSerializer types,
        /// HostedServices and Client Proxies.
        /// </summary>
        /// <remarks>Currently only generates C# source files.</remarks>
        /// <param name="contractFilename">The name of a contract source code (.cs) file.</param>
        /// <param name="hostedServiceFilename">The name of a hosted service source code (.cs) file.</param>
        /// <param name="clientProxyFilename">The name of a client proxy source code (.cs) file.</param>
        /// <param name="targetPlatform">Specifies the target runtime platform.</param>
        public void CreateSourceFiles(string contractFilename, string hostedServiceFilename, string clientProxyFilename, TargetPlatform targetPlatform)
        {
            m_platform = targetPlatform;

            Logger.WriteLine("", LogLevel.Normal);
            Logger.WriteLine("Generating contract source: " + contractFilename + "...", LogLevel.Normal);

            if (contractFilename == null)
                throw new ArgumentNullException("codeFilename", "You must pass a valid code filename.");

            if (m_svcDesc.Types == null)
            {
                throw new Exception("No wsdl types found.");
            }

            string path = Path.GetDirectoryName(contractFilename).Trim();

            if(!string.IsNullOrEmpty(path) && !Directory.Exists(path)) 
            {
                Directory.CreateDirectory(path);
            }

            // Create code file stream
            FileStream dcStream = new FileStream(contractFilename, FileMode.Create, FileAccess.Write, FileShare.None);
            StreamWriter dcStreamWriter = new StreamWriter(dcStream);

            // Write the auto generated header
            dcStreamWriter.Write(AutoGenTextHeader.Message);

            try
            {

                // Set up data contract code generator
                CSharpCodeProvider cSharpCP = new CSharpCodeProvider();
                ICodeGenerator codeGen = cSharpCP.CreateGenerator(dcStreamWriter);
                CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions();
                codeGenOptions.BracingStyle = "C";

                // Cobble up a valid .net namespace. Turn any progression that's not a-z or A-Z to a single '.'
                string targetNamespaceName = CodeGenUtils.GenerateDotNetNamespace(m_svcDesc.TargetNamespace);

                // For some reason we have to force schemas to compile. Though it was suppose to automatically. Huh!
                foreach (XmlSchema schema in m_svcDesc.Types.Schemas)
                {
                    XmlSchemaSet schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema);
                    schemaSet.Compile();
                }
                

                // Create new code namespace
                CodeNamespace targetNamespace = new CodeNamespace(targetNamespaceName);

                // Add data contract using directives
                CodeSnippetCompileUnit compileUnit = new CodeSnippetCompileUnit("using System;");
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using System.Xml;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                if (m_platform == TargetPlatform.MicroFramework)
                {
                    compileUnit.Value = "using System.Ext;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                    compileUnit.Value = "using System.Ext.Xml;";
                    codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                }
                compileUnit.Value = "using Ws.ServiceModel;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Mtom;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using Ws.Services.Serialization;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlElement = Ws.Services.Xml.WsXmlNode;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlAttribute = Ws.Services.Xml.WsXmlAttribute;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "using XmlConvert = Ws.Services.Serialization.WsXmlConvert;";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Value = "";
                codeGen.GenerateCodeFromCompileUnit(compileUnit, dcStreamWriter, codeGenOptions);
                compileUnit.Namespaces.Add(targetNamespace);
                m_dcCodeGen.CodeNamespaces = compileUnit.Namespaces;

                Logger.WriteLine("", LogLevel.Normal);

                // Create HostedServices and ClientProxies collections
                HostedServices hostedServices = new HostedServices(targetNamespaceName);
                ClientProxies clientProxies = new ClientProxies(targetNamespaceName);

                // For each PortType process
                foreach (PortType portType in m_svcDesc.PortTypes)
                {
                    // For each operation in the port type:
                    // Get input and output message parts.
                    // If the message part is a simple type:
                    //   Build HostedService operation.
                    // Else if the message part is an element:
                    //   Find elements in Schema
                    //   If element type is native xml type:
                    //     Build HostedService operation.
                    //   Else if element references a simple or complex type:
                    //     If simpleType is base xml type with restrictions:
                    //       Build HostedService operation.
                    //     Else
                    //       Build DataContract and DataContractSerializer.
                    //       Build HostedService Operation.
                    //     

                    if (!CodeGenUtils.IsSoapBinding(portType, m_svcDesc))
                    {
                        continue;
                    }

                    // Create instance of a HostedService to hold the port type details
                    HostedService hostedService = new HostedService(portType.Name, m_svcDesc.TargetNamespace, m_platform);

                    // Create instance of ClientProxyGenerator
                    ClientProxy clientProxy = new ClientProxy(portType.Name, m_platform);

                    // Create service contract interface
                    CodeTypeDeclaration serviceCodeType = new CodeTypeDeclaration("I" + portType.Name);
                    CodeAttributeArgument codeAttr = new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(m_svcDesc.TargetNamespace));
                    CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration("ServiceContract", codeAttr);
                    serviceCodeType.CustomAttributes.Add(codeAttrDecl);

                    // Check for Policy assertions. If found add policy assertion attributes. Policy assertion attributes
                    // are required to regenerate policy assertions when converting a service to Wsdl.
                    List<PolicyAssertion> policyAssertions = GetPolicyAssertions();
                    bool OptimizedMimeEncoded = false;
                    foreach (PolicyAssertion assert in policyAssertions)
                    {
                        serviceCodeType.CustomAttributes.Add(CreatePolicyAssertions(assert.Name, assert.Namespace.ToString(), assert.PolicyID));
                    
                        // if Optimized Mime assertion id found set a processing flag
                        if (assert.Name == "OptimizedMimeSerialization")
                        {
                            OptimizedMimeEncoded = true;
                        }
                    }

                    // Add type declaration
                    serviceCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCodeType.IsInterface = true;

                    // Create service contract callback client interface
                    CodeTypeDeclaration serviceCallbackCodeType = new CodeTypeDeclaration("I" + portType.Name + "Callback");

                    // Add type declaration
                    serviceCallbackCodeType.TypeAttributes = TypeAttributes.Public;
                    serviceCallbackCodeType.IsInterface = true;

                    // If the binding contains a ref to Mtom encoding type set the Mtom flag
                    if (OptimizedMimeEncoded)
                    {
                        m_dcCodeGen.EncodingType = MessageEncodingType.Mtom;
                        hostedService.EncodingType = MessageEncodingType.Mtom;
                        clientProxy.EncodingType = MessageEncodingType.Mtom;
                    }

                    // Step through port operations, get method names and parse elements.
                    for (int pt_index = 0; pt_index < portType.Operations.Count; ++pt_index)
                    {
                        Operation operation = portType.Operations[pt_index];
                        string operationName = operation.Name;

                        string inputMessageName = null;
                        string outputMessageName = null;
                        MessagePartCollection inputMessageParts = null;
                        MessagePartCollection outputMessageParts = null;
                        string inAction = null;
                        string outAction = null;
                        GetAction(portType, operation, m_svcDesc.TargetNamespace, ref inAction, ref outAction);

                        // Oneway request port type
                        if (operation.Messages.Flow == OperationFlow.OneWay)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Twoway request/response pattern
                        else if (operation.Messages.Flow == OperationFlow.RequestResponse)
                        {
                            OperationInput input = operation.Messages.Input;
                            inputMessageName = input.Message.Name;
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }
                        // Event pattern
                        else if (operation.Messages.Flow == OperationFlow.Notification)
                        {
                            OperationOutput output = operation.Messages.Output;
                            outputMessageName = output.Message.Name;

                            // Add operation for HostedService code generation
                            hostedService.AddOperation(operation, inAction, outAction);

                            // Add method for ClientProxy code generation
                            clientProxy.AddOperation(operation, inAction, outAction);
                        }

                        // Find input and output message parts collection in messages collection
                        // and store for later.
                        foreach (Message message in m_svcDesc.Messages)
                        {
                            if (inputMessageName != null)
                                if (message.Name == inputMessageName)
                                {
                                    inputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }

                            if (outputMessageName != null)
                                if (message.Name == outputMessageName)
                                {
                                    outputMessageParts = message.Parts;

                                    // Add operation for HostedService code generation
                                    hostedService.Messages.Add(message);

                                    // Add Message to ClientProxy generator for later
                                    clientProxy.Messages.Add(message);
                                }
                        }

                        try
                        {
                            // Try to generate Data Contracts and DataContractSerializers
                            GenerateTypeContracts(operation, inputMessageParts, outputMessageParts);

                            // If operation flow is notification (event) add OperationContract to ServiceContractCallback
                            // else add OperationContract to ServiceContract
                            if (operation.Messages.Flow == OperationFlow.Notification)
                            {
                                AddServiceOperationToInterface(operation, outAction, serviceCallbackCodeType);
                            }
                            else
                                AddServiceOperationToInterface(operation, inAction, serviceCodeType);
                        }
                        catch (Exception e)
                        {
                            dcStreamWriter.Close();
                            File.Delete(contractFilename);
                            Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                            return;
                        }
                    }

                    // Add serviceCodeType Service Contract interface to namespace
                    // A serviceCodeType is added even if the wsdl only contains notifications. In that case
                    // the contract will be empty but the ServiceContract attribute and CallbackContract argument
                    // will be used to point to the notification or callback contract interace
                    targetNamespace.Types.Add(serviceCodeType);

                    // If service contract callback type contains members add callback contract to namespace
                    // and add CallbackContract reference attribute to serviceCodeType contract.
                    if (serviceCallbackCodeType.Members.Count > 0)
                    {
                        // Add the callback argument to the service description attribute
                        CodeAttributeArgument callbackArg = new CodeAttributeArgument("CallbackContract",
                            new CodeTypeOfExpression(serviceCallbackCodeType.Name)
                        );
                        serviceCodeType.CustomAttributes[0].Arguments.Add(callbackArg);

                        // Add the callback interface to namespace
                        targetNamespace.Types.Add(serviceCallbackCodeType);
                    }

                    // If the hosted service has opeations add to Hosted Services collection for Code Gen
                    if (hostedService.ServiceOperations.Count > 0)
                        hostedServices.Add(hostedService);

                    // If the client Proxy service has opeations add to client proxy collection for Code Gen
                    if (clientProxy.ServiceOperations.Count > 0)
                        clientProxies.Add(clientProxy);
                }

                // MOD: 12-02-08 Added code to handle multiple type namespaces
                // Generate contract source file
                foreach (CodeNamespace codeNamespace in compileUnit.Namespaces)
                {
                    codeGen.GenerateCodeFromNamespace(codeNamespace, dcStreamWriter, codeGenOptions);
                }
                dcStreamWriter.Flush();
                dcStreamWriter.Close();

                // Generate Hosted Service code
                Logger.WriteLine("Generating Hosted Service source: " + hostedServiceFilename + "...", LogLevel.Normal);
                HostedServiceGenerator hsGen = new HostedServiceGenerator();
                hsGen.GenerateCode(hostedServiceFilename, hostedServices);

                // Generate Client proxy code
                Logger.WriteLine("Generating Client Proxy source: " + clientProxyFilename + "...", LogLevel.Normal);
                ClientProxyGenerator cpGen = new ClientProxyGenerator();
                cpGen.GenerateCode(clientProxyFilename, clientProxies);
            }
            catch (Exception e)
            {
                dcStreamWriter.Close();
                File.Delete(contractFilename);
                Logger.WriteLine("Failed to generate service code. " + e.Message, LogLevel.Normal);
                throw new Exception("Failed to generate service code. ", e);
            }
        }
        private void VerifyDeploymentExists(HostedService cloudService, string slot)
        {
            bool exists = false;

            if (cloudService.Deployments != null)
            {
                exists = cloudService.Deployments.Exists(d => string.Equals(
                    d.DeploymentSlot,
                    slot,
                    StringComparison.OrdinalIgnoreCase));
            }

            if (!exists)
            {
                throw new Exception(string.Format(Resources.CannotFindDeployment, cloudService.ServiceName, slot));
            }
        }
        public void TestSetup()
        {
            GlobalPathInfo.GlobalSettingsDirectory = Data.AzureSdkAppDir;
            CmdletSubscriptionExtensions.SessionManager = new InMemorySessionManager();

            storageService = new StorageService()
            {
                ServiceName = storageName,
                StorageServiceKeys = new StorageServiceKeys()
                {
                    Primary = "MNao3bm7t7B/x+g2/ssh9HnG0mEh1QV5EHpcna8CetYn+TSRoA8/SBoH6B3Ufwtnz3jZLSw9GEUuCTr3VooBWq==",
                    Secondary = "secondaryKey"
                },
                StorageServiceProperties = new StorageServiceProperties()
                {
                    Endpoints = new EndpointList()
                    {
                        "http://awesome.blob.core.windows.net/",
                        "http://awesome.queue.core.windows.net/",
                        "http://awesome.table.core.windows.net/"
                    }
                }
            };

            deployment = new Deployment()
            {
                DeploymentSlot = DeploymentSlotType.Production,
                Name = "mydeployment",
                PrivateID = "privateId",
                Status = DeploymentStatus.Starting,
                RoleInstanceList = new RoleInstanceList()
                {
                    new RoleInstance()
                    {
                        InstanceStatus = RoleInstanceStatus.ReadyRole,
                        RoleName = "Role1",
                        InstanceName = "Instance_Role1"
                    }
                }
            };

            cloudService = new HostedService()
            {
                ServiceName = serviceName,
                Deployments = new DeploymentList()
            };
            subscription = new SubscriptionData()
            {
                Certificate = It.IsAny<X509Certificate2>(),
                IsDefault = true,
                ServiceEndpoint = "https://www.azure.com",
                SubscriptionId = Guid.NewGuid().ToString(),
                SubscriptionName = Data.Subscription1
            };

            serviceManagementChannelMock = new Mock<IServiceManagement>();
            serviceManagementChannelMock.Setup(f => f.EndGetHostedServiceWithDetails(It.IsAny<IAsyncResult>()))
                .Returns(cloudService);
            serviceManagementChannelMock.Setup(f => f.EndGetStorageService((It.IsAny<IAsyncResult>())))
                .Returns(storageService);
            serviceManagementChannelMock.Setup(f => f.EndGetStorageKeys(It.IsAny<IAsyncResult>()))
                .Returns(storageService);
            serviceManagementChannelMock.Setup(f => f.EndGetDeploymentBySlot(It.IsAny<IAsyncResult>()))
                .Returns(deployment);

            cloudBlobUtilityMock = new Mock<CloudBlobUtility>();
            cloudBlobUtilityMock.Setup(f => f.UploadPackageToBlob(
                serviceManagementChannelMock.Object,
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<BlobRequestOptions>())).Returns(new Uri("http://www.packageurl.azure.com"));

            client = new CloudServiceClient(subscription)
            {
                ServiceManagementChannel = serviceManagementChannelMock.Object,
                CloudBlobUtility = cloudBlobUtilityMock.Object
            };
        }