Beispiel #1
0
        public static void SetFormattedMessage(ServiceBusHelper serviceBusHelper, string messageText, FastColoredTextBox textBox)
        {
            if (serviceBusHelper == null)
            {
                throw new ArgumentNullException(nameof(serviceBusHelper), $"{nameof(serviceBusHelper)} parameter cannot be null");
            }

            if (string.IsNullOrEmpty(messageText))
            {
                throw new ArgumentNullException(nameof(messageText), $"{nameof(messageText)} parameter cannot be null");
            }

            if (textBox == null)
            {
                throw new ArgumentNullException(nameof(textBox), $"{nameof(textBox)} parameter cannot be null");
            }

            InternalSetFormattedMessage(messageText, textBox);
        }
 /// <summary>
 /// Deserialize the xml string into an object instance.
 /// </summary>
 /// <param name="serviceBusHelper">A ServiceBusHelper object.</param>
 /// <param name="xml">The string that must be deserialized.</param>
 /// <returns>The object deserialized.</returns>
 public static void DeserializeAndCreate(ServiceBusHelper serviceBusHelper, string xml)
 {
     if (string.IsNullOrEmpty(xml))
     {
         return;
     }
     using (var stringReader = new StringReader(xml))
     {
         using (var xmlReader = XmlReader.Create(stringReader))
         {
             var root        = XElement.Load(xmlReader);
             var descendants = root.Descendants();
             CreateQueues(serviceBusHelper,
                          root.Descendants(string.Format(NodeNameFormat, Namespace, QueueEntity)));
             CreateTopics(serviceBusHelper,
                          root.Descendants(string.Format(NodeNameFormat, Namespace, TopicEntity)));
         }
     }
 }
Beispiel #3
0
        void OnServiceBusLogOn(object sender, EventArgs e)
        {
            string serviceNamespace = "";

            if (IsServiceBusAddress(m_MexAddressTextBox.Text))
            {
                serviceNamespace = ServiceBusHelper.ExtractNamespace(new Uri(m_MexAddressTextBox.Text));
            }

LOGIN:
            LogonDialog dialog = new LogonDialog(serviceNamespace, ServiceBusHelper.DefaultIssuer);

            dialog.ShowDialog();

            if (IsServiceBusAddress(m_MexAddressTextBox.Text) == false)
            {
                try
                {
                    m_MexAddressTextBox.Text = ServiceBusEnvironment.CreateServiceUri("sb", dialog.ServiceNamespace, "").AbsoluteUri;
                }
                catch
                {
                    System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show("Invalid service namespace", "MEX Explorer", System.Windows.Forms.MessageBoxButtons.RetryCancel, System.Windows.Forms.MessageBoxIcon.Error);
                    if (result == System.Windows.Forms.DialogResult.Retry)
                    {
                        goto LOGIN;
                    }
                    else
                    {
                        return;
                    }
                }
            }


            TransportClientEndpointBehavior credentials = new TransportClientEndpointBehavior();

            credentials.CredentialType = TransportClientCredentialType.SharedSecret;
            credentials.Credentials.SharedSecret.IssuerName   = dialog.Issuer;
            credentials.Credentials.SharedSecret.IssuerSecret = dialog.Secret;

            m_NamespaceCredentials[dialog.ServiceNamespace] = credentials;
        }
 private void ChangeHVACMode()
 {
     try
     {
         if (netOnewayChannel != null)
         {
             ServiceBusHelper.SendHVACModeValue(netOnewayChannel, tsDeviceId.Text, "HVAC-1", hvacMode);
             AddLog(String.Format("HVAC Mode is set to {0}", ServiceBusHelper.GetHVACModeString(hvacMode)));
         }
         else
         {
             MessageBox.Show("netOnewayChannel is not initialized", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
 private void ChangeSetPointValue()
 {
     try
     {
         if (netOnewayChannel != null)
         {
             ServiceBusHelper.SendHVACSetPointValue(netOnewayChannel, tsDeviceId.Text, "HVAC-1", setPoint);
             AddLog(String.Format("Changed HVAC SetPoint to {0} degrees F", setPoint));
         }
         else
         {
             MessageBox.Show("netOnewayChannel is not initialized", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Beispiel #6
0
        public ConnectForm(ServiceBusHelper serviceBusHelper)
        {
            InitializeComponent();
            this.serviceBusHelper = serviceBusHelper;
            cboServiceBusNamespace.Items.Add(SelectServiceBusNamespace);
            cboServiceBusNamespace.Items.Add(EnterConnectionString);
            if (serviceBusHelper.ServiceBusNamespaces != null)
            {
                // ReSharper disable CoVariantArrayConversion
                cboServiceBusNamespace.Items.AddRange(serviceBusHelper.ServiceBusNamespaces.Keys.OrderBy(s => s).ToArray());
                // ReSharper restore CoVariantArrayConversion
            }

            ConnectivityMode = ServiceBusHelper.ConnectivityMode;
            cboConnectivityMode.DataSource   = Enum.GetValues(typeof(ConnectivityMode));
            cboConnectivityMode.SelectedItem = ConnectivityMode;

            cboTransportType.DataSource = Enum.GetValues(typeof(TransportType));
            var settings = new MessagingFactorySettings();

            cboTransportType.SelectedItem = settings.TransportType;

            cboServiceBusNamespace.SelectedIndex = connectionStringIndex > 0 ? connectionStringIndex : 0;
            if (cboServiceBusNamespace.Text == EnterConnectionString)
            {
                txtUri.Text = connectionString;
            }

            txtQueueFilterExpression.Text        = FilterExpressionHelper.QueueFilterExpression;
            txtTopicFilterExpression.Text        = FilterExpressionHelper.TopicFilterExpression;
            txtSubscriptionFilterExpression.Text = FilterExpressionHelper.SubscriptionFilterExpression;
            btnOk.Enabled = cboServiceBusNamespace.SelectedIndex > 1 || (cboServiceBusNamespace.Text == EnterConnectionString && !string.IsNullOrWhiteSpace(connectionString));

            foreach (var item in MainForm.SingletonMainForm.Entities)
            {
                cboSelectedEntities.Items.Add(item);
            }

            foreach (var item in MainForm.SingletonMainForm.SelectedEntities)
            {
                cboSelectedEntities.CheckBoxItems[item].Checked = true;
            }
        }
    public async Task UpdateSistemaCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Mock <IEventHandler> mockServiceBus           = ServiceBusHelper.GetInstance();
        Mock <IHubContext <CpnucleoHub> > mockSignalR = SignalRHelper.GetInstance();

        Guid     sistemaId    = Guid.NewGuid();
        DateTime dataInclusao = DateTime.Now;

        Sistema sistema = MockEntityHelper.GetNewSistema(sistemaId);

        await unitOfWork.SistemaRepository.AddAsync(sistema);

        await unitOfWork.SaveChangesAsync();

        unitOfWork.SistemaRepository.Detatch(sistema);

        UpdateSistemaCommand request = new()
        {
            Sistema = MockViewModelHelper.GetNewSistema(sistemaId, dataInclusao)
        };

        GetSistemaQuery request2 = new()
        {
            Id = sistemaId
        };

        // Act
        SistemaHandler  handler  = new(unitOfWork, mapper, mockServiceBus.Object, mockSignalR.Object);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        SistemaViewModel response2 = await handler.Handle(request2, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
        Assert.True(response2 != null);
        Assert.True(response2.Id == sistemaId);
        Assert.True(response2.DataInclusao.Ticks == dataInclusao.Ticks);
    }
}
Beispiel #8
0
        public static void SetFormattedMessage(ServiceBusHelper serviceBusHelper, EventData message, FastColoredTextBox textBox)
        {
            if (serviceBusHelper == null)
            {
                throw new ArgumentNullException(nameof(serviceBusHelper), $"{nameof(serviceBusHelper)} parameter cannot be null");
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message), $"{nameof(message)} parameter cannot be null");
            }

            if (textBox == null)
            {
                throw new ArgumentNullException(nameof(textBox), $"{nameof(textBox)} parameter cannot be null");
            }

            InternalSetFormattedMessage(serviceBusHelper.GetMessageText(message, out _), textBox);
        }
    public async Task CreateSistemaCommand_Handle()
    {
        // Arrange
        IUnitOfWork unitOfWork = DbContextHelper.GetContext();
        IMapper     mapper     = AutoMapperHelper.GetMappings();

        Mock <IEventHandler> mockServiceBus           = ServiceBusHelper.GetInstance();
        Mock <IHubContext <CpnucleoHub> > mockSignalR = SignalRHelper.GetInstance();

        CreateSistemaCommand request = new()
        {
            Sistema = MockViewModelHelper.GetNewSistema()
        };

        // Act
        SistemaHandler  handler  = new(unitOfWork, mapper, mockServiceBus.Object, mockSignalR.Object);
        OperationResult response = await handler.Handle(request, CancellationToken.None);

        // Assert
        Assert.True(response == OperationResult.Success);
    }
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm)
        {
            try
            {
                InitializeComponent();
                Task.Factory.StartNew(AsyncWriteToLog).ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        WriteToLog(t.Exception.Message);
                    }
                });
                this.mainForm        = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;
                var metricMonitorControl = new MetricMonitorControl(WriteToLog, new ServiceBusHelper(WriteToLog, serviceBusHelper), null, null, null)
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1),
                    Size     = new Size(panelMain.Size.Width - 3, panelMain.Size.Height - 26),
                    Anchor   = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };


                Text             = MetricsHeader;
                logTraceListener = new LogTraceListener(WriteToLog);
                Trace.Listeners.Add(logTraceListener);
                metricMonitorControl.Focus();

                panelMain.Controls.Add(metricMonitorControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
        static void Main(string[] args)
        {
            try
            {
                string serviceNamespaceDomain = ServiceBusHelper.GetServiceBusSolutionName();
                string issuerName             = "owner";
                string issuerSecret           = "wJBJaobUmarWn6kqv7QpaaRh3ttNVr3w1OjiotVEOL4=";
                ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.AutoDetect;

                TransportClientEndpointBehavior relayCredentials = new TransportClientEndpointBehavior();
                relayCredentials.TokenProvider = SharedSecretTokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);
                Uri serviceAddress = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain,
                                                                            "Gateway/MulticastService/");
                ServiceHost host = new ServiceHost(typeof(MulticastGatewayOperations), serviceAddress);
                host.Description.Endpoints[0].Behaviors.Add(relayCredentials);
                host.Open();


                Console.WriteLine("ServiceUri:" + serviceAddress.ToString());

                Console.WriteLine("Service registered for public discovery.");
                NetEventRelayBinding binding = host.Description.Endpoints[0].Binding as NetEventRelayBinding;
                if (binding != null)
                {
                    Console.WriteLine("Scheme:" + binding.Scheme);
                    Console.WriteLine("Security Mode:" + binding.Security.Mode);
                    Console.WriteLine("Security RelayAuthType:" + binding.Security.RelayClientAuthenticationType.ToString());
                    Console.WriteLine("Security Transport.ProtectionLevel:" + binding.Security.Transport.ProtectionLevel.ToString());
                }
                Console.WriteLine("Press [Enter] to exit");
                Console.ReadLine();

                host.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void SendKwh()
        {
            Random r   = new Random();
            double kwh = double.Parse(String.Format("{0:0.00}", (r.NextDouble() * 100)));

            try
            {
                if (netOnewayChannel != null)
                {
                    ServiceBusHelper.SendKwhValue(netOnewayChannel, tsDeviceId.Text, "Meter-1", kwh);
                    tslbl.Text = String.Format("Sent value {0} kWh @ {1}", kwh, DateTime.UtcNow.ToString("s"));
                }
                else
                {
                    MessageBox.Show("netOnewayChannel is not initialized", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #13
0
 public ConnectForm(ServiceBusHelper serviceBusHelper)
 {
     InitializeComponent();
     this.serviceBusHelper = serviceBusHelper;
     cboServiceBusNamespace.Items.Add(SelectServiceBusNamespace);
     cboServiceBusNamespace.Items.Add(EnterConnectionString);
     if (serviceBusHelper.ServiceBusNamespaces != null)
     {
         // ReSharper disable CoVariantArrayConversion
         cboServiceBusNamespace.Items.AddRange(serviceBusHelper.ServiceBusNamespaces.Keys.ToArray());
         // ReSharper restore CoVariantArrayConversion
     }
     cboServiceBusNamespace.SelectedIndex = connectionStringIndex > 0 ? connectionStringIndex : 0;
     if (cboServiceBusNamespace.Text == EnterConnectionString)
     {
         txtUri.Text = connectionString;
     }
     txtQueueFilterExpression.Text        = FilterExpressionHelper.QueueFilterExpression;
     txtTopicFilterExpression.Text        = FilterExpressionHelper.TopicFilterExpression;
     txtSubscriptionFilterExpression.Text = FilterExpressionHelper.SubscriptionFilterExpression;
     btnOk.Enabled = cboServiceBusNamespace.SelectedIndex > 1 || (cboServiceBusNamespace.Text == EnterConnectionString && !string.IsNullOrEmpty(connectionString));
 }
Beispiel #14
0
        /// <summary>
        /// Adds services for the current feature to the specified <see cref="IServiceCollection"/>.
        /// </summary>
        /// <param name="services">
        /// The <see cref="IServiceCollection"/> to add the feature's services to.
        /// </param>
        /// <param name="configuration">The configuration.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IServiceCollection AddFeatureServices(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddDbContext <PdsContext>(options =>
            {
                options.UseSqlServer(configuration.GetConnectionString("contracts"));
            });

            services.AddRepositoriesServices(configuration);
            services.AddAutoMapper(typeof(FeatureServiceCollectionExtensions).Assembly);
            services.AddScoped <IContractService, ContractService>();

            services.AddAsposeLicense();
            services.AddScoped <IDocumentManagementContractService, AsposeDocumentManagementContractService>();
            services.AddScoped <IDocumentManagementService, AsposeDocumentManagementService>();
            services.AddScoped <IContractValidationService, ContractValidationService>();

            services.AddTransient(typeof(IAuthenticationService <>), typeof(AuthenticationService <>));

            services.AddSingleton <IUriService>(provider =>
            {
                var accesor     = provider.GetRequiredService <IHttpContextAccessor>();
                var request     = accesor.HttpContext.Request;
                var absoluteUri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent());
                return(new UriService(absoluteUri));
            });

            services.AddSingleton(typeof(ISemaphoreOnEntity <>), typeof(SemaphoreOnEntity <>));

            services.AddSingleton <ITopicClient>(serviceProvider => ServiceBusHelper.GetTopicClient(configuration));
            services.AddSingleton <IMessagePublisher, MessagePublisher>();

            services.AddMediatR(typeof(FeatureServiceCollectionExtensions).Assembly);

            services.AddSingleton(s => Helpers.BlobHelper.GetBlobContainerClient(configuration));
            services.AddSingleton <IContractDocumentService, ContractDocumentService>();

            return(services);
        }
Beispiel #15
0
        public ActionResult Index()
        {
            ViewBag.LinuxData = "VNET not connected!";
            try
            {
                ViewBag.LinuxData = getGeoIPData(getIP(Request));
            }
            catch (Exception e)
            {
                ViewBag.LinuxData = e.ToString();
            }

            var cx  = new MyModel();
            var itm = new MyEntitySample();

            itm.Name = ViewBag.LinuxData;
            cx.MyEntitySamples.Add(itm);
            cx.SaveChanges();

            ServiceBusHelper.SendToAll(itm);

            return(View(cx.MyEntitySamples.OrderByDescending(e => e.Id).Take(8)));
        }
Beispiel #16
0
        public async Task <IActionResult> PostProduct([FromBody] Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Products.Add(product);
            await _context.SaveChangesAsync();

            try
            {
                await ServiceBusHelper.SendMessageAsync($"Product Added. Name - {product.Name}, Type - {product.Type}, Price - {product.Price}");
            }
            catch (Exception ex)
            {
                //Service Bus Connection Failed
            }



            return(CreatedAtAction("GetProduct", new { id = product.Id }, product));
        }
Beispiel #17
0
        private void CloseChannels()
        {
            if (this.netOnewayChannel != null && this.netOnewayChannelFactory != null)
            {
                ServiceBusHelper.CloseoneWayChannelFactoryAndChannel(this.netOnewayChannelFactory, this.netOnewayChannel);
            }

            if (netEventRelayChannel != null && netEventRelayChannelFactory != null)
            {
                try
                {
                    netEventRelayChannel.GoingOffline(tsGatewayId.Text, serviceUri, DateTime.UtcNow);
                }
                catch (Exception) { }
                netEventRelayChannel.Close();

                netEventRelayChannelFactory.Close();
            }
            if (server != null)
            {
                server.Close();
            }
        }
        private void InitNetOnewayRelayClient()
        {
            string issuerName             = tsSolutionName.Text;
            string issuerKey              = tsSolutionPassword.Text;
            string serviceNamespaceDomain = tsSolutionToConnect.Text;

            try
            {
                Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "OnewayEnergyServiceOperations");

                netOnewayChannelFactory = new ChannelFactory <IOnewayEnergyServiceChannel>("RelayEndpoint", new EndpointAddress(address));

                netOnewayChannel = ServiceBusHelper.GetOneWayEnergyChannel(netOnewayChannelFactory);

                ClearLog();
                AddLog("Connected");
                AddLog(netOnewayChannelFactory.Endpoint.Address.Uri.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private IMediator BuildMediator()
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.development.json", optional: false, reloadOnChange: true)
                                .Build();

            var services = new ServiceCollection();

            services.AddLoggerAdapter();
            services.AddAutoMapper(typeof(FeatureServiceCollectionExtensions).Assembly);
            var policyRegistry = services.AddPolicyRegistry();

            services.AddAuditApiClient(configuration, policyRegistry);
            services.AddSingleton <ITopicClient>(serviceProvider => ServiceBusHelper.GetTopicClient(configuration));
            services.AddSingleton <IMessagePublisher, MessagePublisher>();

            services.AddMediatR(typeof(FeatureServiceCollectionExtensions).Assembly);

            var provider = services.BuildServiceProvider();

            return(provider.GetRequiredService <IMediator>());
        }
Beispiel #20
0
        public MessageForm(IEnumerable <BrokeredMessage> brokeredMessages, ServiceBusHelper serviceBusHelper, WriteToLogDelegate writeToLog)
        {
            this.brokeredMessages = brokeredMessages;
            this.serviceBusHelper = serviceBusHelper;
            this.writeToLog       = writeToLog;
            InitializeComponent();

            // Make it just a small dialog with the controls on one row
            messagesSplitContainer.Visible = false;
            btnSave.Visible           = false;
            btnSubmit.Location        = btnSave.Location;
            cboSenderInspector.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            int moveRightInPixels = btnClose.Left - btnSubmit.Left;

            Size                      = new Size(Size.Width - moveRightInPixels, 80);
            lblBody.Left             += moveRightInPixels;
            cboBodyType.Left         += moveRightInPixels;
            chkNewMessageId.Left     += moveRightInPixels;
            chkRemove.Left           += moveRightInPixels;
            cboSenderInspector.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
            FormBorderStyle           = FormBorderStyle.FixedDialog;

            cboBodyType.SelectedIndex = (int)MainForm.SingletonMainForm.MessageBodyType;

            // Get Brokered Message Inspector classes
            cboSenderInspector.Items.Add(SelectBrokeredMessageInspector);
            cboSenderInspector.SelectedIndex = 0;

            if (serviceBusHelper.BrokeredMessageInspectors == null)
            {
                return;
            }
            foreach (var key in serviceBusHelper.BrokeredMessageInspectors.Keys)
            {
                cboSenderInspector.Items.Add(key);
            }
        }
Beispiel #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("DbConnection");

            services.AddDbContext <DemoDbContext>(options =>
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    options.UseInMemoryDatabase("Demodb");
                }
                else
                {
                    options.UseSqlServer(connectionString);
                }
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo()
                {
                    Title       = "Product API",
                    Description = "Products api"
                });
            });

            var sbConnectionString = Configuration.GetSection("ServiceBus")["ConnectionString"];

            if (!string.IsNullOrEmpty(sbConnectionString))
            {
                var sbHelper = new ServiceBusHelper(sbConnectionString, "orders");
                sbHelper.RegisterEventHandler(ServiceBusHelper.ProcessMessagesAsync);
                services.AddSingleton <ServiceBusHelper>(sbHelper);
            }

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        void ExploreServiceBus()
        {
            string mexAddress = m_MexAddressTextBox.Text;

            if (IsServiceBusAddress(mexAddress))
            {
                if (m_NamespaceCredentials.ContainsKey(ServiceBusHelper.ExtractNamespace(new Uri(mexAddress))) == false)
                {
                    OnServiceBusLogOn(this, EventArgs.Empty);
                }
            }

            SplashScreen splash = new SplashScreen(Resources.Progress);

            try
            {
                ExploreServiceBus(mexAddress);
            }
            finally
            {
                splash.Close();
                m_ExploreButton.Enabled = true;
            }
        }
Beispiel #23
0
        /// <summary>
        /// Creates the rules which xml definition is contained in the collection passed as a parameter.
        /// </summary>
        /// <param name="serviceBusHelper">A ServiceBusHelper object.</param>
        /// <param name="rules">The IEnumerable<XElement/> collection containing the xml definition of the rules to create.</param>
        private static List <RuleDescription> CreateRules(ServiceBusHelper serviceBusHelper, IEnumerable <XElement> rules)
        {
            if (rules == null)
            {
                return(null);
            }
            var fullName = typeof(RuleDescription).FullName;

            if (string.IsNullOrEmpty(fullName) ||
                !propertyCache.ContainsKey(fullName))
            {
                return(null);
            }
            var propertyDictionary = propertyCache[fullName];
            var list       = new List <RuleDescription>();
            var filterName = string.Format(NodeNameFormat, Namespace, FilterEntity);
            var actionName = string.Format(NodeNameFormat, Namespace, ActionEntity);

            foreach (var rule in rules)
            {
                Filter     filter        = null;
                RuleAction action        = null;
                var        propertyValue = new Dictionary <string, object>();
                var        properties    = rule.Elements();
                foreach (var property in properties)
                {
                    if (property.Name == filterName)
                    {
                        filter = CreateFilter(serviceBusHelper, property.Elements().FirstOrDefault());
                    }
                    else
                    {
                        if (property.Name == actionName)
                        {
                            action = CreateAction(serviceBusHelper, property.Elements().FirstOrDefault());
                        }
                        else
                        {
                            var xmlReader = property.CreateReader();
                            GetPropertyValue(propertyDictionary,
                                             propertyValue,
                                             xmlReader);
                        }
                    }
                }
                var ruleDescription = new RuleDescription();
                if (filter != null)
                {
                    ruleDescription.Filter = filter;
                }
                if (action != null)
                {
                    ruleDescription.Action = action;
                }
                if (propertyValue.ContainsKey(Name))
                {
                    ruleDescription.Name = propertyValue[Name] as string;
                }
                list.Add(ruleDescription);
            }
            return(list);
        }
Beispiel #24
0
        /// <summary>
        /// Creates the subscriptions which xml definition is contained in the collection passed as a parameter.
        /// </summary>
        /// <param name="serviceBusHelper">A ServiceBusHelper object.</param>
        /// <param name="topicDescription">A description of the topic to which to add the subscription.</param>
        /// <param name="subscriptions">The IEnumerable<XElement/> collection containing the xml definition of the subscriptions to create.</param>
        private static void CreateSubscriptions(ServiceBusHelper serviceBusHelper, TopicDescription topicDescription, IEnumerable <XElement> subscriptions)
        {
            try
            {
                if (serviceBusHelper == null ||
                    subscriptions == null)
                {
                    return;
                }
                var fullName = typeof(SubscriptionDescription).FullName;
                if (string.IsNullOrEmpty(fullName) ||
                    !propertyCache.ContainsKey(fullName))
                {
                    return;
                }
                var propertyDictionary = propertyCache[fullName];
                var ruleName           = string.Format(NodeNameFormat, Namespace, RuleEntity);
                var rulesName          = string.Format(NodeNameFormat, Namespace, RuleEntityList);
                foreach (var subscription in subscriptions)
                {
                    var propertyValue            = new Dictionary <string, object>();
                    var properties               = subscription.Elements();
                    IEnumerable <XElement> rules = null;
                    foreach (var property in properties)
                    {
                        if (property.Name == rulesName)
                        {
                            rules = property.Descendants(ruleName);
                        }
                        else
                        {
                            var xmlReader = property.CreateReader();
                            GetPropertyValue(propertyDictionary,
                                             propertyValue,
                                             xmlReader);
                        }
                    }

                    if (propertyValue.ContainsKey(Name) &&
                        propertyValue.ContainsKey(TopicPath))
                    {
                        RuleDescription defaultRuleDescription = null;
                        IEnumerable <RuleDescription> nonDefaultRuleDescriptions = null;
                        var ruleDescriptions = CreateRules(serviceBusHelper, rules);
                        if (ruleDescriptions != null)
                        {
                            defaultRuleDescription =
                                ruleDescriptions.FirstOrDefault(r => r.Name == RuleDescription.DefaultRuleName);
                            nonDefaultRuleDescriptions = ruleDescriptions.Where(r => r.Name != RuleDescription.DefaultRuleName);
                        }
                        var subscriptionDescription = new SubscriptionDescription(propertyValue[TopicPath] as string,
                                                                                  propertyValue[Name] as string);
                        SetPropertyValue(propertyDictionary,
                                         propertyValue,
                                         subscriptionDescription);
                        if (defaultRuleDescription != null)
                        {
                            serviceBusHelper.CreateSubscription(topicDescription, subscriptionDescription, defaultRuleDescription);
                        }
                        else
                        {
                            serviceBusHelper.CreateSubscription(topicDescription, subscriptionDescription);
                        }
                        if (nonDefaultRuleDescriptions != null)
                        {
                            foreach (var ruleDescription in nonDefaultRuleDescriptions)
                            {
                                serviceBusHelper.AddRule(subscriptionDescription, ruleDescription);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Creates the topics which xml definition is contained in the collection passed as a parameter.
        /// </summary>
        /// <param name="serviceBusHelper">A ServiceBusHelper object.</param>
        /// <param name="topics">The IEnumerable<XElement/> collection containing the xml definition of the topics to create.</param>
        private static void CreateTopics(ServiceBusHelper serviceBusHelper, IEnumerable <XElement> topics)
        {
            try
            {
                if (serviceBusHelper == null ||
                    topics == null)
                {
                    return;
                }
                var fullName = typeof(TopicDescription).FullName;
                if (string.IsNullOrEmpty(fullName) ||
                    !propertyCache.ContainsKey(fullName))
                {
                    return;
                }
                var propertyDictionary = propertyCache[fullName];
                var subscriptionName   = string.Format(NodeNameFormat, Namespace, SubscriptionEntity);
                var subscriptionsName  = string.Format(NodeNameFormat, Namespace, SubscriptionEntityList);
                foreach (var topic in topics)
                {
                    try
                    {
                        var propertyValue = new Dictionary <string, object>();
                        var properties    = topic.Elements();
                        IEnumerable <XElement> subscriptions = null;
                        foreach (var property in properties)
                        {
                            if (property.Name == subscriptionsName)
                            {
                                subscriptions = property.Descendants(subscriptionName);
                            }
                            else
                            {
                                var xmlReader = property.CreateReader();
                                GetPropertyValue(propertyDictionary,
                                                 propertyValue,
                                                 xmlReader);
                            }
                        }

                        if (propertyValue.ContainsKey(Path))
                        {
                            var topicDescription = new TopicDescription(propertyValue[Path] as string);
                            SetPropertyValue(propertyDictionary,
                                             propertyValue,
                                             topicDescription);
                            topicDescription = serviceBusHelper.CreateTopic(topicDescription);
                            CreateSubscriptions(serviceBusHelper, topicDescription, subscriptions);
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Serializes an entity using the XmlSerializer.
        /// </summary>
        /// <param name="serviceBusHelper">A ServiceBusHelper object.</param>
        /// <param name="xmlWriter">The XmlWriter object to use.</param>
        /// <param name="entity">The entity to serialize.</param>
        /// <returns>A XML string.</returns>
        private static void SerializeEntity(ServiceBusHelper serviceBusHelper, XmlWriter xmlWriter, object entity)
        {
            if (xmlWriter == null ||
                entity == null)
            {
                return;
            }
            var type     = entity.GetType();
            var typeName = type.Name;

            if (type.FullName == null || !propertyCache.ContainsKey(type.FullName))
            {
                return;
            }
            var propertyDictionary = propertyCache[type.FullName];

            xmlWriter.WriteStartElement(MapClassToEntity(type));
            foreach (var keyValuePair in propertyDictionary)
            {
                var value = keyValuePair.Value.GetValue(entity, null);
                xmlWriter.WriteStartElement(keyValuePair.Value.Name);
                if (value is Filter || value is RuleAction)
                {
                    SerializeEntity(serviceBusHelper, xmlWriter, value);
                }
                else
                {
                    xmlWriter.WriteString(string.Format(EntityFormat, value));
                }
                xmlWriter.WriteEndElement();
            }
            if (entity is TopicDescription)
            {
                var topic            = entity as TopicDescription;
                var subscriptionList = serviceBusHelper.GetSubscriptions(topic.Path);
                if (subscriptionList.Any())
                {
                    xmlWriter.WriteStartElement(SubscriptionEntityList);
                    foreach (var subscription in subscriptionList)
                    {
                        SerializeEntity(serviceBusHelper, xmlWriter, subscription);
                    }
                    xmlWriter.WriteEndElement();
                }
            }
            if (entity is SubscriptionDescription)
            {
                var subscription = entity as SubscriptionDescription;
                var ruleList     = serviceBusHelper.GetRules(subscription.TopicPath, subscription.Name);
                if (ruleList.Any())
                {
                    xmlWriter.WriteStartElement(RuleEntityList);
                    foreach (var rule in ruleList)
                    {
                        SerializeEntity(serviceBusHelper, xmlWriter, rule);
                    }
                    xmlWriter.WriteEndElement();
                }
            }
            xmlWriter.WriteEndElement();
            switch (typeName)
            {
            case QueueDescriptionClass:
                var queueDescription = entity as QueueDescription;
                if (queueDescription != null)
                {
                    MainForm.StaticWriteToLog(string.Format(QueueExported, queueDescription.Path));
                }
                break;

            case TopicDescriptionClass:
                var topicDescription = entity as TopicDescription;
                if (topicDescription != null)
                {
                    MainForm.StaticWriteToLog(string.Format(TopicExported, topicDescription.Path));
                }
                break;

            case SubscriptionDescriptionClass:
                var subscriptionDescription = entity as SubscriptionDescription;
                if (subscriptionDescription != null)
                {
                    MainForm.StaticWriteToLog(string.Format(SubscriptionExported,
                                                            subscriptionDescription.Name,
                                                            subscriptionDescription.TopicPath));
                }
                break;

            case RuleDescriptionClass:
                var ruleDescription = entity as RuleDescription;
                if (ruleDescription != null)
                {
                    MainForm.StaticWriteToLog(string.Format(RuleExported,
                                                            ruleDescription.Name));
                }
                break;
            }
        }
Beispiel #27
0
        static void TurnEverythingOff(string serviceNamespace, string gatewayId)
        {
            ChannelFactory <IEnergyServiceGatewayOperationsChannel> netTcpRelayChannelFactory = null;
            IEnergyServiceGatewayOperationsChannel netTcpRelayChannel = null;

            try
            {
                Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, ServiceBusHelper.GetGatewayServicePath(gatewayId));
                //For WS2207HttpRelayBinding
                // Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("http", serviceNamespace, ServiceBusHelper.GetGatewayServicePath(gatewayId));

                netTcpRelayChannelFactory = new ChannelFactory <IEnergyServiceGatewayOperationsChannel>("RelayTcpEndpoint", new EndpointAddress(serviceUri));
                netTcpRelayChannel        = netTcpRelayChannelFactory.CreateChannel();
                netTcpRelayChannel.Open();

                Console.WriteLine("Connected to " + serviceUri.ToString());
                Console.WriteLine("Light switch is:" + netTcpRelayChannel.GetLightingValue(gatewayId, "Lighting-1"));
                netTcpRelayChannel.SetLightingValue(gatewayId, "Lighting-1", 0);
                Console.WriteLine("Light switch turned OFF");

                Console.WriteLine("Current Temperature:" + netTcpRelayChannel.GetCurrentTemp(gatewayId, "HVAC-1"));
                Console.WriteLine("Current Set Point:" + netTcpRelayChannel.GetHVACSetpoint(gatewayId, "HVAC-1"));
                Console.WriteLine("Current HVAC Mode:" + netTcpRelayChannel.GetHVACMode(gatewayId, "HVAC-1"));
                netTcpRelayChannel.SetHVACMode(gatewayId, "HVAC-1", 0);
                netTcpRelayChannel.SetHVACSetpoint(gatewayId, "HVAC-1", 78);
                Console.WriteLine("Set HVAC mode to OFF");
                Console.WriteLine("Set everything to off on " + gatewayId);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (netTcpRelayChannel != null && netTcpRelayChannelFactory != null)
                {
                    netTcpRelayChannel.Close();

                    netTcpRelayChannelFactory.Close();
                }
            }
        }
Beispiel #28
0
        public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
        {
            if (m_SubjectName != null)
            {
                switch (m_Mode)
                {
                case ServiceSecurity.Anonymous:
                case ServiceSecurity.BusinessToBusiness:
                case ServiceSecurity.Internet:
                {
                    string subjectName;
                    if (m_SubjectName != String.Empty)
                    {
                        subjectName = m_SubjectName;
                    }
                    else
                    {
                        subjectName = description.Endpoints[0].Address.Uri.Host;
                    }
                    serviceHostBase.Credentials.ServiceCertificate.SetCertificate(m_StoreLocation, m_StoreName, m_FindType, subjectName);
                    break;
                }

                case ServiceSecurity.ServiceBus:
                {
                    string subjectName;
                    if (m_SubjectName != String.Empty)
                    {
                        subjectName = m_SubjectName;
                    }
                    else
                    {
                        subjectName = ServiceBusHelper.ExtractNamespace(description.Endpoints[0].Address.Uri);
                    }

                    serviceHostBase.Credentials.ServiceCertificate.SetCertificate(m_StoreLocation, m_StoreName, m_FindType, subjectName);

                    break;
                }
                }
            }
            else
            {
                switch (m_Mode)
                {
                case ServiceSecurity.Anonymous:
                case ServiceSecurity.BusinessToBusiness:
                case ServiceSecurity.Internet:
                {
                    string subjectName = description.Endpoints[0].Address.Uri.Host;
                    serviceHostBase.Credentials.ServiceCertificate.SetCertificate(m_StoreLocation, m_StoreName, m_FindType, subjectName);
                    break;
                }

                case ServiceSecurity.ServiceBus:
                {
                    string subjectName = ServiceBusHelper.ExtractNamespace(description.Endpoints[0].Address.Uri);
                    serviceHostBase.Credentials.ServiceCertificate.SetCertificate(m_StoreLocation, m_StoreName, m_FindType, subjectName);
                    break;
                }
                }
            }
            if (UseAspNetProviders == true)
            {
                Debug.Assert(serviceHostBase.Credentials != null);
                serviceHostBase.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.UseAspNetRoles;
                string applicationName;
                Debug.Assert(Roles.ApplicationName == Membership.ApplicationName);
                if (String.IsNullOrEmpty(ApplicationName))
                {
                    ApplicationName = Membership.ApplicationName;
                }
                if (String.IsNullOrEmpty(ApplicationName) || ApplicationName == "/")
                {
                    if (String.IsNullOrEmpty(Assembly.GetEntryAssembly().GetName().Name))
                    {
                        applicationName = AppDomain.CurrentDomain.FriendlyName;
                    }
                    else
                    {
                        applicationName = Assembly.GetEntryAssembly().GetName().Name;
                    }
                }
                else
                {
                    applicationName = ApplicationName;
                }
                Membership.ApplicationName = applicationName;
                Roles.ApplicationName      = applicationName;

                if (m_Mode == ServiceSecurity.Internet)
                {
                    serviceHostBase.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.MembershipProvider;
                }
            }
            else
            {
                Debug.Assert(m_ApplicationName == null);
                //Reiterate the defaults
                serviceHostBase.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Windows;
                serviceHostBase.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.UseWindowsGroups;
            }
            if (m_Mode == ServiceSecurity.Anonymous || m_Mode == ServiceSecurity.BusinessToBusiness && UseAspNetProviders == false)
            {
                serviceHostBase.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.None;
            }

            //Make it affect only when possible
            if (ImpersonateAll)
            {
                if (m_Mode == ServiceSecurity.Intranet || (m_Mode == ServiceSecurity.Internet && UseAspNetProviders == false))
                {
                    return;
                }
                else
                {
                    ImpersonateAll = false;
                }
            }
            if (m_Mode == ServiceSecurity.BusinessToBusiness)
            {
                serviceHostBase.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
            }
        }
        ServiceEndpoint[] GetServiceBusEndpoints()
        {
            string serviceNamespace = ServiceBusHelper.ExtractNamespace(new Uri(m_MexAddressTextBox.Text));

            return(ServiceBusMetadataHelper.GetEndpoints(m_MexAddressTextBox.Text, m_NamespaceCredentials[serviceNamespace]));
        }
        void OnConfigureDiscovery(object sender, EventArgs e)
        {
            string serviceNamespace = "";

            if (IsServiceBusAddress(m_MexAddressTextBox.Text))
            {
                serviceNamespace = ServiceBusHelper.ExtractNamespace(new Uri(m_MexAddressTextBox.Text));
            }

            bool announcementsEnables = m_ServiceBusAnnouncementSinks.ContainsKey(serviceNamespace);

            if (m_DisoveryPaths.ContainsKey(serviceNamespace) == false)
            {
                m_DisoveryPaths[serviceNamespace] = DiscoverableServiceHost.DiscoveryPath;
            }

            if (m_AnnouncementsPaths.ContainsKey(serviceNamespace) == false)
            {
                m_AnnouncementsPaths[serviceNamespace] = DiscoverableServiceHost.AnnouncementsPath;
            }

            DiscoveryDialog dialog = new DiscoveryDialog(serviceNamespace, m_DisoveryPaths[serviceNamespace], announcementsEnables, m_AnnouncementsPaths[serviceNamespace]);

            dialog.ShowDialog();

            serviceNamespace = dialog.ServiceNamespace;

            m_MexAddressTextBox.Text = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "").AbsoluteUri;

            m_DisoveryPaths[serviceNamespace] = dialog.DiscoveryPath;

            if (String.IsNullOrWhiteSpace(dialog.AnnouncementsPath) == false)
            {
                m_AnnouncementsPaths[serviceNamespace] = dialog.AnnouncementsPath;

                if (m_NamespaceCredentials.ContainsKey(ServiceBusHelper.ExtractNamespace(new Uri(m_MexAddressTextBox.Text))) == false)
                {
                    OnServiceBusLogOn(this, EventArgs.Empty);
                }

                Uri newAnouncementsAddress = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, m_AnnouncementsPaths[serviceNamespace]);

                if (m_ServiceBusAnnouncementSinks.ContainsKey(serviceNamespace))
                {
                    if (m_ServiceBusAnnouncementSinks[serviceNamespace].AnnouncementsAddress.AbsoluteUri != newAnouncementsAddress.AbsoluteUri)
                    {
                        m_ServiceBusAnnouncementSinks[serviceNamespace].Close();
                        m_ServiceBusAnnouncementSinks.Remove(serviceNamespace);
                    }
                    else
                    {
                        return;
                    }
                }

                TokenProvider tokenPorvider = m_NamespaceCredentials[serviceNamespace];

                m_ServiceBusAnnouncementSinks[serviceNamespace] = new ServiceBusAnnouncementSink <IMetadataExchange>(serviceNamespace, tokenPorvider);
                m_ServiceBusAnnouncementSinks[serviceNamespace].AnnouncementsAddress = newAnouncementsAddress;

                m_ServiceBusAnnouncementSinks[serviceNamespace].OnlineAnnouncementReceived  += OnHelloNotice;
                m_ServiceBusAnnouncementSinks[serviceNamespace].OfflineAnnouncementReceived += OnByeNotice;

                m_ServiceBusAnnouncementSinks[serviceNamespace].Open();
            }
            else
            {
                if (m_ServiceBusAnnouncementSinks.ContainsKey(serviceNamespace))
                {
                    m_ServiceBusAnnouncementSinks[serviceNamespace].Close();
                    m_ServiceBusAnnouncementSinks.Remove(serviceNamespace);
                }
            }
        }