Esempio n. 1
0
        private async Task SendMessageAsync(Mocks.CloudBlobStorageProviderMock cloudStorage, Mocks.InboxHttpHandlerMock inboxMock, CryptoSettings senderCrypto, OwnEndpoint senderEndpoint, Endpoint receiverEndpoint)
        {
            Requires.NotNull(cloudStorage, "cloudStorage");
            Requires.NotNull(senderCrypto, "senderCrypto");
            Requires.NotNull(senderEndpoint, "senderEndpoint");
            Requires.NotNull(receiverEndpoint, "receiverEndpoint");

            var httpHandler = new Mocks.HttpMessageHandlerMock();

            cloudStorage.AddHttpHandler(httpHandler);

            inboxMock.Register(httpHandler);

            var sentMessage = Valid.Message;

            var channel = new Channel()
            {
                HttpClient = new HttpClient(httpHandler),
                CloudBlobStorage = cloudStorage,
                CryptoServices = senderCrypto,
                Endpoint = senderEndpoint,
                Logger = this.logger,
            };

            await channel.PostAsync(sentMessage, new[] { receiverEndpoint }, Valid.ExpirationUtc);
        }
Esempio n. 2
0
		public void DefaultContactCtor() {
			var contact = new Endpoint();
			Assert.That(contact.MessageReceivingEndpoint, Is.Null);
			Assert.That(contact.EncryptionKeyPublicMaterial, Is.Null);
			Assert.That(contact.SigningKeyPublicMaterial, Is.Null);
			Assert.That(contact.CreatedOnUtc, Is.EqualTo(DateTime.UtcNow).Within(TimeSpan.FromMinutes(1)));
		}
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="endpoint"></param>
 public RemoteServiceInterceptor(Endpoint endpoint)
     : this(endpoint
     , endpoint.Resolve<ILoggerFactory>()
     , endpoint.Resolve<ISerializer>()
     , endpoint.Resolve<ILoadBalancingHelper>())
 {
 }
 public Binding Create(Endpoint serviceInterface)
 {
     var binding = new BasicHttpBinding
                       {
                           Name = serviceInterface.EndpointName,
                           AllowCookies = false,
                           HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard),
                           MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize,
                           MaxReceivedMessageSize = serviceInterface.MaxReceivedSize,
                           MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Mtom),
                           MaxBufferSize = serviceInterface.MaxBufferSize,
                           TransferMode = TransferMode.Streamed,
                           TextEncoding = Encoding.UTF8,
                           ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                           BypassProxyOnLocal = true,
                           UseDefaultWebProxy = false,
                             
                       };
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true")
     {
         binding.BypassProxyOnLocal = false;
         binding.UseDefaultWebProxy = true;
     }
     return binding;
 }
 public Binding Create(Endpoint serviceInterface)
 {
     System.Net.ServicePointManager.ServerCertificateValidationCallback =
         ((sender, certificate, chain, sslPolicyErrors) => true);
     var secureBinding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential)
                             {
                                 Name = "secure",
                                 TransactionFlow = false,
                                 HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard),
                                 MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize,
                                 MaxReceivedMessageSize = serviceInterface.MaxReceivedSize,
                                 MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text),
                                 TextEncoding = Encoding.UTF8,
                                 ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                                 BypassProxyOnLocal = true,
                                 UseDefaultWebProxy = false
                             };
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy")=="true")
     {
         secureBinding.BypassProxyOnLocal = false;
         secureBinding.UseDefaultWebProxy = true; 
     }
     SetSecuritySettings(serviceInterface, secureBinding);
     return secureBinding;
 }
        public void Configure(AbstractRhinoServiceBusConfiguration config, IBusContainerBuilder builder, IServiceLocator locator)
        {
            var busConfig = config as RhinoServiceBusConfiguration;
            if (busConfig == null)
                return;

            var busElement = config.ConfigurationSection.Bus;

            if (busElement == null)
                return;

            var loadBalancerEndpointAsString = busElement.LoadBalancerEndpoint;

            if (string.IsNullOrEmpty(loadBalancerEndpointAsString))
                return;

            Uri loadBalancerEndpoint;
            if (!Uri.TryCreate(loadBalancerEndpointAsString, UriKind.Absolute, out loadBalancerEndpoint))
                throw new ConfigurationErrorsException(
                    "Attribute 'loadBalancerEndpoint' on 'bus' has an invalid value '" + loadBalancerEndpointAsString + "'");

            var endpoint = new Endpoint { Uri = loadBalancerEndpoint };
            builder.RegisterLoadBalancerEndpoint(endpoint.Uri);
            config.AddMessageModule<LoadBalancerMessageModule>();
        }
        public HttpResponseMessage Put(Endpoint endpoint)
        {
            try
            {
                if (endpoint == null)
                    throw WebException(Constants.ErrorParameterEndpointCannotBeNull, HttpStatusCode.BadRequest);

                // Set the username under which the app will store the channel
                endpoint.UserId = this.mapUsernameDelegate(this.Request);

                if (endpoint.ExpirationTime == null || endpoint.ExpirationTime == DateTime.MinValue)
                    endpoint.ExpirationTime = DateTime.UtcNow.Add(defaultEndpointExpirationTime);

                this.Repository.InsertOrUpdate(endpoint);
                return new HttpResponseMessage(HttpStatusCode.Accepted);
            }
            catch (HttpResponseException)
            {
                throw;
            }
            catch (Exception exception)
            {
                throw WebException(exception.Message, HttpStatusCode.InternalServerError);
            }
        }
 public Binding Create(Endpoint serviceInterface)
 {
     if (Utilities.Utilities.GetDisableCertificateValidation().EqualsCaseInsensitive("true"))
         System.Net.ServicePointManager.ServerCertificateValidationCallback =
             ((sender, certificate, chain, sslPolicyErrors) => true);
     var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
     {
         Name = serviceInterface.EndpointName,
         AllowCookies = false,
         HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard),
         MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize,
         MaxReceivedMessageSize = serviceInterface.MaxReceivedSize,
         MessageEncoding = serviceInterface.MessageFormat.ParseAsEnum(WSMessageEncoding.Text),
         TextEncoding = Encoding.UTF8,
         ReaderQuotas = XmlDictionaryReaderQuotas.Max,
         BypassProxyOnLocal = true,
         UseDefaultWebProxy = false
     };
     if (ConfigurationManagerHelper.GetValueOnKey("stardust.UseDefaultProxy") == "true")
     {
         binding.BypassProxyOnLocal = false;
         binding.UseDefaultWebProxy = true;
     }
     binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
     return binding;
 }
        public void EndpointSendAndReceive()
        {
            using (var management = new RabbitMqEndpointManagement(_queue))
            {
                management.BindQueue(_queue.Name, _exchange.Name, ExchangeType.Fanout, "", null);
            }

            IMessageSerializer serializer = new XmlMessageSerializer();

            var message = new BugsBunny {Food = "Carrot"};

            IDuplexTransport transport = _factory.BuildLoopback(new TransportSettings(_exchange));
            IOutboundTransport error = _factory.BuildError(new TransportSettings(_error));

            var sendEndpoint = new Endpoint(_exchange, serializer, transport, error,
                new InMemoryInboundMessageTracker(5));
            sendEndpoint.Send(message);


            var receiveEndpoint = new Endpoint(_queue, serializer, transport, error,
                new InMemoryInboundMessageTracker(5));
            receiveEndpoint.Receive(o =>
                {
                    return b =>
                        {
                            var bb = (BugsBunny)b;
                            Console.WriteLine(bb.Food);
                        };
                }, TimeSpan.Zero);
        }
Esempio n. 10
0
        public static void Test(ITransport t, IQueueStrategy strategy,
            Endpoint queueEndpoint, Action<Message> send, Func<MessageEnumerator>
            enumer)
        {
            Guid id = Guid.NewGuid();
            var serializer = new XmlMessageSerializer(new
                                                          DefaultReflection(), new DefaultKernel());

            var subscriptionStorage = new MsmqSubscriptionStorage(new
                                                                      DefaultReflection(),
                                                                  serializer,
                                                                  queueEndpoint.Uri,
                                                                  new
                                                                      EndpointRouter(),
                                                                  strategy);
            subscriptionStorage.Initialize();

            var wait = new ManualResetEvent(false);

            subscriptionStorage.SubscriptionChanged += () => wait.Set();

            t.AdministrativeMessageArrived +=
                subscriptionStorage.HandleAdministrativeMessage;

            Message msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     AddInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });
            send(msg);

            wait.WaitOne();

            msg = new MessageBuilder
                (serializer).GenerateMsmqMessageFromMessageBatch(new
                                                                     RemoveInstanceSubscription
                {
                    Endpoint = queueEndpoint.Uri.ToString(),
                    InstanceSubscriptionKey = id,
                    Type = typeof (TestMessage2).FullName,
                });

            wait.Reset();

            send(msg);

            wait.WaitOne();

            IEnumerable<Uri> uris = subscriptionStorage
                .GetSubscriptionsFor(typeof (TestMessage2));
            Assert.Equal(0, uris.Count());

            int count = 0;
            MessageEnumerator copy = enumer();
            while (copy.MoveNext()) count++;
            Assert.Equal(0, count);
        }
Esempio n. 11
0
        public MessageQueue[] InitializeQueue(Endpoint queueEndpoint, QueueType queueType)
        {
        	var queue = MsmqUtil.GetQueuePath(queueEndpoint).Create();
        	switch (queueType)
            {
                case QueueType.Standard:
                    return new[]
	                {
	                    queue,
	                    MsmqUtil.OpenOrCreateQueue(GetErrorsQueuePath(), QueueAccessMode.SendAndReceive, queue),
	                    MsmqUtil.OpenOrCreateQueue(GetSubscriptionQueuePath(), QueueAccessMode.SendAndReceive, queue),
	                    MsmqUtil.OpenOrCreateQueue(GetDiscardedQueuePath(), QueueAccessMode.SendAndReceive, queue),
	                    MsmqUtil.OpenOrCreateQueue(GetTimeoutQueuePath(), QueueAccessMode.SendAndReceive, queue),
	                };
                case QueueType.LoadBalancer:
                    return new[]
	                {
	                    queue,
	                    MsmqUtil.OpenOrCreateQueue(GetKnownWorkersQueuePath(), QueueAccessMode.SendAndReceive, queue),
	                    MsmqUtil.OpenOrCreateQueue(GetKnownEndpointsQueuePath(), QueueAccessMode.SendAndReceive, queue),
	                };
                case QueueType.Raw:
                    return new[]
	                {
	                    queue,
	                };
                default:
                    throw new ArgumentOutOfRangeException("queueType", "Can't handle queue type: " + queueType);
            }
        }
Esempio n. 12
0
        public static QueueInfo GetQueuePath(Endpoint endpoint)
        {
            var uri = endpoint.Uri;
            if (uri.AbsolutePath.IndexOf("/", 1) >= 0)
            {
                throw new InvalidOperationException(
                    "Invalid enpoint url : " + uri + Environment.NewLine +
                    "Queue Endpoints can't have a child folders (including 'public')" + Environment.NewLine +
                    "Good: 'msmq://machinename/queue_name'." + Environment.NewLine +
                    " Bad: msmq://machinename/round_file/queue_name"
                    );
            }

            string hostName = uri.Host;
            string queuePathWithFlatSubQueue =
                uri.AbsolutePath.Substring(1);
            if (string.IsNullOrEmpty(uri.Fragment) == false && uri.Fragment.Length > 1)
                queuePathWithFlatSubQueue += uri.Fragment;
            if (string.Compare(hostName, ".") == 0 ||
                string.Compare(hostName, Environment.MachineName, true) == 0 ||
                string.Compare(hostName, "localhost", true) == 0)
            {
                return new QueueInfo
                {
                    IsLocal = true,
                    QueuePath = Environment.MachineName + @"\private$\" + queuePathWithFlatSubQueue,
                    QueueUri = uri,
                    Transactional = endpoint.Transactional
                };
            }

            IPAddress address;
            if (IPAddress.TryParse(hostName, out address))
            {
                return new QueueInfo
                {
                    IsLocal = false,
                    QueuePath = "FormatName:DIRECT=TCP:" + hostName + @"\private$\" + queuePathWithFlatSubQueue,
					QueueUri = uri,
					Transactional = endpoint.Transactional
                };
            }
            if (guidRegEx.IsMatch(hostName))
            {
                return new QueueInfo
                {
                    IsLocal = false,
                    QueuePath = "FormatName:PRIVATE=" + hostName + @"\" + queuePathWithFlatSubQueue,
					QueueUri = uri,
					Transactional = endpoint.Transactional
                };  
            }
            return new QueueInfo
            {
                IsLocal = false,
                QueuePath = "FormatName:DIRECT=OS:" + hostName + @"\private$\" + queuePathWithFlatSubQueue,
				QueueUri = uri,
				Transactional = endpoint.Transactional
            };
        }
Esempio n. 13
0
        public void Run()
        {
            while (true)
            {
                var url = Console.ReadLine();
                if (url == null)
                {
                    break;
                }

                url = url.Trim();
                if (!string.IsNullOrEmpty(url))
                {
                    try
                    {
                        var endPoint = new Endpoint(url);
                        var output = this.dispatcher.DispatchAction(endPoint);
                        Console.WriteLine(output);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
        }
Esempio n. 14
0
        public MsmqFlatQueueTestBase()
        {
            defaultTestBase = new MsmqTestBase();

            testQueueEndPoint = new Endpoint
            {
                Uri = new Uri("msmq://localhost/test_queue")
            };
            testQueuePath = MsmqUtil.GetQueuePath(testQueueEndPoint).QueuePath;

            transactionalTestQueueEndpoint = new Endpoint
            {
                Uri = new Uri("msmq://localhost/transactional_test_queue")
            };
            transactionalTestQueuePath = MsmqUtil.GetQueuePath(transactionalTestQueueEndpoint).QueuePath;

            subscriptionsEndpoint = new Endpoint
            {
                Uri = new Uri(testQueueEndPoint.Uri + "#" + subscriptions)
            };
            subscriptionQueuePath = MsmqUtil.GetQueuePath(subscriptionsEndpoint).QueuePath;

            SetupQueues();

            queue = MsmqUtil.GetQueuePath(testQueueEndPoint).Open();
            transactionalQueue = MsmqUtil.GetQueuePath(transactionalTestQueueEndpoint).Open();
            subscriptions = MsmqUtil.GetQueuePath(subscriptionsEndpoint).Open(QueueAccessMode.SendAndReceive,
                new XmlMessageFormatter(new[]
                {
                    typeof (string)
                }));
        }
        public void SaveEndpoint(Endpoint endpoint)
        {
            using (var conn = _db.OpenConnection())
            using (var tx = conn.BeginTransaction())
            {
                var tags = endpoint.Metadata.Tags.ToDbString();

                conn.Execute(
                    $"replace into EndpointConfig(MonitorType, Address, GroupName, Name, Id, Password, RegisteredOnUtc, RegistrationUpdatedOnUtc, MonitorTag{(tags != null ? ", Tags" : "")}) values(@MonitorType,@Address,@Group,@Name,@Id,@Password,@RegisteredOnUtc,@RegistrationUpdatedOnUtc,@MonitorTag{(tags != null ? ",@Tags" : "")})",
                    new
                    {
                        endpoint.Identity.MonitorType,
                        endpoint.Identity.Address,
                        endpoint.Metadata.Group,
                        endpoint.Metadata.Name,
                        endpoint.Identity.Id,
                        endpoint.Password,
                        endpoint.Metadata.RegisteredOnUtc,
                        endpoint.Metadata.RegistrationUpdatedOnUtc,
                        endpoint.Metadata.MonitorTag,
                        tags
                    }, tx);

                tx.Commit();
            }
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            LogFactory.BuildLogger = type => new ConsoleWindowLogger(type);
            ConsoleWindowLogger.MinimumLogLevel = LogLevel.Info;

            var endpoint = new Endpoint();
            endpoint.Start();

            using (var scope = Settings.RootContainer.BeginLifetimeScope())
            {
                var dtoCompanyQueryService = scope.GetInstance<DtoCompanyQueryService>();

                var dtoEmployeeQueryService = scope.GetInstance<DtoEmployeeQueryService>();

                var googlePage = dtoCompanyQueryService
                    .Query
                    .Where(c => c.Employees.Any(employee => employee.Name.Contains("Smith")))
                    .OrderBy(company => company.Name).FetchPage(1, 10);

                var firstCompanyDto = dtoCompanyQueryService.Query.First();
                var companiesWithMoreThanTwoEmployees = dtoCompanyQueryService.Query.Where(company => company.Employees.Count > 2).ToArray();

                var ordered = dtoCompanyQueryService.Query
                    .OrderByDescending(company => company.Employees.Count)
                    .ThenByDescending(company => company.Name)
                    .ToArray();

                dtoEmployeeQueryService.Query.FirstOrDefault(employee => employee.Name.Length > 2);
            }
        }
 private EndpointDetails(Endpoint endpoint)
 {
     Id = endpoint.Identity.Id;
     Address = endpoint.Identity.Address;
     MonitorType = endpoint.Identity.MonitorType;
     Name = endpoint.Metadata.Name;
     Group = endpoint.Metadata.Group;
     var health = endpoint.Health;
     LastModifiedTime = endpoint.LastModifiedTimeUtc;
     if (health != null)
     {
         Status = health.Status;
         LastCheckUtc = health.CheckTimeUtc;
         LastResponseTime = health.ResponseTime;
         Details = health.Details.ToDictionary(p => p.Key, p => p.Value);
     }
     else
     {
         Details = new Dictionary<string, string>();
         Status = EndpointStatus.NotRun;
     }
     Tags = endpoint.Metadata.Tags;
     RegisteredOnUtc = endpoint.Metadata.RegisteredOnUtc;
     RegistrationUpdatedOnUtc = endpoint.Metadata.RegistrationUpdatedOnUtc;
     MonitorTag = endpoint.Metadata.MonitorTag;
 }
Esempio n. 18
0
 public void Report( Endpoint endpoint, EndpointStatus status )
 {
     var message = BuildMessage( endpoint, status );
     using ( var client = BuildSmtpClient() )
     {
         client.Send( message );
     }
 }
Esempio n. 19
0
 public MessageQueue[] InitializeQueue(Endpoint queueEndpoint, QueueType queueType)
 {
     var path = MsmqUtil.GetQueuePath(queueEndpoint);
     return new[]
     {
         path.Create()
     };
 }
 protected void CreateQueues(QueueType mainQueueType, Endpoint mainQueueEndpoint, string user)
 {
     // will create the queues if they are not already there
     var queues = queueStrategy.InitializeQueue(mainQueueEndpoint, mainQueueType);
     foreach (var queue in queues)
     {
         GrantPermissions(queue, user);
     }
 }
        private async Task MonitorEndpointUpdatesAsync(Endpoint endpoint, CancellationToken cancellationToken)
        {
            while (!endpoint.IsDisposed && !cancellationToken.IsCancellationRequested)
            {
                if (WasEndpointUpdateMissed(endpoint))
                    ReportEndpointTimeout(endpoint);

                await _timeCoordinator.Delay(GetEndpointUpdateCheckDelay(endpoint), cancellationToken);
            }
        }
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="factory"></param>
 /// <param name="serializer"></param>
 /// <param name="loadBalancingHelper"></param>
 public RemoteServiceInterceptor(Endpoint endpoint
     , ILoggerFactory factory
     , ISerializer serializer
     , ILoadBalancingHelper loadBalancingHelper)
 {
     this._endpoint = endpoint;
     this._log = factory.Create(typeof(RemoteServiceInterceptor));
     this._serializer = serializer;
     this._loadBalancingHelper = loadBalancingHelper;
 }
        public AuthenticationFilterTests()
        {
            _requestCredentials = new Credentials(Guid.NewGuid(), "request");
            _adminCredentials = new Credentials(Guid.NewGuid(), "admin");
            _pullMonitorCredentials = new Credentials(Guid.NewGuid(), "pull");

            SetUpCredentialsProvider();
            SetUpTimeCoordinator();

            _endpoint = GetTestEndpoint();
        }
Esempio n. 24
0
 public FastServer(string serverName, SessionProtocol sessionProtocol, Endpoint endpoint)
 {
     if (endpoint == null || sessionProtocol == null)
     {
         throw new System.NullReferenceException();
     }
     this.endpoint = endpoint;
     this.sessionProtocol = sessionProtocol;
     this.serverName = serverName;
     endpoint.ConnectionListener = this;
 }
Esempio n. 25
0
 public static Binding CreateBinding(Endpoint serviceInterface)
 {
     try
     {
         return BindingFactory.CreateBinding(serviceInterface);
     }
     catch (Exception ex)
     {
         throw new InvalidChannelBindingException(string.Format("Error creating binding {0}", serviceInterface.EndpointName),ex);
     }
 }
Esempio n. 26
0
        public EndpointInfo(Endpoint endpoint, string version)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint", "endpoint is null.");
            }

            FullName = Name = endpoint.Name;
            Version = version;
            Host = endpoint.Host ?? String.Empty;
        }
Esempio n. 27
0
 public static BytesReceivedEventArgs GetBytesReceivedResponse(Endpoint endpoint)
 {
     switch (endpoint)
     {
         case Endpoint.PutBytes:
             return new BytesReceivedEventArgs(Util.CombineArrays(Util.GetBytes((ushort)1), Util.GetBytes((ushort)Endpoint.PutBytes), new byte[] { 1 }));
         case Endpoint.SystemMessage:
             return new BytesReceivedEventArgs(Util.CombineArrays(Util.GetBytes((ushort)2), Util.GetBytes((ushort)Endpoint.SystemMessage), new byte[] { 0, 0 }));
         default:
             throw new InvalidOperationException();
     }        
 }
Esempio n. 28
0
        public void Configuration(IAppBuilder app)
        {
            InitializeLogging();

            LogFactory.BuildLogger = type => new Log4NetLogger(type);

            var config = WebApiConfig.Configure(app);

            var endpoint = new Endpoint();
            endpoint.Start();

            config.DependencyResolver = ((WebApiAutofacAdapter)Settings.RootContainer).BuildAutofacDependencyResolver();
        }
Esempio n. 29
0
 public static EndpointAddress EndpointAddress(string serviceName, Endpoint serviceInterface,string rootUrl)
 {
     try
     {
         var formater = Resolver.Activate<IEndpointUrlFormater>();
         return formater.GetEndpointAddress(serviceName, serviceInterface, rootUrl);
     }
     catch (Exception ex)
     {
         
         throw new FormatException("Failure formating endpoint address",ex);
     }
 }
Esempio n. 30
0
 public Binding Create(Endpoint serviceInterface)
 {
     var binding = new NetTcpBinding(SecurityMode.None)
                       {
                           Name = serviceInterface.EndpointName,
                           HostNameComparisonMode = serviceInterface.HostNameComparisonMode.ParseAsEnum(HostNameComparisonMode.StrongWildcard),
                           MaxBufferPoolSize = serviceInterface.MaxBufferPoolSize,
                           MaxReceivedMessageSize = serviceInterface.MaxReceivedSize,
                           ReaderQuotas = XmlDictionaryReaderQuotas.Max,
                           TransferMode = TransferMode.Streamed
                       };
     return binding;
 }
Esempio n. 31
0
 /// <summary> Object.GetHashCode method override. </summary>
 public override int GetHashCode()
 {
     // Note that Port cannot be used because Port==0 matches any non-zero Port value for .Equals
     return(Endpoint.GetHashCode() ^ Generation.GetHashCode());
 }
Esempio n. 32
0
 public JsonEndpoint(Endpoint endpoint)
 {
     serviceName = endpoint.Service_name;
     ipv4        = new IPAddress(BitConverter.GetBytes(endpoint.Ipv4)).ToString();
     port        = endpoint.Port;
 }
Esempio n. 33
0
        public void ProcessPrivacy(string usersFile, string privacyPreference)
        {
            List <string> usersList = new List <string>();

            try
            {
                usersList = FileAccess.GetUsersFileData(usersFile);
            }
            catch (Exception ex)
            {
                Log.WriteLogEntry("ERROR", String.Format("Error while reading Users file: {0}", ex.Message), "Error while reading Users file.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
            }

            PrivacyModePreference userPrivacyPreference = PrivacyModePreference.None;

            switch (privacyPreference.ToLowerInvariant())
            {
            case "default":
                userPrivacyPreference = PrivacyModePreference.None;
                break;

            case "private":
                userPrivacyPreference = PrivacyModePreference.Private;
                break;

            case "public":
                userPrivacyPreference = PrivacyModePreference.Standard;
                break;

            default:
                // Should not happen
                Log.WriteLogEntry("ERROR", "Incorrect value for PrivacyPreference parameter.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
                break;
            }

            if (usersList.Count > 0)
            {
                ucmaPlatform.StartupPlatform();
                ucmaEndpoint = new Endpoint(ucmaPlatform.CollabPlatform);
                PrivacyManager privacyManager = new PrivacyManager(ucmaEndpoint);

                foreach (string user in usersList)
                {
                    Log.WriteLogEntry("INFO", String.Format("Processing user {0}...", user.ToLowerInvariant()), String.Format("Processing user {0}...", user.ToLowerInvariant()));

                    try
                    {
                        privacyManager.SetPrivacyPreference(user, userPrivacyPreference);
                    }
                    catch (RegisterException rex)
                    {
                        Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}. Diag Info: {3}.", user.ToLowerInvariant(), rex.Message, (rex.InnerException == null ? "N/A" : rex.InnerException.Message), (String.IsNullOrEmpty(rex.DiagnosticInformation.ToString()) ? "N/A" : rex.DiagnosticInformation.ToString())), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}", user.ToLowerInvariant(), ex.Message, (ex.InnerException == null ? "N/A" : ex.InnerException.Message)), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                    }
                }
            }
            else
            {
                Log.WriteLogEntry("WARNING", "Users file is empty or invalid. No action will be performed.");
            }
        }
Esempio n. 34
0
        public async Task Start()
        {
            var config = ConfigureEndpoint();

            endpoint = await Endpoint.Start(config).ConfigureAwait(false);
        }
Esempio n. 35
0
 internal Task <IList <StreamSubscriptionHandle <object> > > GetAllSubscriptionHandles()
 {
     return(Endpoint.GetAllSubscriptionHandles());
 }
        public void TestValidateNATNetworkPoliciesForManifestGenerationOnOpenForComposeScenario()
        {
            ApplicationTypeInformation applicationTypeInfo = new ApplicationTypeInformation("AppType", "1.0");
            Application app = new Application();

            app.name = "TestApp";
            Management.ImageBuilder.SingleInstance.CodePackage cpkg = new Management.ImageBuilder.SingleInstance.CodePackage();
            cpkg.image = "image";
            cpkg.name  = "CodePackage";
            var endpoints = new List <Endpoint>();
            var endpoint  = new Endpoint();

            endpoint.name = "publicListener";
            endpoint.port = 8080;
            endpoints.Add(endpoint);
            cpkg.endpoints = endpoints;
            var resource = new Resources();
            var req      = new ResourceDescription();

            req.cpu           = 0.5;
            req.memoryInGB    = 1;
            resource.requests = req;
            cpkg.resources    = resource;
            Service svc = new Service();

            svc.properties.codePackages = new List <Management.ImageBuilder.SingleInstance.CodePackage>();
            svc.properties.codePackages.Add(cpkg);
            svc.name = "Svc1";
            NetworkRef nref = new NetworkRef();

            nref.name = StringConstants.NatNetworkName;
            EndpointRef endpointRef = new EndpointRef();

            endpointRef.name  = "publicListener";
            nref.endpointRefs = new List <EndpointRef>()
            {
                endpointRef
            };
            svc.properties.networkRefs = new List <NetworkRef>();
            svc.properties.networkRefs.Add(nref);
            app.properties.services = new List <Service>();
            app.properties.services.Add(svc);

            string applicationTestDir        = Path.Combine(TestUtility.TestDirectory, Guid.NewGuid().ToString());
            string currentExecutingDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            this.imageBuilder.BuildSingleInstanceApplication(app, "AppType", "1.0", "TestApp", new Uri("fabric:/TestApp"), false, TimeSpan.MaxValue, applicationTestDir, null, true, false, null, new GenerationConfig());
            string expectedAppManifest = Path.Combine(applicationTestDir, "ApplicationManifest.xml");

            var validatingXmlReaderSettings = new XmlReaderSettings();

            validatingXmlReaderSettings.ValidationType = ValidationType.Schema;
            validatingXmlReaderSettings.Schemas.Add(StringConstants.FabricNamespace, Path.Combine(currentExecutingDirectory, StringConstants.DefaultSchemaPath));
            validatingXmlReaderSettings.XmlResolver = null;
            var applicationManifestType = ImageBuilderUtility.ReadXml <ApplicationManifestType>(expectedAppManifest, validatingXmlReaderSettings);

            ApplicationManifestTypeServiceManifestImport[] servicemanifestimports = applicationManifestType.ServiceManifestImport;
            foreach (var serviceManifestImport in servicemanifestimports)
            {
                var policies = serviceManifestImport.Policies;
                foreach (var policy in policies)
                {
                    if (policy.GetType() == typeof(ContainerHostPoliciesType))
                    {
                        var ContainerHostPoliciesTypeItems = ((ContainerHostPoliciesType)policy).Items;
                        foreach (var item in ContainerHostPoliciesTypeItems)
                        {
                            if (item.GetType() == typeof(PortBindingType))
                            {
                                var portBindingType = (PortBindingType)item;
                                Verify.AreEqual("publicListener", portBindingType.EndpointRef);
                                Verify.AreEqual(8080, portBindingType.ContainerPort);
                            }
                        }
                    }
                }
            }
        }
        public void CreateNewPlan_For_State_Unit_SavesMemberDataCorrectly(
            bool thisPeriodSubmitted,
            bool lastPeriod1Submitted,
            bool lastPeriod2Submitted
            )
        {
            DateTimeDbTestExtensions.SetUtcNowToRandomDate();
            var reportingTerms = ReportingPeriod.GetReportingTerms(reportingFrequency);

            if (reportingTerms.All(o => o != reportingTerm))
            {
                return;
            }

            var testParams = Endpoint.ArrangeOnSqlSession(AssemblySetupFixture.EndpointTestContainer,
                                                          s =>
            {
                var organizations = IntegrationTestOrganizationHelper.SetupOrzanizations(
                    stateReportingFrequency: reportingFrequency,
                    zoneReportingFrequency: ReportingFrequency.Monthly);

                var nswState  = organizations.First(o => o.Key == IntegrationTestOrganizationHelper.NswState).Value;
                var laPerouse = new OrganizationBuilder()
                                .SetDescription("La perouse")
                                .SetOrganizationType(OrganizationType.Unit)
                                .SetReportingFreQuency(ReportingFrequency.Monthly)
                                .SetParent(nswState)
                                .BuildAndPersist(s);

                var lalorPark = new OrganizationBuilder()
                                .SetDescription("Lalor park")
                                .SetOrganizationType(OrganizationType.Unit)
                                .SetReportingFreQuency(ReportingFrequency.Monthly)
                                .SetParent(nswState)
                                .BuildAndPersist(s);

                var description = DataProvider.Get <string>();
                var year        = 2019;
                OrganizationReference organizationRef = nswState;

                var reportingPeriod = new ReportingPeriod(reportingFrequency, reportingTerm, year);
                var expected        = new StateReportBuilder()
                                      .SetDescription(description)
                                      .SetOrganization(organizationRef)
                                      .SetReportingPeriod(new ReportingPeriod(reportingFrequency, reportingPeriod.ReportingTerm,
                                                                              reportingPeriod.Year))
                                      .Build();


                var lastPeriod1 = reportingPeriod.GetReportingPeriodOfPreviousTerm();
                var lastPeriod2 = lastPeriod1.GetReportingPeriodOfPreviousTerm();

                var laPerouseThisPeriodUnitReport =
                    IntegrationTestStateReportHelper.BuildAndPersistUnitReport(thisPeriodSubmitted, laPerouse, reportingPeriod, s);
                var laPerouseLastPeriod1UnitReport =
                    IntegrationTestStateReportHelper.BuildAndPersistUnitReport(lastPeriod1Submitted, laPerouse, lastPeriod1, s);
                var laPerouseLastPeriod2UnitReport =
                    IntegrationTestStateReportHelper.BuildAndPersistUnitReport(lastPeriod2Submitted, laPerouse, lastPeriod2, s);

                var lalorParkThisPeriodUnitReport =
                    IntegrationTestStateReportHelper.BuildAndPersistUnitReport(thisPeriodSubmitted, lalorPark, reportingPeriod, s);
                var lalorParkLastPeriod1UnitReport =
                    IntegrationTestStateReportHelper.BuildAndPersistUnitReport(lastPeriod1Submitted, lalorPark, lastPeriod1, s);
                var lalorParkLastPeriod2UnitReport =
                    IntegrationTestStateReportHelper.BuildAndPersistUnitReport(lastPeriod2Submitted, lalorPark, lastPeriod2, s);

                var laPerouseUnitReports = new[]
                {
                    laPerouseThisPeriodUnitReport,
                    laPerouseLastPeriod1UnitReport,
                    laPerouseLastPeriod2UnitReport,
                };

                var lalorParkeUnitReports = new[]
                {
                    lalorParkThisPeriodUnitReport,
                    lalorParkLastPeriod1UnitReport,
                    lalorParkLastPeriod2UnitReport,
                };

                var lastSubmittedLapeRouseReport = IntegrationTestStateReportHelper.GetLastSubmittedReport(laPerouseUnitReports, reportingPeriod);
                var lastSubmittedLalorParkReport = IntegrationTestStateReportHelper.GetLastSubmittedReport(lalorParkeUnitReports, reportingPeriod);

                var submittedReports = new[] { lastSubmittedLapeRouseReport, lastSubmittedLalorParkReport }.Where(o => o != null).ToArray();

                var expectedMemberMemberData               = IntegrationTestStateReportHelper.GetExpectedMemberData(submittedReports, nameof(StateReport.MemberMemberData));
                var expectedMemberMemberGeneratedData      = expectedMemberMemberData;
                var expectedAssociateMemberData            = IntegrationTestStateReportHelper.GetExpectedMemberData(submittedReports, nameof(StateReport.AssociateMemberData));
                var expectedAssociateMemberGeneratedData   = expectedAssociateMemberData;
                var expectedPreliminaryMemberData          = IntegrationTestStateReportHelper.GetExpectedMemberData(submittedReports, nameof(StateReport.PreliminaryMemberData));
                var expectedPreliminaryMemberGeneratedData = expectedPreliminaryMemberData;
                var expectedSupporterMemberData            = IntegrationTestStateReportHelper.GetExpectedMemberData(submittedReports, nameof(StateReport.SupporterMemberData));
                var expectedSupporterMemberGeneratedData   = expectedSupporterMemberData;

                return(new
                {
                    description,
                    reportingPeriod,
                    organizationRef,
                    expected,
                    expectedMemberMemberData,
                    expectedMemberMemberGeneratedData,
                    expectedAssociateMemberData,
                    expectedAssociateMemberGeneratedData,
                    expectedPreliminaryMemberData,
                    expectedPreliminaryMemberGeneratedData,
                    expectedSupporterMemberData,
                    expectedSupporterMemberGeneratedData,
                });
            });
            var result = Endpoint.Act(AssemblySetupFixture.EndpointTestContainer,
                                      c =>
            {
                var stateReport = c.GetInstance <IStateReportFactory>()
                                  .CreateNewStatePlan(testParams.description,
                                                      testParams.organizationRef,
                                                      testParams.reportingPeriod.ReportingTerm,
                                                      testParams.reportingPeriod.Year,
                                                      reportingFrequency);
                return(new
                {
                    stateReport
                });
            });

            result.stateReport.Should().NotBeNull();

            //no need to repeat this section for the other field types
            result.stateReport.Should().BeEquivalentTo(testParams.expected, e =>
                                                       e.Excluding(p => p.Id)
                                                       .Excluding(p => p.MemberMemberData)
                                                       .Excluding(p => p.MemberMemberGeneratedData)
                                                       .Excluding(p => p.AssociateMemberData)
                                                       .Excluding(p => p.AssociateMemberGeneratedData)
                                                       .Excluding(p => p.PreliminaryMemberData)
                                                       .Excluding(p => p.PreliminaryMemberGeneratedData)
                                                       .Excluding(p => p.SupporterMemberData)
                                                       .Excluding(p => p.SupporterMemberGeneratedData)

                                                       .Excluding(p => p.WorkerMeetingProgramData)
                                                       .Excluding(p => p.WorkerMeetingProgramGeneratedData)
                                                       .Excluding(p => p.DawahMeetingProgramData)
                                                       .Excluding(p => p.DawahMeetingProgramGeneratedData)
                                                       .Excluding(p => p.StateLeaderMeetingProgramData)
                                                       .Excluding(p => p.StateLeaderMeetingProgramGeneratedData)
                                                       .Excluding(p => p.StateOutingMeetingProgramData)
                                                       .Excluding(p => p.StateOutingMeetingProgramGeneratedData)
                                                       .Excluding(p => p.IftarMeetingProgramData)
                                                       .Excluding(p => p.IftarMeetingProgramGeneratedData)
                                                       .Excluding(p => p.LearningMeetingProgramData)
                                                       .Excluding(p => p.LearningMeetingProgramGeneratedData)
                                                       .Excluding(p => p.SocialDawahMeetingProgramData)
                                                       .Excluding(p => p.SocialDawahMeetingProgramGeneratedData)
                                                       .Excluding(p => p.DawahGroupMeetingProgramData)
                                                       .Excluding(p => p.DawahGroupMeetingProgramGeneratedData)
                                                       .Excluding(p => p.NextGMeetingProgramData)
                                                       .Excluding(p => p.NextGMeetingProgramGeneratedData)

                                                       .Excluding(p => p.CmsMeetingProgramData)
                                                       .Excluding(p => p.CmsMeetingProgramGeneratedData)
                                                       .Excluding(p => p.SmMeetingProgramData)
                                                       .Excluding(p => p.SmMeetingProgramGeneratedData)
                                                       .Excluding(p => p.MemberMeetingProgramData)
                                                       .Excluding(p => p.MemberMeetingProgramGeneratedData)
                                                       .Excluding(p => p.TafsirMeetingProgramData)
                                                       .Excluding(p => p.TafsirMeetingProgramGeneratedData)
                                                       .Excluding(p => p.UnitMeetingProgramData)
                                                       .Excluding(p => p.UnitMeetingProgramGeneratedData)
                                                       .Excluding(p => p.FamilyVisitMeetingProgramData)
                                                       .Excluding(p => p.FamilyVisitMeetingProgramGeneratedData)
                                                       .Excluding(p => p.EidReunionMeetingProgramData)
                                                       .Excluding(p => p.EidReunionMeetingProgramGeneratedData)
                                                       .Excluding(p => p.BbqMeetingProgramData)
                                                       .Excluding(p => p.BbqMeetingProgramGeneratedData)
                                                       .Excluding(p => p.GatheringMeetingProgramData)
                                                       .Excluding(p => p.GatheringMeetingProgramGeneratedData)
                                                       .Excluding(p => p.OtherMeetingProgramData)
                                                       .Excluding(p => p.OtherMeetingProgramGeneratedData)

                                                       .Excluding(p => p.GroupStudyTeachingLearningProgramData)
                                                       .Excluding(p => p.GroupStudyTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.StudyCircleTeachingLearningProgramData)
                                                       .Excluding(p => p.StudyCircleTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.PracticeDarsTeachingLearningProgramData)
                                                       .Excluding(p => p.PracticeDarsTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.StateLearningCampTeachingLearningProgramData)
                                                       .Excluding(p => p.StateLearningCampTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.QuranStudyTeachingLearningProgramData)
                                                       .Excluding(p => p.QuranStudyTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.QuranClassTeachingLearningProgramData)
                                                       .Excluding(p => p.QuranClassTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.MemorizingAyatTeachingLearningProgramData)
                                                       .Excluding(p => p.MemorizingAyatTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.StateLearningSessionTeachingLearningProgramData)
                                                       .Excluding(p => p.StateLearningSessionTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.StateQiyamulLailTeachingLearningProgramData)
                                                       .Excluding(p => p.StateQiyamulLailTeachingLearningProgramGeneratedData)

                                                       .Excluding(p => p.StudyCircleForAssociateMemberTeachingLearningProgramData)
                                                       .Excluding(p => p.StudyCircleForAssociateMemberTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.HadithTeachingLearningProgramData)
                                                       .Excluding(p => p.HadithTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.WeekendIslamicSchoolTeachingLearningProgramData)
                                                       .Excluding(p => p.WeekendIslamicSchoolTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.MemorizingHadithTeachingLearningProgramData)
                                                       .Excluding(p => p.MemorizingHadithTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.MemorizingDoaTeachingLearningProgramData)
                                                       .Excluding(p => p.MemorizingDoaTeachingLearningProgramGeneratedData)
                                                       .Excluding(p => p.OtherTeachingLearningProgramData)
                                                       .Excluding(p => p.OtherTeachingLearningProgramGeneratedData)

                                                       .Excluding(p => p.BookSaleMaterialData)
                                                       .Excluding(p => p.BookSaleMaterialGeneratedData)
                                                       .Excluding(p => p.BookDistributionMaterialData)
                                                       .Excluding(p => p.BookDistributionMaterialGeneratedData)
                                                       .Excluding(p => p.BookLibraryStockData)
                                                       .Excluding(p => p.BookLibraryStockGeneratedData)
                                                       .Excluding(p => p.OtherSaleMaterialData)
                                                       .Excluding(p => p.OtherSaleMaterialGeneratedData)
                                                       .Excluding(p => p.OtherDistributionMaterialData)
                                                       .Excluding(p => p.OtherDistributionMaterialGeneratedData)
                                                       .Excluding(p => p.OtherLibraryStockData)
                                                       .Excluding(p => p.OtherLibraryStockGeneratedData)
                                                       .Excluding(p => p.VhsSaleMaterialData)
                                                       .Excluding(p => p.VhsSaleMaterialGeneratedData)
                                                       .Excluding(p => p.VhsDistributionMaterialData)
                                                       .Excluding(p => p.VhsDistributionMaterialGeneratedData)
                                                       .Excluding(p => p.VhsLibraryStockData)
                                                       .Excluding(p => p.VhsLibraryStockGeneratedData)
                                                       .Excluding(p => p.EmailDistributionMaterialData)
                                                       .Excluding(p => p.EmailDistributionMaterialGeneratedData)
                                                       .Excluding(p => p.IpdcLeafletDistributionMaterialData)
                                                       .Excluding(p => p.IpdcLeafletDistributionMaterialGeneratedData)
                                                       .Excluding(p => p.BaitulMalFinanceData)
                                                       .Excluding(p => p.BaitulMalFinanceGeneratedData)
                                                       .Excluding(p => p.ADayMasjidProjectFinanceData)
                                                       .Excluding(p => p.ADayMasjidProjectFinanceGeneratedData)
                                                       .Excluding(p => p.MasjidTableBankFinanceData)
                                                       .Excluding(p => p.MasjidTableBankFinanceGeneratedData)


                                                       .Excluding(p => p.QardeHasanaSocialWelfareData)
                                                       .Excluding(p => p.QardeHasanaSocialWelfareGeneratedData)
                                                       .Excluding(p => p.PatientVisitSocialWelfareData)
                                                       .Excluding(p => p.PatientVisitSocialWelfareGeneratedData)
                                                       .Excluding(p => p.SocialVisitSocialWelfareData)
                                                       .Excluding(p => p.SocialVisitSocialWelfareGeneratedData)
                                                       .Excluding(p => p.TransportSocialWelfareData)
                                                       .Excluding(p => p.TransportSocialWelfareGeneratedData)
                                                       .Excluding(p => p.ShiftingSocialWelfareData)
                                                       .Excluding(p => p.ShiftingSocialWelfareGeneratedData)
                                                       .Excluding(p => p.ShoppingSocialWelfareData)
                                                       .Excluding(p => p.ShoppingSocialWelfareGeneratedData)
                                                       .Excluding(p => p.FoodDistributionSocialWelfareData)
                                                       .Excluding(p => p.FoodDistributionSocialWelfareGeneratedData)
                                                       .Excluding(p => p.CleanUpAustraliaSocialWelfareData)
                                                       .Excluding(p => p.CleanUpAustraliaSocialWelfareGeneratedData)
                                                       .Excluding(p => p.OtherSocialWelfareData)
                                                       .Excluding(p => p.OtherSocialWelfareGeneratedData)

                                                       );

            result.stateReport.MemberMemberData.Should().BeEquivalentTo(testParams.expectedMemberMemberData);
            result.stateReport.MemberMemberGeneratedData.Should().BeEquivalentTo(testParams.expectedMemberMemberGeneratedData);

            result.stateReport.AssociateMemberData.Should().BeEquivalentTo(testParams.expectedAssociateMemberData);
            result.stateReport.AssociateMemberGeneratedData.Should().BeEquivalentTo(testParams.expectedAssociateMemberGeneratedData);

            result.stateReport.PreliminaryMemberData.Should().BeEquivalentTo(testParams.expectedPreliminaryMemberData);
            result.stateReport.PreliminaryMemberGeneratedData.Should().BeEquivalentTo(testParams.expectedPreliminaryMemberGeneratedData);

            result.stateReport.SupporterMemberData.Should().BeEquivalentTo(testParams.expectedSupporterMemberData);
            result.stateReport.SupporterMemberGeneratedData.Should().BeEquivalentTo(testParams.expectedSupporterMemberGeneratedData);
        }
        private static void UpdateEndpoint(String regionId, String product, String domain, Endpoint endpoint)
        {
            ISet <String> regionIds = endpoint.RegionIds;

            regionIds.Add(regionId);

            List <ProductDomain> productDomains = endpoint.ProductDomains;
            ProductDomain        productDomain  = FindProductDomain(productDomains, product);

            if (null == productDomain)
            {
                productDomains.Add(new ProductDomain(product, domain));
            }
            else
            {
                productDomain.DomianName = domain;
            }
        }
 public EndpointDependTestClass1(Endpoint endpoint1)
 {
     Endpoint = endpoint1;
 }
Esempio n. 40
0
 void OnShutdown()
 {
     Endpoint?.Stop().GetAwaiter().GetResult();
 }
Esempio n. 41
0
        public static void ParseFileLines(string[] fileLines,
                                          out Video[] videos,
                                          out Endpoint[] endpoints,
                                          out CacheServer[] cacheServers,
                                          out RequestDescription[] requests,
                                          IProgress <float> progress
                                          )
        {
            progress.Report(0);

            int totalLines  = fileLines.Length;
            int currentLine = 0;

            int[] specs = fileLines[currentLine].Split(' ').Select(int.Parse).ToArray();

            progress.Report(currentLine / (float)totalLines);

            int videoCount      = specs[0];
            int endpointCount   = specs[1];
            int requestCount    = specs[2];
            int cachServerCount = specs[3];
            int cachecapacity   = specs[4];

            // init Arrays
            cacheServers        = new CacheServer[cachServerCount];
            videos              = new Video[videoCount];
            endpoints           = new Endpoint[endpointCount];
            requests            = new RequestDescription[requestCount];
            CacheServer.MAXSIZE = cachecapacity;

            for (int i = 0; i < cachServerCount; i++)
            {
                cacheServers[i] = new CacheServer(i);
            }



            // Parse Videos
            int[] videoSizes = fileLines[++currentLine].Split(' ').Select(int.Parse).ToArray();
            if (videoSizes.Length != videoCount)
            {
                throw new Exception("Video Count mismatch");
            }

            for (int i = 0; i < videoSizes.Length; i++)
            {
                var newVideo = new Video(videoSizes[i], i);
                videos[i] = newVideo;
            }


            // ParseEndpoints and cacheData
            for (int i = 0; i < endpointCount; i++)
            {
                progress.Report(currentLine / (float)totalLines);
                int   endpointId      = ++currentLine;
                int[] endpointSpecs   = fileLines[endpointId].Split(' ').Select(int.Parse).ToArray();
                int   endpointLatency = endpointSpecs[0];
                int   connectedCaches = endpointSpecs[1];
                var   newEndpoint     = new Endpoint(endpointId, endpointLatency);

                for (int j = 0; j < connectedCaches; j++)
                {
                    int[] cacheSpecs   = fileLines[++currentLine].Split(' ').Select(int.Parse).ToArray();
                    int   cacheId      = cacheSpecs[0];
                    int   cacheLatency = cacheSpecs[1];

                    // Add cache Server Info
                    newEndpoint.AddCacheConnection(cacheServers[cacheId], cacheLatency);
                }

                endpoints[i] = newEndpoint;
            }

            // Parse Requests
            for (int i = 0; i < requestCount; i++)
            {
                progress.Report(currentLine / (float)totalLines);
                int[] requestSpecs     = fileLines[++currentLine].Split(' ').Select(int.Parse).ToArray();
                int   videoId          = requestSpecs[0];
                int   endpointId       = requestSpecs[1];
                int   numberOfRequests = requestSpecs[2];

                var newRequest = new RequestDescription(videos[videoId], endpoints[endpointId], numberOfRequests);
                requests[i] = newRequest;
            }

            progress.Report(1);
        }
 public EndpointDependTestClass2(Endpoint endpoint1, Endpoint endpoint2)
 {
     Endpoint1 = endpoint1;
     Endpoint2 = endpoint2;
 }
        public void CustomDomainCRUDTest()
        {
            var handler1 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };
            var handler2 = new RecordedDelegatingHandler {
                StatusCodeToReturn = HttpStatusCode.OK
            };

            using (MockContext context = MockContext.Start(this.GetType()))
            {
                // Create clients
                var cdnMgmtClient   = CdnTestUtilities.GetCdnManagementClient(context, handler1);
                var resourcesClient = CdnTestUtilities.GetResourceManagementClient(context, handler2);

                // Create resource group
                var resourceGroupName = CdnTestUtilities.CreateResourceGroup(resourcesClient);

                // Create a standard cdn profile
                string  profileName      = TestUtilities.GenerateName("profile");
                Profile createParameters = new Profile
                {
                    Location = "WestUs",
                    Sku      = new Sku {
                        Name = SkuName.StandardMicrosoft
                    },
                    Tags = new Dictionary <string, string>
                    {
                        { "key1", "value1" },
                        { "key2", "value2" }
                    }
                };

                var profile = cdnMgmtClient.Profiles.Create(resourceGroupName, profileName, createParameters);

                // Create a cdn endpoint with minimum requirements
                string endpointName             = "endpoint-f3757d2a3e10";
                var    endpointCreateParameters = new Endpoint
                {
                    Location       = "WestUs",
                    IsHttpAllowed  = true,
                    IsHttpsAllowed = true,
                    Origins        = new List <DeepCreatedOrigin>
                    {
                        new DeepCreatedOrigin
                        {
                            Name     = "origin1",
                            HostName = "host1.hello.com"
                        }
                    }
                };

                var endpoint = cdnMgmtClient.Endpoints.Create(resourceGroupName, profileName, endpointName, endpointCreateParameters);

                // List custom domains one this endpoint should return none
                var customDomains = cdnMgmtClient.CustomDomains.ListByEndpoint(resourceGroupName, profileName, endpointName);
                Assert.Empty(customDomains);

                // NOTE: There is a CName mapping already created for this custom domain and endpoint hostname
                // "sdk-1-f3757d2a3e10.DUSTYDOGPETCARE.US" maps to "endpoint-f3757d2a3e10.azureedge.net"
                // "sdk-2-f3757d2a3e10.DUSTYDOGPETCARE.US" maps to "endpoint-f3757d2a3e10.azureedge.net"

                // Create custom domain on running endpoint should succeed
                string customDomainName1 = TestUtilities.GenerateName("customDomain");

                cdnMgmtClient.CustomDomains.Create(resourceGroupName, profileName, endpointName, customDomainName1, "sdk-1-f3757d2a3e10.DUSTYDOGPETCARE.US");

                // List custom domains one this endpoint should return one
                customDomains = cdnMgmtClient.CustomDomains.ListByEndpoint(resourceGroupName, profileName, endpointName);
                Assert.Single(customDomains);

                // Stop endpoint
                cdnMgmtClient.Endpoints.Stop(resourceGroupName, profileName, endpointName);

                // Create another custom domain on stopped endpoint should succeed
                string customDomainName2 = TestUtilities.GenerateName("customDomain");
                cdnMgmtClient.CustomDomains.Create(resourceGroupName, profileName, endpointName, customDomainName2, "sdk-2-f3757d2a3e10.DUSTYDOGPETCARE.US");

                // List custom domains one this endpoint should return two
                customDomains = cdnMgmtClient.CustomDomains.ListByEndpoint(resourceGroupName, profileName, endpointName);
                Assert.Equal(2, customDomains.Count());

                // Disable custom https on custom domain that is not enabled should fail
                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    cdnMgmtClient.CustomDomains.DisableCustomHttps(resourceGroupName, profileName, endpointName, customDomainName2);
                });

                // Delete second custom domain on stopped endpoint should succeed
                cdnMgmtClient.CustomDomains.Delete(resourceGroupName, profileName, endpointName, customDomainName2);

                // Get deleted custom domain should fail
                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    cdnMgmtClient.CustomDomains.Get(resourceGroupName, profileName, endpointName, customDomainName2);
                });

                // List custom domains on endpoint should return one
                customDomains = cdnMgmtClient.CustomDomains.ListByEndpoint(resourceGroupName, profileName, endpointName);
                Assert.Single(customDomains);

                // Start endpoint
                cdnMgmtClient.Endpoints.Start(resourceGroupName, profileName, endpointName);

                // Enable custom https using CDN managed certificate on custom domain
                cdnMgmtClient.CustomDomains.EnableCustomHttps(resourceGroupName, profileName, endpointName, customDomainName1);

                // add the same deleted custom domain again
                cdnMgmtClient.CustomDomains.Create(resourceGroupName, profileName, endpointName, customDomainName2, "sdk-2-f3757d2a3e10.DUSTYDOGPETCARE.US");

                // Enable custom https using BYOC on custom domain
                var byocParameters = new KeyVaultCertificateSourceParameters()
                {
                    ResourceGroupName = "byoc",
                    SecretName        = "CdnSDKE2EBYOCTest",
                    SecretVersion     = "526c5d25cc1a46a5bb85ce85ee2b89cc",
                    SubscriptionId    = "3c0124f9-e564-4c42-86f7-fa79457aedc3",
                    VaultName         = "Azure-CDN-BYOC"
                };

                cdnMgmtClient.CustomDomains.EnableCustomHttps(resourceGroupName, profileName, endpointName, customDomainName2, new UserManagedHttpsParameters(ProtocolType.ServerNameIndication, byocParameters));

                // Delete first custom domain should succeed
                cdnMgmtClient.CustomDomains.Delete(resourceGroupName, profileName, endpointName, customDomainName1);

                // Get deleted custom domain should fail
                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    cdnMgmtClient.CustomDomains.Get(resourceGroupName, profileName, endpointName, customDomainName1);
                });

                // Delete second custom domain should succeed
                cdnMgmtClient.CustomDomains.Delete(resourceGroupName, profileName, endpointName, customDomainName2);

                // Get deleted custom domain should fail
                Assert.ThrowsAny <ErrorResponseException>(() =>
                {
                    cdnMgmtClient.CustomDomains.Get(resourceGroupName, profileName, endpointName, customDomainName2);
                });

                // List custom domains on endpoint should return none
                customDomains = cdnMgmtClient.CustomDomains.ListByEndpoint(resourceGroupName, profileName, endpointName);
                Assert.Empty(customDomains);

                // Delete resource group
                CdnTestUtilities.DeleteResourceGroup(resourcesClient, resourceGroupName);
            }
        }
Esempio n. 44
0
 public MessageLoggingModule(IEndpointRouter endpointRouter, Uri logQueue)
 {
     logEndpoint = endpointRouter.GetRoutedEndpoint(logQueue);
 }
Esempio n. 45
0
 public virtual Task Push(object item)
 {
     return(Endpoint.OnNextAsync(item));
 }
Esempio n. 46
0
 public AuditEndpointExplorerItem(Endpoint endpoint)
     : base(endpoint)
 {
 }
Esempio n. 47
0
    static async Task MainAsync()
    {
        Console.Title = "Samples.ASB.Polymorphic.Subscriber";
        var endpointConfiguration = new EndpointConfiguration("Samples.ASB.Polymorphic.Subscriber");
        var transport             = endpointConfiguration.UseTransport <AzureServiceBusTransport>();
        var connectionString      = Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString");

        if (string.IsNullOrWhiteSpace(connectionString))
        {
            throw new Exception("Could not read the 'AzureServiceBus.ConnectionString' environment variable. Check the sample prerequisites.");
        }
        transport.ConnectionString(connectionString);
        var topology = transport.UseTopology <EndpointOrientedTopology>();

        transport.Sanitization().UseStrategy <ValidateAndHashIfNeeded>();

        #region RegisterPublisherNames

        topology.RegisterPublisher(typeof(BaseEvent), "Samples.ASB.Polymorphic.Publisher");
        topology.RegisterPublisher(typeof(DerivedEvent), "Samples.ASB.Polymorphic.Publisher");

        #endregion

        endpointConfiguration.SendFailedMessagesTo("error");

        #region DisableAutoSubscripton

        endpointConfiguration.DisableFeature <AutoSubscribe>();

        #endregion

        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UsePersistence <InMemoryPersistence>();
        var recoverability = endpointConfiguration.Recoverability();
        recoverability.Delayed(
            customizations: settings =>
        {
            settings.NumberOfRetries(0);
        });

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        try
        {
            #region ControledSubscriptions

            await endpointInstance.Subscribe <BaseEvent>()
            .ConfigureAwait(false);

            #endregion

            Console.WriteLine("Subscriber is ready to receive events");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
Esempio n. 48
0
        public void ProcessContacts(string usersFile, string contactsFile, string contactsGroup, bool deletionMode)
        {
            List <string>      usersList    = new List <string>();
            List <ContactItem> contactsList = new List <ContactItem>();

            try
            {
                usersList = FileAccess.GetUsersFileData(usersFile);
            }
            catch (Exception ex)
            {
                Log.WriteLogEntry("ERROR", String.Format("Error while reading Users file: {0}", ex.Message), "Error while reading Users file.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
            }

            try
            {
                contactsList = FileAccess.GetContactsFileData(contactsFile);
            }
            catch (Exception ex)
            {
                Log.WriteLogEntry("ERROR", String.Format("Error while reading Contacts file: {0}", ex.Message), "Error while reading Contacts file.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
            }

            if ((contactsList.Count > 0) && (usersList.Count > 0))
            {
                ucmaPlatform.StartupPlatform();
                ucmaEndpoint = new Endpoint(ucmaPlatform.CollabPlatform);
                ContactListManager contactListManager = new ContactListManager(ucmaEndpoint);

                foreach (string user in usersList)
                {
                    Log.WriteLogEntry("INFO", String.Format("Processing user {0}...", user.ToLowerInvariant()), String.Format("Processing user {0}...", user.ToLowerInvariant()));

                    try
                    {
                        if (!deletionMode)
                        {
                            contactListManager.AddContacts(user, contactsList, contactsGroup);
                        }
                        else
                        {
                            contactListManager.RemoveContacts(user, contactsList);
                        }
                    }
                    catch (RegisterException rex)
                    {
                        Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}. Diag Info: {3}.", user.ToLowerInvariant(), rex.Message, (rex.InnerException == null ? "N/A" : rex.InnerException.Message), (String.IsNullOrEmpty(rex.DiagnosticInformation.ToString()) ? "N/A" : rex.DiagnosticInformation.ToString())), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                    }
                    catch (PublishSubscribeException pex)
                    {
                        // If contact list provide is UCS (Exchange Server 2013)
                        if (pex.DiagnosticInformation.ErrorCode == 2164)
                        {
                            Log.WriteLogEntry("WARNING", String.Format("Error while processing user {0}: User's contact list is stored in Unified Contact Store. It can't be managed by {1}", user.ToLowerInvariant(), LumtGlobals.ApplicationShortName), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                        }
                        else
                        {
                            Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}. Diag Info: {3}.", user.ToLowerInvariant(), pex.Message, (pex.InnerException == null ? "N/A" : pex.InnerException.Message), (String.IsNullOrEmpty(pex.DiagnosticInformation.ToString()) ? "N/A" : pex.DiagnosticInformation.ToString())), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}", user.ToLowerInvariant(), ex.Message, (ex.InnerException == null ? "N/A" : ex.InnerException.Message)), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                    }
                }
            }
            else
            {
                Log.WriteLogEntry("WARNING", "Users or Contacts file is empty or invalid. No action will be performed.");
            }
        }
Esempio n. 49
0
    static async Task Main()
    {
        var endpointConfiguration = new EndpointConfiguration("SmokeTest.ClientNoHeartbeat");

        endpointConfiguration.UseTransport <LearningTransport>();

        var enpointInstance = await Endpoint.Start(endpointConfiguration);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");


        var exit = false;

        do
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("-------------------------------------");
            Console.WriteLine("[ A ] Send 1 good Message");
            Console.WriteLine("[ B ] Send 10 bad Messages");
            Console.WriteLine("[ C ] Send Infinite bad Messages ");
            Console.WriteLine("[ Q ] Quit");
            Console.WriteLine("-------------------------------------");
            Console.Write("Make a Choice: ");

            var key = Console.ReadKey();
            Console.WriteLine();


            string text = wordblob.LoremIpsum(5, 5, 1, 1, 1);

#pragma warning disable IDE0010 // Add missing cases
            switch (key.Key)
#pragma warning restore IDE0010 // Add missing cases
            {
            case ConsoleKey.A:
                await SendMessage(enpointInstance, false, text);

                break;

            case ConsoleKey.B:

                for (var i = 0; i < 10; i++)
                {
                    await SendMessage(enpointInstance, true, text);
                }
                break;

            case ConsoleKey.C:

                while (!Console.KeyAvailable)
                {
                    await SendMessage(enpointInstance, true, text);

                    Task.Delay(200).Wait();     // 5 messages a second
                    Console.WriteLine("Press any key to stop sending messages");
                }

                break;

            case ConsoleKey.Q:
                exit = true;
                break;

            default:
                Console.WriteLine("Option not valid, Try again.");
                continue;
            }
        }while (!exit);

        await enpointInstance.Stop();
    }
Esempio n. 50
0
 public ProductsCall(Endpoint endpoint, Payload payload) : base(endpoint, payload)
 {
 }
Esempio n. 51
0
 public IndexedEndpoint(int index, Endpoint endpoint)
 {
     Index    = index;
     Endpoint = endpoint;
 }
Esempio n. 52
0
        static (IReadOnlyList <string> httpMethods, bool acceptCorsPreflight) GetHttpMethods(Endpoint e)
        {
            var metadata = e.Metadata.GetMetadata <IHttpMethodMetadata>();

            return(metadata == null ? (Array.Empty <string>(), false) : (metadata.HttpMethods, metadata.AcceptCorsPreflight));
        }
Esempio n. 53
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.MultiTenant.Receiver";

        var sharedDatabaseConfiguration = CreateBasicNHibernateConfig();

        var tenantDatabasesConfiguration = CreateBasicNHibernateConfig();
        var mapper = new ModelMapper();

        mapper.AddMapping <OrderMap>();
        tenantDatabasesConfiguration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Receiver");

        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.LimitMessageProcessingConcurrencyTo(1);
        endpointConfiguration.SendFailedMessagesTo("error");

        #region ReceiverConfiguration

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(tenantDatabasesConfiguration);
        persistence.UseSubscriptionStorageConfiguration(sharedDatabaseConfiguration);
        persistence.UseTimeoutStorageConfiguration(sharedDatabaseConfiguration);
        persistence.DisableSchemaUpdate();

        endpointConfiguration.EnableOutbox();

        var settingsHolder = endpointConfiguration.GetSettings();
        settingsHolder.Set("NHibernate.Timeouts.AutoUpdateSchema", true);
        settingsHolder.Set("NHibernate.Subscriptions.AutoUpdateSchema", true);

        #endregion

        #region ReplaceOpenSqlConnection

        endpointConfiguration.Pipeline.Register <ExtractTenantConnectionStringBehavior.Registration>();

        #endregion

        #region RegisterPropagateTenantIdBehavior

        endpointConfiguration.Pipeline.Register <PropagateOutgoingTenantIdBehavior.Registration>();
        endpointConfiguration.Pipeline.Register <PropagateIncomingTenantIdBehavior.Registration>();

        #endregion


        var startableEndpoint = await Endpoint.Create(endpointConfiguration)
                                .ConfigureAwait(false);

        #region CreateSchema

        CreateSchema(tenantDatabasesConfiguration, "A");
        CreateSchema(tenantDatabasesConfiguration, "B");

        #endregion

        var endpointInstance = await startableEndpoint.Start()
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        if (endpointInstance != null)
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
Esempio n. 54
0
 /// <summary>
 /// VoIP endpoint. Must only create one endpoint for multiple accounts.
 /// </summary>
 /// <param name="useIPv6">Use IPv6.</param>
 /// <param name="transportType">The transport type flags.</param>
 public VoIPEndpoint(Nequeo.Net.PjSip.IPv6_Use useIPv6, Nequeo.Net.PjSip.TransportType transportType)
 {
     _endpoint = new Endpoint();
     _endpoint.Initialise(useIPv6, transportType);
 }
Esempio n. 55
0
 public UdpListener(Endpoint endpoint)
 {
     this.parent = endpoint;
     this.log    = endpoint.Logger;
 }
        public virtual HttpResponse DoAction <T>(AcsRequest <T> request, bool autoRetry, int maxRetryNumber, string regionId,
                                                 AlibabaCloudCredentials credentials, Signer signer, FormatType?format, List <Endpoint> endpoints) where T : AcsResponse
        {
            FormatType?requestFormatType = request.AcceptFormat;

            if (null != requestFormatType)
            {
                format = requestFormatType;
            }
            ProductDomain domain = null;

            if (request.ProductDomain != null)
            {
                domain = request.ProductDomain;
            }
            else
            {
                domain = Endpoint.FindProductDomain(regionId, request.Product, endpoints);
            }
            if (null == domain)
            {
                throw new ClientException("SDK.InvalidRegionId", "Can not find endpoint to access.");
            }

            request.Headers["User-Agent"] = UserAgent.Resolve(request.GetSysUserAgentConfig(), this.userAgentConfig);

            bool shouldRetry = true;

            for (int retryTimes = 0; shouldRetry; retryTimes++)
            {
                shouldRetry = autoRetry && retryTimes < maxRetryNumber;
                HttpRequest httpRequest = request.SignRequest(signer, credentials, format, domain);

                ResolveTimeout(httpRequest);
                SetHttpsInsecure(IgnoreCertificate);
                ResolveProxy(httpRequest, request);

                HttpResponse response = this.GetResponse(httpRequest);

                PrintHttpDebugMsg(request, response);

                if (response.Content == null)
                {
                    if (shouldRetry)
                    {
                        continue;
                    }
                    else
                    {
                        throw new ClientException("SDK.ConnectionReset", "Connection reset.");
                    }
                }

                if (500 <= response.Status && shouldRetry)
                {
                    continue;
                }

                return(response);
            }

            return(null);
        }
Esempio n. 57
0
        public void ProcessAlertNotifications(string usersFile, string alertWhenAddToContactListNotification, string alertWhenDNDNotification)
        {
            List <string> usersList = new List <string>();

            try
            {
                usersList = FileAccess.GetUsersFileData(usersFile);
            }
            catch (Exception ex)
            {
                Log.WriteLogEntry("ERROR", String.Format("Error while reading Users file: {0}", ex.Message), "Error while reading Users file.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
            }

            NotifyAdditionToContactListType notifyAdditionToContactList = NotifyAdditionToContactListType.NoChange;

            switch (alertWhenAddToContactListNotification.ToLowerInvariant())
            {
            case "":
                notifyAdditionToContactList = NotifyAdditionToContactListType.NoChange;
                break;

            case "yes":
                notifyAdditionToContactList = NotifyAdditionToContactListType.Yes;
                break;

            case "no":
                notifyAdditionToContactList = NotifyAdditionToContactListType.No;
                break;

            default:
                // Should not happen
                Log.WriteLogEntry("ERROR", "Incorrect value for NotifyAdd parameter.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
                break;
            }

            AlertsWhenDoNotDisturbType alertsWhenDoNotDisturb = AlertsWhenDoNotDisturbType.NoChange;

            switch (alertWhenDNDNotification.ToLowerInvariant())
            {
            case "":
                alertsWhenDoNotDisturb = AlertsWhenDoNotDisturbType.NoChange;
                break;

            case "noalerts":
                alertsWhenDoNotDisturb = AlertsWhenDoNotDisturbType.NoAlerts;
                break;

            case "allalerts":
                alertsWhenDoNotDisturb = AlertsWhenDoNotDisturbType.DisplayAllAlerts;
                break;

            case "alertsfromworkgroup":
                alertsWhenDoNotDisturb = AlertsWhenDoNotDisturbType.DisplayAlertsFromHighPresence;
                break;

            default:
                // Should not happen
                Log.WriteLogEntry("ERROR", "Incorrect value for NotifyWhenDND parameter.");
                CleanupEnvironment();
                Program.CloseApplicationOnError();
                break;
            }

            if (usersList.Count > 0)
            {
                ucmaPlatform.StartupPlatform();
                ucmaEndpoint = new Endpoint(ucmaPlatform.CollabPlatform);
                AlertsManager alertsManager = new AlertsManager(ucmaEndpoint);

                foreach (string user in usersList)
                {
                    Log.WriteLogEntry("INFO", String.Format("Processing user {0}...", user.ToLowerInvariant()), String.Format("Processing user {0}...", user.ToLowerInvariant()));

                    try
                    {
                        alertsManager.SetAlertNotificationSetting(user, notifyAdditionToContactList, alertsWhenDoNotDisturb);
                    }
                    catch (RegisterException rex)
                    {
                        Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}. Diag Info: {3}.", user.ToLowerInvariant(), rex.Message, (rex.InnerException == null ? "N/A" : rex.InnerException.Message), (String.IsNullOrEmpty(rex.DiagnosticInformation.ToString()) ? "N/A" : rex.DiagnosticInformation.ToString())), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLogEntry("ERROR", String.Format("Error while processing user {0}: {1}. Inner Exception: {2}", user.ToLowerInvariant(), ex.Message, (ex.InnerException == null ? "N/A" : ex.InnerException.Message)), String.Format("Error while processing user {0}", user.ToLowerInvariant()));
                    }
                }
            }
            else
            {
                Log.WriteLogEntry("WARNING", "Users file is empty or invalid. No action will be performed.");
            }
        }
 public void Initialize(Endpoint source)
 {
     endpoint = source;
 }
Esempio n. 59
0
        /// <summary>
        /// Takes the configuration class and converts it to a SAML2.0 metadata document.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="keyInfo">The keyInfo.</param>
        private void ConvertToMetadata(Saml2Config config, KeyInfo keyInfo)
        {
            var entity = CreateDefaultEntity();

            entity.EntityID   = config.ServiceProvider.Id;
            entity.ValidUntil = DateTime.Now + config.Metadata.Lifetime;

            var serviceProviderDescriptor = new SpSsoDescriptor
            {
                ProtocolSupportEnumeration = new[] { Saml20Constants.Protocol },
                AuthnRequestsSigned        = XmlConvert.ToString(true),
                WantAssertionsSigned       = XmlConvert.ToString(true)
            };

            if (config.ServiceProvider.NameIdFormats.Count > 0)
            {
                serviceProviderDescriptor.NameIdFormat = new string[config.ServiceProvider.NameIdFormats.Count];
                var count = 0;
                foreach (var nameIdFormat in config.ServiceProvider.NameIdFormats)
                {
                    serviceProviderDescriptor.NameIdFormat[count++] = nameIdFormat;
                }
            }

            var baseUrl = new Uri(config.ServiceProvider.Server);
            var logoutServiceEndpoints      = new List <Endpoint>();
            var signonServiceEndpoints      = new List <IndexedEndpoint>();
            var artifactResolutionEndpoints = new List <IndexedEndpoint>(2);

            // Include endpoints.
            foreach (var endpoint in config.ServiceProvider.Endpoints)
            {
                if (endpoint.Type == EndpointType.SignOn)
                {
                    var loginEndpoint = new IndexedEndpoint
                    {
                        Index     = endpoint.Index,
                        IsDefault = true,
                        Location  = new Uri(baseUrl, endpoint.LocalPath).ToString(),
                        Binding   = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost)
                    };

                    signonServiceEndpoints.Add(loginEndpoint);

                    var artifactSignonEndpoint = new IndexedEndpoint
                    {
                        Binding  = Saml20Constants.ProtocolBindings.HttpSoap,
                        Index    = loginEndpoint.Index,
                        Location = loginEndpoint.Location
                    };

                    artifactResolutionEndpoints.Add(artifactSignonEndpoint);
                }
                else if (endpoint.Type == EndpointType.Logout)
                {
                    var logoutEndpoint = new Endpoint
                    {
                        Location = new Uri(baseUrl, endpoint.LocalPath).ToString()
                    };

                    logoutEndpoint.ResponseLocation = logoutEndpoint.Location;
                    logoutEndpoint.Binding          = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost);
                    logoutServiceEndpoints.Add(logoutEndpoint);

                    var artifactLogoutEndpoint = new IndexedEndpoint
                    {
                        Binding  = Saml20Constants.ProtocolBindings.HttpSoap,
                        Index    = endpoint.Index,
                        Location = logoutEndpoint.Location
                    };

                    artifactResolutionEndpoints.Add(artifactLogoutEndpoint);
                }
            }

            serviceProviderDescriptor.SingleLogoutService      = logoutServiceEndpoints.ToArray();
            serviceProviderDescriptor.AssertionConsumerService = signonServiceEndpoints.ToArray();

            // Attribute consuming service.
            if (config.Metadata.RequestedAttributes.Count > 0)
            {
                var attConsumingService = new AttributeConsumingService();
                serviceProviderDescriptor.AttributeConsumingService = new[] { attConsumingService };
                attConsumingService.Index       = signonServiceEndpoints[0].Index;
                attConsumingService.IsDefault   = true;
                attConsumingService.ServiceName = new[] { new LocalizedName("SP", "en") };

                attConsumingService.RequestedAttribute = new RequestedAttribute[config.Metadata.RequestedAttributes.Count];

                for (var i = 0; i < config.Metadata.RequestedAttributes.Count; i++)
                {
                    attConsumingService.RequestedAttribute[i] = new RequestedAttribute
                    {
                        Name       = config.Metadata.RequestedAttributes[i].Name,
                        NameFormat = SamlAttribute.NameformatBasic,
                        IsRequired = config.Metadata.RequestedAttributes[i].IsRequired
                    };
                }
            }
            else
            {
                serviceProviderDescriptor.AttributeConsumingService = new AttributeConsumingService[0];
            }

            if (!config.Metadata.ExcludeArtifactEndpoints)
            {
                serviceProviderDescriptor.ArtifactResolutionService = artifactResolutionEndpoints.ToArray();
            }

            entity.Items = new object[] { serviceProviderDescriptor };

            // Keyinfo
            var keySigning    = new KeyDescriptor();
            var keyEncryption = new KeyDescriptor();

            serviceProviderDescriptor.KeyDescriptor = new[] { keySigning, keyEncryption };

            keySigning.Use          = KeyTypes.Signing;
            keySigning.UseSpecified = true;

            keyEncryption.Use          = KeyTypes.Encryption;
            keyEncryption.UseSpecified = true;

            // Ugly conversion between the .Net framework classes and our classes ... avert your eyes!!
            keySigning.KeyInfo    = Serialization.DeserializeFromXmlString <Schema.XmlDSig.KeyInfo>(keyInfo.GetXml().OuterXml);
            keyEncryption.KeyInfo = keySigning.KeyInfo;

            // apply the <Organization> element
            if (config.Metadata.Organization != null)
            {
                entity.Organization = new Schema.Metadata.Organization
                {
                    OrganizationName = new[] { new LocalizedName {
                                                   Value = config.Metadata.Organization.Name
                                               } },
                    OrganizationDisplayName = new[] { new LocalizedName {
                                                          Value = config.Metadata.Organization.DisplayName
                                                      } },
                    OrganizationURL = new[] { new LocalizedURI {
                                                  Value = config.Metadata.Organization.Url
                                              } }
                };
            }

            if (config.Metadata.Contacts.Count > 0)
            {
                entity.ContactPerson = config.Metadata.Contacts.Select(x => new Schema.Metadata.Contact
                {
                    ContactType =
                        (Schema.Metadata.ContactType)
                            ((int)x.Type),
                    Company         = x.Company,
                    GivenName       = x.GivenName,
                    SurName         = x.SurName,
                    EmailAddress    = new[] { x.Email },
                    TelephoneNumber = new[] { x.Phone }
                }).ToArray();
            }
        }
Esempio n. 60
0
    static async Task Main()
    {
        Console.Title = "Samples.SqlOutbox.Sender";
        var random = new Random();

        var endpointConfiguration = new EndpointConfiguration("Samples.SqlOutbox.Sender");

        endpointConfiguration.EnableInstallers();
        endpointConfiguration.SendFailedMessagesTo("error");

        #region SenderConfiguration

        var connection = @"Data Source=.\SqlExpress;Database=NsbSamplesSqlOutbox;Integrated Security=True;Max Pool Size=100";

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(connection);
        transport.DefaultSchema("sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");

        var persistence = endpointConfiguration.UsePersistence <SqlPersistence>();
        persistence.ConnectionBuilder(
            connectionBuilder: () =>
        {
            return(new SqlConnection(connection));
        });
        var dialect = persistence.SqlDialect <SqlDialect.MsSqlServer>();
        dialect.Schema("sender");
        persistence.TablePrefix("");

        var subscriptions = persistence.SubscriptionSettings();
        subscriptions.DisableCache();

        endpointConfiguration.EnableOutbox();

        #endregion

        SqlHelper.CreateSchema(connection, "sender");
        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }
            var orderSubmitted = new OrderSubmitted
            {
                OrderId = Guid.NewGuid(),
                Value   = random.Next(100)
            };
            await endpointInstance.Publish(orderSubmitted)
            .ConfigureAwait(false);
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }