public void Should_Return_Url_That_Starts_With_Base_Url()
        {
            /* Setup */
            /* Test */
            var result = _builder.Build();

            /* Assert */
            Assert.That(result, Is.StringStarting(_baseUrl));
        }
        public static string JavascriptRouteFunction(this UrlHelper url, string routeName,
                                                     bool useRouteData = true,
                                                     IDictionary <string, string> overrideValues = null)
        {
            var route   = GetRoute(url, routeName);
            var builder = new UrlBuilder(new UrlComposer(), route);

            return(useRouteData ?
                   builder.Build(url.RequestContext.RouteData.Values, overrideValues) :
                   builder.Build(new Dictionary <string, object>(), overrideValues));
        }
        public bool startClient()
        {
            try{
                //Tenta Encerrar Cliente OPC
                if (this.server != null)
                {
                    this.stopClient();
                }

                // Define the cancellation token.
                this.readingCancelationTokenSource = new CancellationTokenSource();
                this.readingCancelationToken       = this.readingCancelationTokenSource.Token;

                Uri url = UrlBuilder.Build(this.name, this.host);
                this.server = new OpcDaServer(url);
                this.server.Connect();

                Console.WriteLine("Servidor OPC Instanciado na url {0}", url);
                return(true);
            }
            catch (Exception e)
            {
                //Console.Write("Falha ao Iniciar Conexão do Opc");

                Console.Write("Falha ao Iniciar Conexão do Opc -> ");
                //Console.Write(e.ToString());

                Console.Write(e.ToString());
            }
            return(false);
        }
示例#4
0
        //private static string server = String.Format("opcda:/{0}", DatabaseInteractor.GetServerName());

        public static object ReadTag(string serverName, string opcTag = "")
        {
            Uri    url = UrlBuilder.Build(serverName);
            object readString;

            using (var client = new OpcDaServer(url))
            {
                client.Connect();
                var g1 = client.AddGroup("g1");
                g1.IsActive = true;
                var item = new[]
                {
                    new OpcDaItemDefinition
                    {
                        ItemId   = opcTag,
                        IsActive = true
                    }
                };
                g1.AddItems(item);
                try
                {
                    readString = g1.Read(g1.Items)[0].Value;
                    return(readString);
                }
                catch (Exception e)
                {
                    log.Error(String.Format("Error reading Tag {0}", opcTag));
                    log.Error(e);
                    return(null);
                }
            }
        }
示例#5
0
        public WebRequester WithUrl(string url, object query)
        {
            var requestUrl = _urlBuilder.Build(url, query);

            _requestInit = () => (HttpWebRequest)WebRequest.Create(requestUrl);
            return(this);
        }
示例#6
0
        internal static void WriteTag(string serverName, string opcTag, object valueToWrite)
        {
            Uri url = UrlBuilder.Build(serverName);

            using (var client = new OpcDaServer(url))
            {
                client.Connect();
                var g1   = client.AddGroup("g1");
                var item = new[]
                {
                    new OpcDaItemDefinition
                    {
                        ItemId   = opcTag,
                        IsActive = true
                    }
                };
                g1.AddItems(item);
                object[] writeObject = { valueToWrite };
                try
                {
                    g1.Write(g1.Items, writeObject);
                }
                catch (Exception e)
                {
                    log.Error(String.Format("Error writing Tag {opcTag}", opcTag));
                    log.Error(e);
                }
            }
        }
        public async Task GetAValueOfAnItemBySubscription()
        {
            Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");

            using (var server = new OpcDaServer(url))
            {
                // Connect to the server first.
                server.Connect();

                // Create a group with items.
                OpcDaGroup group = CreateGroupWithItems(server);

                // Configure subscription.
                group.ValuesChanged += OnGroupValuesChanged;
                group.UpdateRate     = TimeSpan.FromMilliseconds(100); // ValuesChanged won't be triggered if zero

                // Wait some time.
                await Task.Delay(1000);

                // The output should be like the following:
                //   ItemId: Bucket Brigade.Int4; Value: 0; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:11 +03:00
                //   ItemId: Random.Int2; Value: 0; Quality: Bad+BadOutOfService+NotLimited; Timestamp: 04/19/2016 12:41:11 +03:00
                //   ItemId: Random.Int2; Value: 41; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:13 +03:00
                //   ItemId: Random.Int2; Value: 18467; Quality: Good+Good+NotLimited; Timestamp: 04/19/2016 12:41:13 +03:00
                // ...
            }
        }
        public async Task ReadValiesAsynchronously()
        {
            Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");

            using (var server = new OpcDaServer(url))
            {
                // Connect to the server first.
                server.Connect();

                // Create a group with items.
                OpcDaGroup group = CreateGroupWithItems(server);

                // Read values of items from device asynchronously.
                OpcDaItemValue[] values = await group.ReadAsync(group.Items);

                // Output values
                foreach (OpcDaItemValue value in values)
                {
                    Console.WriteLine("ItemId: {0}; Value: {1}; Quality: {2}; Timestamp: {3}",
                                      value.Item.ItemId, value.Value, value.Quality, value.Timestamp);
                }

                // The output should be like the following:
                //   ItemId: Bucket Brigade.Int4; Value: 0; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 13:40:57 +03:00
                //   ItemId: Random.Int2; Value: 26500; Quality: Good+Good+NotLimited; Timestamp: 04/18/2016 13:40:57 +03:00

                values.Should().OnlyContain(v => v.Error.Succeeded);
                values.Should().OnlyContain(v => v.Quality.Master == OpcDaQualityMaster.Good);
            }
        }
        public void BrowsingAnOpcDaServerLocally()
        {
            Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");

            using (var server = new OpcDaServer(url))
            {
                // Connect to the server first.
                server.Connect();

                // Browse elements.
                var browser = new OpcDaBrowserAuto(server);
                BrowseChildren(browser);

                // The output should be like the following:
                // #MonitorACLFile (ItemId: #MonitorACLFile, IsHint: False, IsItem: True, HasChildren: False)
                // @Clients (ItemId: @Clients, IsHint: False, IsItem: True, HasChildren: False)
                // Configured Aliases (ItemId: Configured Aliases, IsHint: False, IsItem: False, HasChildren: True)
                // Simulation Items (ItemId: Simulation Items, IsHint: False, IsItem: False, HasChildren: True)
                //   Bucket Brigade (ItemId: Bucket Brigade, IsHint: False, IsItem: False, HasChildren: True)
                //     ArrayOfReal8 (ItemId: Bucket Brigade.ArrayOfReal8, IsHint: False, IsItem: True, HasChildren: False)
                //     ArrayOfString (ItemId: Bucket Brigade.ArrayOfString, IsHint: False, IsItem: True, HasChildren: False)
                //     Boolean (ItemId: Bucket Brigade.Boolean, IsHint: False, IsItem: True, HasChildren: False)
                //     Int1 (ItemId: Bucket Brigade.Int1, IsHint: False, IsItem: True, HasChildren: False)
                //     Int2 (ItemId: Bucket Brigade.Int2, IsHint: False, IsItem: True, HasChildren: False)
                //     Int4 (ItemId: Bucket Brigade.Int4, IsHint: False, IsItem: True, HasChildren: False)
                // ...
            }
        }
示例#10
0
        private HttpRequestMessage BuildMessage(HttpMethod method, HttpContent content)
        {
            var msg = new HttpRequestMessage(method, UrlBuilder.Build(url, queryParams));

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    msg.Headers.Add(header.Name, header.Value);
                }
            }

            if (timeout != TimeSpan.Zero)
            {
                msg.Properties.Add(Constants.PropertyTimeoutInMs, timeout);
            }
            if (retry > 0)
            {
                msg.Properties.Add(Constants.PropertyRetryCount, retry);
            }

            if (content != null)
            {
                msg.Content = content;
            }

            return(msg);
        }
        public void TestInitialize()
        {
            var uri = UrlBuilder.Build("Matrikon.OPC.Simulation.1");

            _server = new OpcDaServer(uri);
            _server.Connect();
            _opcBrowser = new OpcDaBrowser1(_server);
        }
        public void Test_MemoryLeaks()
        {
            using (var server = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1")))
            {
                for (var gi = 0; gi < 500; gi++)
                {
                    var group    = server.AddGroup("g" + gi);
                    var itemDefs = Enumerable.Repeat(
                        new[]
                    {
                        new OpcDaItemDefinition
                        {
                            ItemId = "Random.Int1"
                        },
                        new OpcDaItemDefinition
                        {
                            ItemId            = "Random.Int2",
                            RequestedDataType = TypeConverter.FromVarEnum(VarEnum.VT_R4)
                        }
                    }, 1000).SelectMany(t => t).ToArray();

                    var cts = new CancellationTokenSource();

                    group.ValidateItems(itemDefs);
                    group.AddItems(itemDefs);
                    group.SetActiveItems(group.Items);
                    group.SetDataTypes(group.Items, TypeConverter.FromVarEnum(VarEnum.VT_I4));
                    group.SyncItems();

                    group.IsActive = true;
                    group.SyncState();

                    // sync read
                    group.Read(group.Items);
                    group.ReadMaxAge(group.Items, TimeSpan.Zero);

                    // async read
                    Task.WaitAll(group.ReadAsync(group.Items, cts.Token), group.ReadMaxAgeAsync(group.Items,
                                                                                                TimeSpan.Zero, cts.Token),
                                 group.RefreshAsync(OpcDaDataSource.Cache, cts.Token)
                                 );

                    group.RemoveItems(group.Items.Take(group.Items.Count / 2).ToArray());

                    // sync read
                    group.Read(group.Items);
                    group.ReadMaxAge(group.Items, TimeSpan.Zero);

                    // async read
                    Task.WaitAll(group.ReadAsync(group.Items, cts.Token), group.ReadMaxAgeAsync(group.Items,
                                                                                                TimeSpan.Zero, cts.Token),
                                 group.RefreshAsync(OpcDaDataSource.Cache, cts.Token)
                                 );
                }
            }
            GC.Collect();
        }
示例#13
0
        public void UrlBuilder_JourneyEndLengthIsNot7_ThrowsJourneyRequestException(string data)
        {
            //Arrange
            Properties.JourneyStart = data;
            var builder = new UrlBuilder(Properties);

            //Act => Assert
            builder.Build();
        }
示例#14
0
        public void UrlBuilder_InvalidJourneyPref_ThrowsJourneyRequestException(string data)
        {
            //Arrange
            Properties.JourneyPref = data;
            var builder = new UrlBuilder(Properties);

            //Act => Assert
            builder.Build();
        }
示例#15
0
 public void TestInitialize()
 {
     _matrikon = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1"));
     _matrikon.Connect();
     _graybox = new OpcDaServer(UrlBuilder.Build("Graybox.Simulator.1"));
     _graybox.Connect();
     _matrikonBrowser = new OpcDaBrowser3(_matrikon);
     _grayboxBrowser  = new OpcDaBrowser3(_graybox);
 }
示例#16
0
文件: Program.cs 项目: dzeju/OPC_test
        static void Main()
        {
            Bootstrap.Initialize();

            Uri url = UrlBuilder.Build("Matrikon.OPC.Simulation.1");

            using (var server = new OpcDaServer(url))
            {
                // Connect to the server first.
                server.Connect();

                // Create a group with items.
                OpcDaGroup group = server.AddGroup("MyGroup");
                group.IsActive = true;

                var definition1 = new OpcDaItemDefinition
                {
                    ItemId   = "Random.Boolean",
                    IsActive = true
                };
                var definition2 = new OpcDaItemDefinition
                {
                    ItemId   = "Random.Int1",
                    IsActive = true
                };
                var definition3 = new OpcDaItemDefinition
                {
                    ItemId   = "Random.Int2",
                    IsActive = true
                };
                OpcDaItemDefinition[] definitions = { definition1, definition2, definition3 };
                OpcDaItemResult[]     results     = group.AddItems(definitions);

                // Handle adding results.
                foreach (OpcDaItemResult result in results)
                {
                    if (result.Error.Failed)
                    {
                        Console.WriteLine("Error adding items: {0}", result.Error);
                    }
                }

                while (true)
                {
                    OpcDaItemValue[] values = group.Read(group.Items, OpcDaDataSource.Device);
                    Console.WriteLine("Random.Boolean: {0} \n Random.Int1: {1} \n Random.Int2: {2}", values[0].Value, values[1].Value, values[2].Value);
                    Thread.Sleep(1000);
                    Console.Clear();
                }


                /*int count = server.Groups.Count;
                 * Console.WriteLine(count);*/
            }
        }
示例#17
0
        public void UrlBuilder_GetUrl_ReturnsStringUrl()
        {
            var urlBuilder = new UrlBuilder(Properties);
            var result     = urlBuilder.Build();
            //Act
            var expected =
                $"https://appsvc-journeyplannermiddleware-test-01.azurewebsites.net/api/Journey/{Properties.JourneyStart}/to/{Properties.JourneyEnd}/?accessOption={Properties.AccessOption}&journeyPreference={Properties.JourneyPref}";

            //Assert
            Assert.AreEqual(expected, result);
        }
示例#18
0
        public void Should_Not_Add_Double_Slash_Between_Base_And_Relative_Url(string baseUrl, string relativeUrl, string expectedUrl)
        {
            /* Setup */
            var builder = new UrlBuilder(baseUrl);

            /* Test */
            var result = builder.Build(relativeUrl);

            /* Assert */
            Assert.That(result, Is.EqualTo(expectedUrl));
        }
示例#19
0
        public async Task GetResponseAsync_CallsTheUrlFromUrlBuilder(string url)
        {
            // Arrange
            var expectedUrl = Client.ApiBase + url;

            UrlBuilder.Build(NullRequest).Returns(url);

            // Act
            await Client.GetResponseAsync(NullRequest);

            // Assert
            await HttpClient.Received().GetAsync(expectedUrl);
        }
示例#20
0
        public void UrlBuilder_simple()
        {
            IUrlBuilder urlBuilder = new UrlBuilder()
                                     .SetScheme(Scheme.Https)
                                     .SetHost("foo.example.com")
                                     .SetPort(81)
                                     .SetPath("/about")
            ;

            var url = urlBuilder.Build();

            Assert.Equal("https://foo.example.com:81/about", url.ToString());
        }
示例#21
0
        public async Task GetResponseAsync_AddsTheResponseToTheCache(ErgastRequest <ErgastResponse> request, string url)
        {
            // Arrange
            var expectedUrl = Client.ApiBase + url;

            UrlBuilder.Build(request).Returns(url);

            // Act
            await Client.GetResponseAsync(request);

            // Assert
            Cache.Received().AddOrReplace(expectedUrl, Arg.Any <ErgastResponse>());
        }
        public void Test_Connect_Disconnect()
        {
            var serv = new OpcDaServer(UrlBuilder.Build("Matrikon.OPC.Simulation.1"));

            serv.Connect();
            serv.IsConnected.Should().BeTrue();
            serv.Disconnect();
            serv.IsConnected.Should().BeFalse();
            serv.Connect();
            serv.IsConnected.Should().BeTrue();
            serv.Disconnect();
            serv.IsConnected.Should().BeFalse();
        }
示例#23
0
        public void GetUrl_HostPathFile()
        {
            var options = new Options()
            {
                Url = "reporting.company.com/ReportServer/ReportService2010.asmx"
            };
            var urlBuilder = new UrlBuilder();

            urlBuilder.Setup(options);
            urlBuilder.Build();
            var url = urlBuilder.GetUrl();

            Assert.That(url, Is.EqualTo("http://reporting.company.com/ReportServer/ReportService2010.asmx"));
        }
示例#24
0
        private async Task <IHttpResponse <T> > PerformRequestAsync <T>(HttpMethod method, string url, object query, ContentType type = ContentType.Negotiated, object data = null) where T : class
        {
            var fullUrl = _urlBuilder.Build(url, query);

            var request = _requestWrapper
                          .WithUrl(fullUrl)
                          .WithMethod(method)
                          .WithPayload(data, type)
                          .Prepare();

            var response = await request.PerformAsync();

            return(await _responseTransformer.TransformAsync <T>(response));
        }
示例#25
0
        public void Should_Append_Query_String_Params_To_Existing_Uri()
        {
            var paramList = new Dictionary <string, string> {
                { "key1", "value1" }, { "key2", "value2" }
            };
            var uri         = new Uri("http://www.mytestsite.com?key0=value0");
            var expectedUrl = uri.AbsoluteUri + "&key1=value1&key2=value2";

            var urlBuilder = new UrlBuilder();

            var newUri = urlBuilder.Build(uri, paramList);

            Assert.AreEqual(expectedUrl, newUri.AbsoluteUri);
        }
示例#26
0
        public async Task <string> DownloadTransactionsAsync(IDictionary <string, string> transactionParameters)
        {
            var urlBuilder = new UrlBuilder(transactionParameters["apibase"])
                             .WithModule(transactionParameters["module"])
                             .WithAction(transactionParameters["action"])
                             .WithFromBlock(transactionParameters["fromBlock"])
                             .WithToBlock(transactionParameters["toBlock"])
                             .WithAddress(transactionParameters["address"])
                             .WithApiKey(transactionParameters["apikey"]);

            HashSet <string> transactionsHashSet = new HashSet <string>();
            var success = true;

            while (success)
            {
                try
                {
                    var uriForBlock         = urlBuilder.Build();
                    var transactionResponse = await GetTransactionsForBlock(uriForBlock);

                    if (transactionResponse == null || transactionResponse.status == 0)
                    {
                        success = false;
                        continue;
                    }

                    transactionResponse.result = transactionResponse.result.Where(p => !transactionsHashSet.Contains(p.transactionHash)).ToList();
                    transactionResponse.result.ForEach(p => transactionsHashSet.Add(p.transactionHash));

                    if (transactionResponse.result.Count == 0)
                    {
                        success = false;
                        continue;
                    }

                    await SaveTransactions(transactionResponse, uriForBlock);

                    var lastTransactionBlock = transactionResponse.result.Select(p => Convert.ToInt32(p.blockNumber, 16)).OrderBy(p => p).LastOrDefault();
                    urlBuilder.WithFromBlock((lastTransactionBlock).ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    success = false;
                }
            }

            return("All transactions saved to database!");
        }
示例#27
0
文件: Program.cs 项目: masmeka/wfopc
        static void Main(string[] args)
        {
            cfg             = new OPCAgentConfig();
            cfg.Host        = ConfigurationManager.AppSettings["host"];
            cfg.OPCName     = ConfigurationManager.AppSettings["opcname"];
            cfg.Period      = Convert.ToInt32(ConfigurationManager.AppSettings["period"]);
            cfg.AssetFolder = ConfigurationManager.AppSettings["assetfolder"];

            var server = new OpcDaServer(UrlBuilder.Build(cfg.OPCName, cfg.Host));

            server.Connect();
            BuildSubcribtion(server, cfg);
            System.Threading.Thread.Sleep(cfg.Period * 10);
            server.Disconnect();
            Console.WriteLine("Press any key ....");
            Console.ReadLine();
        }
示例#28
0
        private static OpcDaServer GetOrCreateServer(string opcServerUrl)
        {
            if (string.IsNullOrEmpty(opcServerUrl))
            {
                throw new Exception("URL is null or empty");
            }
            OpcDaServer server;

            if (servers.TryGetValue(opcServerUrl, out server))
            {
                return(server);
            }

            server = new OpcDaServer(UrlBuilder.Build(opcServerUrl));
            server.Connect();
            servers[opcServerUrl] = server;
            return(server);
        }
示例#29
0
        public static async Task <HttpResponse <TResult> > GetAsync <TResult, TSettings>(String baseAddress,
                                                                                         String requestUri, TSettings requestSettings,
                                                                                         IDictionary <String, IEnumerable <String> > headers = null,
                                                                                         ISerializer serializer  = null,
                                                                                         CancellationToken token = default(CancellationToken)) where TSettings : BaseRequestSettings
        {
            if (requestSettings != null)
            {
                if (requestUri == null)
                {
                    requestUri = "";
                }
                requestUri += "?" + UrlBuilder.Build(requestSettings);
            }
            var response = await GetBaseAsync(baseAddress, requestUri, headers, token).ConfigureAwait(false);

            return(await ParseResult <TResult>(serializer, response));
        }
示例#30
0
        public static async Task <HttpResponse <TResult> > GetAsync <TResult>(String baseAddress, String requestUri,
                                                                              IEnumerable <KeyValuePair <String, String> > nameValueCollection,
                                                                              IDictionary <String, IEnumerable <String> > headers = null,
                                                                              ISerializer serializer  = null,
                                                                              CancellationToken token = default(CancellationToken))
        {
            if (nameValueCollection != null)
            {
                if (requestUri == null)
                {
                    requestUri = "";
                }
                requestUri += "?" + UrlBuilder.Build(nameValueCollection);
            }
            var response = await GetBaseAsync(baseAddress, requestUri, headers, token).ConfigureAwait(false);

            return(await ParseResult <TResult>(serializer, response));
        }