public GymInlineQueryHandler(IUrlHelper urlHelper, IngressClient ingressClient, ITelegramBotClientEx bot, RaidBattlesContext db, RaidService raidService)
 {
     myUrlHelper     = urlHelper;
     myIngressClient = ingressClient;
     myBot           = bot;
     myDb            = db;
     myRaidService   = raidService;
 }
Esempio n. 2
0
 public GeneralInlineQueryHandler(ITelegramBotClientEx bot, IUrlHelper urlHelper, ShareInlineQueryHandler shareInlineQueryHandler, RaidService raidService, IngressClient ingressClient, RaidBattlesContext db)
 {
     myBot       = bot;
     myUrlHelper = urlHelper;
     myShareInlineQueryHandler = shareInlineQueryHandler;
     myRaidService             = raidService;
     myIngressClient           = ingressClient;
     myDb = db;
 }
Esempio n. 3
0
 public GymInlineQueryHandler(IUrlHelper urlHelper, GeneralInlineQueryHandler generalInlineQueryHandler, IngressClient ingressClient, ITelegramBotClientEx bot, RaidBattlesContext db, RaidService raidService, GeoCoderEx geoCoder, IClock clock, TimeZoneService timeZoneService)
 {
     myUrlHelper = urlHelper;
     myGeneralInlineQueryHandler = generalInlineQueryHandler;
     myIngressClient             = ingressClient;
     myBot             = bot;
     myDb              = db;
     myRaidService     = raidService;
     myGeoCoder        = geoCoder;
     myClock           = clock;
     myTimeZoneService = timeZoneService;
 }
Esempio n. 4
0
        public static void CreateClients(IEnumerable <OMFEndPoint> endPoints, bool useCompression = true)
        {
            if (!(endPoints?.Count() > 0))
            {
                string msg = "Must include at least one omf endpoint configuration";
                Logger.Write(msg);
                throw new ArgumentException(msg, nameof(endPoints));
            }

            //create client for each endpoint configuration
            foreach (OMFEndPoint endPoint in endPoints)
            {
                IngressClient ingressClient = new IngressClient(endPoint.URL, endPoint.ProducerToken);
                ingressClient.UseCompression = useCompression;
                OMFIngressHelper.ingressClients.Add(ingressClient, endPoint.Name);
            }
        }
Esempio n. 5
0
        static int Main(string[] args)
        {
            var options = new Options();
            var errors  = new List <Error>();
            var result  = Parser.Default.ParseArguments <Options>(args);

            result.WithParsed(opts => options = opts).WithNotParsed(errs => errors = errs.ToList());
            if (errors.Any())
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error.Tag);
                }
                return(1);
            }

            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string accountId         = appSettings["accountId"];
            string namespaceId       = appSettings["namespaceId"];
            string clusterAddress    = appSettings["address"];
            string ingressServiceUrl = clusterAddress + @"/api/omf";

            // Use a client secret, retrieved from the OSIsoft Cloud Services portal for your account, to
            // create a SecurityHandler used to authenticate this app.
            string resource        = appSettings["resource"];
            string clientId        = appSettings["clientId"];
            string clientSecret    = appSettings["clientSecret"];
            var    securityHandler = new SdsSecurityHandler(resource, accountId, clientId, clientSecret);

            // Create a client to manage OSIsoft Cloud Services Ingress resources.
            using (var managementClient = new IngressManagementClient(clusterAddress, accountId, securityHandler))
            {
                // Connect to a PI server and select PI points for which to move data to OCS.
                var piServerName = appSettings["PIDataArchive"];
                var piServer     = new PIServers()[piServerName];
                var points       = PIPoint.FindPIPoints(piServer, options.TagMask).ToList();
                if (!points.Any())
                {
                    Console.WriteLine($"No PI points found matching the tagMask query!");
                    return(1);
                }

                // Create OCS data ingress objects.
                string publisherName    = appSettings["publisherName"];
                string topicName        = appSettings["topicName"];
                string subscriptionName = appSettings["subscriptionName"];
                Console.WriteLine("Setting up OSIsoft Cloud Services OMF ingress objects.");
                string publisherId    = managementClient.GetOrCreatePublisherAsync(publisherName).GetAwaiter().GetResult();
                string producerToken  = managementClient.GetOrCreateToken(publisherId).GetAwaiter().GetResult();
                string topicId        = managementClient.GetOrCreateTopic(topicName, publisherId).GetAwaiter().GetResult();
                string subscriptionId = managementClient.GetOrCreateSubscription(subscriptionName, topicId, namespaceId).GetAwaiter().GetResult();

                // Each PI point type will be written to an OSIsoft Cloud Services(OCS) SDSStream.
                // The structure of each stream is defined by an OCS SDSType. We create this SDSType
                // by posting an OSIsoft Message Format(OMF) type message to OCS.
                // PI point value types need to translate to OCS SDSTypes. We create a limited number
                // of SDSTypes in OCS and then map PI point value types to those SDSTypes.
                // A mapping between PI point value types and the Ids of the SDSType that represents
                // them in OCS is shown below.
                Dictionary <OmfTypeCode, string> typeIdsByOmfType = new Dictionary <OmfTypeCode, string>();
                typeIdsByOmfType.Add(OmfTypeCode.Number, "numberValueAndTimestamp");
                typeIdsByOmfType.Add(OmfTypeCode.Integer, "integerValueAndTimestamp");
                typeIdsByOmfType.Add(OmfTypeCode.String, "stringValueAndTimestamp");
                typeIdsByOmfType.Add(OmfTypeCode.Time, "timeValueAndTimestamp");
                typeIdsByOmfType.Add(OmfTypeCode.ByteArray, "byteArrayValueAndTimestamp");

                using (var client = new IngressClient(ingressServiceUrl, producerToken)
                {
                    UseCompression = true
                })
                {
                    // Create and send OMF Type messages.
                    Console.WriteLine("Creating basic types in OCS to represent the format of PI points.");
                    List <OmfType> types = GetOmfTypes(typeIdsByOmfType);
                    var            omfTypeMessageContent = new OmfTypeMessageContent()
                    {
                        Types = types
                    };
                    client.SendMessageAsync(omfTypeMessageContent.ToByteArray(), MessageType.Type, MessageAction.Create).GetAwaiter().GetResult();

                    // Generate containers for each of the point with the correct OMF message type.
                    List <OmfContainer> containers = GetOmfContainers(points, typeIdsByOmfType);
                    if (options.WriteMode == Options.DataWriteMode.clearExistingData)
                    {
                        // Deleting the OMF container deletes the underlying SDSStream and its data.
                        Console.WriteLine("Deleting OMF containers corresponding to the selected PI points that existed before the sample was run.");
                        var omfContainerMessageContent = new OmfContainerMessageContent()
                        {
                            Containers = containers
                        };
                        client.SendMessageAsync(omfContainerMessageContent.ToByteArray(), MessageType.Container, MessageAction.Delete).GetAwaiter().GetResult();
                    }

                    Console.WriteLine("Creating corresponding containers for the PI points whose data will be written to OCS.");

                    // OSIsoft Cloud Services' OMF Ingress sets a size limit on the request accepted by its external endpoint. We may need to split, or chunk,
                    // containers into multiple OMF messages sent to the endpoint.
                    for (int chunkStartIndex = 0; chunkStartIndex < containers.Count; chunkStartIndex += MaxChunkSize)
                    {
                        int numberOfContainersToSendInThisChunk = Math.Min(containers.Count - chunkStartIndex, MaxChunkSize);
                        var containersToSendInThisChunk         = containers.GetRange(chunkStartIndex, numberOfContainersToSendInThisChunk).ToList();
                        var omfContainerMessageContent          = new OmfContainerMessageContent()
                        {
                            Containers = containersToSendInThisChunk
                        };
                        client.SendMessageAsync(omfContainerMessageContent.ToByteArray(), MessageType.Container, MessageAction.Create).GetAwaiter().GetResult();
                    }

                    // Write data from each PI point to a SDSStream.
                    foreach (PIPoint point in points)
                    {
                        Console.WriteLine($"Writing PI point data for point {point.Name} to OCS.");
                        string   containerId = GetContainerId(point);
                        AFValues values      = point.RecordedValues(new AFTimeRange(options.StartTime, options.EndTime), AFBoundaryType.Inside, null, true);

                        // OSIsoft Cloud Services' OMF Ingress sets a size limit on the request accepted by its external endpoint. We may need to split, or chunk,
                        // events into multiple OMF messages sent to the endpoint.
                        for (int chunkStartIndex = 0; chunkStartIndex < values.Count; chunkStartIndex += MaxChunkSize)
                        {
                            int numberOfEventsToReadForThisChunk = Math.Min(values.Count - chunkStartIndex, MaxChunkSize);

                            // If there are multiple events at a single timestamp for the PI point, the most recently added event will be written to OCS.
                            List <AFValue> distinctValuesInChunk = values.GetRange(chunkStartIndex, numberOfEventsToReadForThisChunk).GroupBy(value => value.Timestamp).Select(valuesAtTimestamp => valuesAtTimestamp.Last()).ToList();
                            List <PIData>  piDataEvents          = GetPIData(distinctValuesInChunk, ToOmfTypeCode(point.PointType));

                            OmfDataMessageContent omfDataMessageContent = new OmfDataMessageContent(containerId, piDataEvents);

                            Console.WriteLine($"Sending PI point data from index {distinctValuesInChunk.First().Timestamp} to index {distinctValuesInChunk.Last().Timestamp} to OCS ({distinctValuesInChunk.Count} values).");
                            client.SendMessageAsync(omfDataMessageContent.ToByteArray(), MessageType.Data, MessageAction.Create).GetAwaiter().GetResult();
                        }
                    }
                }

                // Delete OCS data ingress objects.
                if (options.DeleteIngressObjects)
                {
                    Console.WriteLine($"Deleting subscription with Id {subscriptionId}.");
                    managementClient.DeleteSubscription(subscriptionId).GetAwaiter().GetResult();
                    Console.WriteLine($"Deleting topic with Id {topicId}.");
                    managementClient.DeleteTopicAsync(topicId).GetAwaiter().GetResult();
                    Console.WriteLine($"Deleting publisher with Id {publisherId}.");
                    managementClient.DeletePublisherAsync(publisherId).GetAwaiter().GetResult();
                }
            }

            return(0);
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            // Set this up in your app.config
            string ingressServiceUrl = ConfigurationManager.AppSettings["IngressServiceUrl"];
            string producerToken     = ConfigurationManager.AppSettings["ProducerToken"];

            IngressClient client = new IngressClient(ingressServiceUrl, producerToken);

            // Use compression when sending data.  For such small sample messages, compression doesn't
            // save us much space, but we're doing it here for demonstration sake.
            client.UseCompression = true;


            // 1) Send the Types message
            client.CreateTypes(new string[] { SimpleType.JsonSchema });
            client.CreateTypes(new string[] { ComplexType.JsonSchema });


            // 2) Send the Streams message
            StreamInfo stream1 = new StreamInfo()
            {
                StreamId = "TestStream1", TypeId = "SimpleType"
            };
            StreamInfo stream2 = new StreamInfo()
            {
                StreamId = "TestStream2", TypeId = "SimpleType"
            };
            StreamInfo stream3 = new StreamInfo()
            {
                StreamId = "TestStream3", TypeId = "ComplexType"
            };

            client.CreateStreams(new StreamInfo[] { stream1, stream2, stream3 });


            // 3) Send the Values messages
            StreamValues complexValue = new StreamValues()
            {
                StreamId = stream3.StreamId,
                Values   = new List <ComplexType> {
                    ComplexType.CreateSampleValue()
                }
            };

            client.SendValuesAsync(new StreamValues[] { complexValue }).Wait();

            // Here we loop indefinitely, sending 10 time series events to two streams every second.
            while (true)
            {
                // Create our set of values to send to our streams
                List <SimpleType> values = new List <SimpleType>();
                for (int i = 0; i < 10; i++)
                {
                    values.Add(new SimpleType()
                    {
                        Time = DateTime.UtcNow, Value = i
                    });
                    Thread.Sleep(10);  // Offset the time-stamps by 10 ms
                }

                StreamValues vals1 = new StreamValues()
                {
                    StreamId = stream1.StreamId, Values = values
                };
                StreamValues vals2 = new StreamValues()
                {
                    StreamId = stream2.StreamId, Values = values
                };

                // Now send them
                client.SendValuesAsync(new StreamValues[] { vals1, vals2 }).Wait();

                Thread.Sleep(1000);
            }
        }
Esempio n. 7
0
 public PortalModel(RaidBattlesContext db, ZonedClock clock, IngressClient ingressClient)
 {
     myDb            = db;
     myClock         = clock;
     myIngressClient = ingressClient;
 }
Esempio n. 8
0
        static void Main(string[] args)
        {
            // Set this up in your app.config
            string ingressServiceUrl = ConfigurationManager.AppSettings["IngressServiceUrl"];
            string producerToken     = ConfigurationManager.AppSettings["ProducerToken"];

            IngressClient client = new IngressClient(ingressServiceUrl, producerToken);

            // Use compression when sending data.  For such small sample messages, compression doesn't
            // save us much space, but we're doing it here for demonstration sake.
            client.UseCompression = false;


            // Types can be classified under two different category:
            // Dynamic Type: Changes frequently (Temperature/Oil Level)
            // Static Type: Do not change frequently (Name)

            // 1) Send the Types message - DynamicType is a dynamic type
            client.CreateTypes(new string[] { DynamicType.JsonSchema });

            // 2) Send the Containers message - Container for dynamic type
            ContainerInfo stream1 = new ContainerInfo()
            {
                Id = "TestStream1", TypeId = "DynamicType"
            };
            ContainerInfo stream2 = new ContainerInfo()
            {
                Id = "TestStream2", TypeId = "DynamicType"
            };

            client.CreateContainers(new ContainerInfo[] { stream1, stream2 });

            // Send the Types messages for static type
            client.CreateTypes(new string[] { StaticType.JsonSchema });

            // Create couple of Static Type Data named Element
            List <StaticType> list = new List <StaticType>();

            for (int i = 1; i < 4; i++)
            {
                list.Add(new StaticType()
                {
                    Id = i.ToString(), Name = "Element" + i, Model = "A" + i
                });
            }

            StaticStreamValues staticStream = new StaticStreamValues()
            {
                TypeId = "StaticType", Values = list
            };

            //  __Link Type to link static data
            //  Source is the parent, Target is the child
            //  Head element need to be linked to _ROOT
            LinkType link1 = new LinkType()
            {
                Source = new SourceTarget()
                {
                    typeid = "StaticType", index = "_ROOT"
                },
                Target = new SourceTarget()
                {
                    typeid = "StaticType", index = "1"
                }
            };
            LinkType link2 = new LinkType()
            {
                Source = new SourceTarget()
                {
                    typeid = "StaticType", index = "1"
                },
                Target = new SourceTarget()
                {
                    typeid = "StaticType", index = "2"
                }
            };
            LinkType link3 = new LinkType()
            {
                Source = new SourceTarget()
                {
                    typeid = "StaticType", index = "2"
                },
                Target = new SourceTarget()
                {
                    typeid = "StaticType", index = "3"
                }
            };
            List <LinkType> list2 = new List <LinkType> {
                link1, link2, link3
            };

            // Send the static data
            StaticStreamValues linkStream = new StaticStreamValues()
            {
                TypeId = "__Link", Values = list2
            };


            client.SendValuesAsync2(new StaticStreamValues[] { staticStream, linkStream }).Wait();

            // Here we loop indefinitely, sending 10 time series events to two streams every second.
            while (true)
            {
                // Create our set of values to send to our streams
                List <DynamicType> values = new List <DynamicType>();
                for (int i = 0; i < 10; i++)
                {
                    values.Add(new DynamicType()
                    {
                        Time = DateTime.UtcNow, Value = i
                    });
                    Thread.Sleep(10);  // Offset the time-stamps by 10 ms
                }
                Console.Write("Running\n");
                DynamicStreamValues vals1 = new DynamicStreamValues()
                {
                    ContainerId = stream1.Id, Values = values
                };
                DynamicStreamValues vals2 = new DynamicStreamValues()
                {
                    ContainerId = stream2.Id, Values = values
                };

                // Now send them
                client.SendValuesAsync(new DynamicStreamValues[] { vals1, vals2 }).Wait();

                Thread.Sleep(1000);
            }
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            // get and parse json configuration file
            string  jsonConfig        = File.ReadAllText(Directory.GetCurrentDirectory() + "/config.json");
            dynamic jsonValues        = JObject.Parse(jsonConfig);
            string  ingressServiceUrl = jsonValues.endpoint;
            string  producerToken     = jsonValues.producertoken;
            int     delayInterval     = jsonValues.interval;

            // create Http client to send requests to ingress service
            IngressClient client = new IngressClient(ingressServiceUrl, producerToken);

            // Use compression when sending data.
            client.UseCompression = jsonValues.compressionGzip;

            // Send Type messages (both Static and Dynamic)
            client.CreateTypes(new string[] { FirstStaticType.JsonSchema, SecondStaticType.JsonSchema });
            client.CreateTypes(new string[] { FirstDynamicType.JsonSchema, SecondDynamicType.JsonSchema, ThirdDynamicType.JsonSchema });

            // Send Container messages
            Container[] streams =
            {
                new Container()
                {
                    Id = "Container1", TypeId = "FirstDynamicType"
                },
                new Container()
                {
                    Id = "Container2", TypeId = "FirstDynamicType"
                },
                new Container()
                {
                    Id = "Container3", TypeId = "SecondDynamicType"
                },
                new Container()
                {
                    Id = "Container4", TypeId = "ThirdDynamicType"
                }
            };
            client.CreateContainers(streams);

            // Send Assets in Data messages
            AssetLinkValues <FirstStaticType> assetParent = new AssetLinkValues <FirstStaticType>()
            {
                typeid = "FirstStaticType",
                Values = new List <FirstStaticType> {
                    new FirstStaticType()
                    {
                        index = "Asset1", name = "Parent element", StringProperty = "Parent element attribute value"
                    }
                }
            };

            client.SendValuesAsync(new AssetLinkValues <FirstStaticType>[] { assetParent }).Wait();

            AssetLinkValues <SecondStaticType> assetChild = new AssetLinkValues <SecondStaticType>()
            {
                typeid = "SecondStaticType",
                Values = new List <SecondStaticType> {
                    new SecondStaticType()
                    {
                        index = "Asset2", name = "Child element", StringProperty = "Child element attribute value"
                    }
                }
            };

            client.SendValuesAsync(new AssetLinkValues <SecondStaticType>[] { assetChild }).Wait();

            // Send Asset-to-child-Asset Links
            AssetLinkValues <AFLink <StaticElement, StaticElement> > dataLink = new AssetLinkValues <AFLink <StaticElement, StaticElement> >()
            {
                typeid = "__Link",
                Values = new List <AFLink <StaticElement, StaticElement> >   {
                    new AFLink <StaticElement, StaticElement>()
                    {
                        source = new StaticElement()
                        {
                            typeid = "FirstStaticType", index = "_ROOT"
                        }, target = new StaticElement()
                        {
                            typeid = "FirstStaticType", index = "Asset1"
                        }
                    },
                    new AFLink <StaticElement, StaticElement>()
                    {
                        source = new StaticElement()
                        {
                            typeid = "FirstStaticType", index = "Asset1"
                        }, target = new StaticElement()
                        {
                            typeid = "SecondStaticType", index = "Asset2"
                        }
                    }
                }
            };

            client.SendValuesAsync(new AssetLinkValues <AFLink <StaticElement, StaticElement> >[] { dataLink, }).Wait();

            // Send Asset-to-Data (i.e. Dynamic Attribute) Links
            AssetLinkValues <AFLink <StaticElement, DynamicElement> > dynamic_dataLink = new AssetLinkValues <AFLink <StaticElement, DynamicElement> >()
            {
                typeid = "__Link",
                Values = new List <AFLink <StaticElement, DynamicElement> >   {
                    new AFLink <StaticElement, DynamicElement>()
                    {
                        source = new StaticElement()
                        {
                            typeid = "FirstStaticType", index = "Asset1"
                        }, target = new DynamicElement()
                        {
                            containerid = "Container1"
                        }
                    },
                    new AFLink <StaticElement, DynamicElement>()
                    {
                        source = new StaticElement()
                        {
                            typeid = "SecondStaticType", index = "Asset2"
                        }, target = new DynamicElement()
                        {
                            containerid = "Container2"
                        }
                    },
                    new AFLink <StaticElement, DynamicElement>()
                    {
                        source = new StaticElement()
                        {
                            typeid = "SecondStaticType", index = "Asset2"
                        }, target = new DynamicElement()
                        {
                            containerid = "Container3"
                        }
                    },
                    new AFLink <StaticElement, DynamicElement>()
                    {
                        source = new StaticElement()
                        {
                            typeid = "SecondStaticType", index = "Asset2"
                        }, target = new DynamicElement()
                        {
                            containerid = "Container4"
                        }
                    }
                }
            };

            client.SendValuesAsync(new AssetLinkValues <AFLink <StaticElement, DynamicElement> >[] { dynamic_dataLink }).Wait();

            // Setting handler for Ctrl+C to exit sending data loop
            bool continueRunning = true;

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                continueRunning = false;
                Console.Write("Stopping... ");
                eventArgs.Cancel = true;
            };

            // simulate realtime data
            Random rint    = new Random();
            Random rdouble = new Random();
            string string_boolean_value = "True";
            int    integer_enum_value   = 0;

            // Now send simulated relatime data continously
            while (continueRunning)
            {
                // Create set of integers to send to streams
                List <FirstDynamicType> values = new List <FirstDynamicType>();
                for (int i = 0; i < 3; i++)
                {
                    values.Add(new FirstDynamicType()
                    {
                        timestamp = DateTime.UtcNow, IntegerProperty = rint.Next()
                    });
                    Thread.Sleep(10);  // Offset the time-stamps by 10 ms
                }
                DataValues vals1 = new DataValues()
                {
                    ContainerId = streams[0].Id, Values = values
                };
                DataValues vals2 = new DataValues()
                {
                    ContainerId = streams[1].Id, Values = values
                };
                // Now send them
                client.SendValuesAsync(new DataValues[] { vals1, vals2 }).Wait();

                // Create set of SecondDynamicType values to send to streams
                List <SecondDynamicType> fnumbers = new List <SecondDynamicType>();
                for (int i = 0; i < 3; i++)
                {
                    string_boolean_value = (string_boolean_value == "True") ? "False" : "True";
                    fnumbers.Add(new SecondDynamicType()
                    {
                        timestamp = DateTime.UtcNow, NumberProperty1 = rdouble.NextDouble(), NumberProperty2 = rdouble.NextDouble(), StringEnum = string_boolean_value
                    });
                    Thread.Sleep(10);  // Offset the time-stamps by 10 ms
                }
                DataValues nums = new DataValues()
                {
                    ContainerId = streams[2].Id, Values = fnumbers
                };
                client.SendValuesAsync(new DataValues[] { nums }).Wait();


                // Create set of ThirdDynamicType values to send to streams
                List <ThirdDynamicType> enumvalues = new List <ThirdDynamicType>();
                for (int i = 0; i < 3; i++)
                {
                    integer_enum_value = (integer_enum_value == 0) ? 1 : 0;
                    enumvalues.Add(new ThirdDynamicType()
                    {
                        timestamp = DateTime.UtcNow, IntegerEnum = integer_enum_value
                    });
                    Thread.Sleep(10);  // Offset the time-stamps by 10 ms
                }
                DataValues bvals = new DataValues()
                {
                    ContainerId = streams[3].Id, Values = enumvalues
                };
                client.SendValuesAsync(new DataValues[] { bvals }).Wait();

                Thread.Sleep(delayInterval);
            }
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            // get and parse json configuration file
            string  jsonConfig        = File.ReadAllText(Directory.GetCurrentDirectory() + "/config.json");
            dynamic jsonValues        = JObject.Parse(jsonConfig);
            string  ingressServiceUrl = jsonValues.endpoint;
            string  producerToken     = jsonValues.producertoken;
            int     delayInterval     = jsonValues.interval;

            consumerKey       = jsonValues.ConsumerKey;
            consumerSecret    = jsonValues.ConsumerSecret;
            accessToken       = jsonValues.AccessToken;
            accessTokenSecret = jsonValues.AccessTokenSecret;

            Auth.SetUserCredentials(consumerKey, consumerSecret, accessToken, accessTokenSecret);

            _stream = Tweetinvi.Stream.CreateFilteredStream();
            _stream.AddTweetLanguageFilter(LanguageFilter.English);

            //_stream.AddTrack("california fire");
            //_stream.AddTrack("green fish");

            List <string> tracks = jsonValues.Tracks.ToObject <List <string> >();

            int id = 1;

            foreach (string track in tracks)
            {
                _stats.Add(new TrackStat
                {
                    Id         = id++,
                    TrackValue = track
                });
                _stream.AddTrack(track);
            }
            _periodStart = QuantizeTime(DateTime.Now);

            _stream.MatchingTweetReceived += (sender, tweetArgs) =>
            {
                //CheckTime();    // need to do this on a timer

                var sanitized = Sanitize(tweetArgs.Tweet.FullText);
                //var sentence = new Sentence(sanitized);

                //Console.WriteLine(tweetArgs.Tweet.CreatedBy.Name);
                Console.WriteLine(tweetArgs.Tweet.Text);
                Console.WriteLine(String.Join(";", tweetArgs.MatchingTracks));

                TrackStat stat;
                foreach (string track in tweetArgs.MatchingTracks)
                {
                    stat = _stats.Where(x => x.TrackValue == track).FirstOrDefault();
                    if (stat != null)
                    {
                        ++stat.TweetCount;
                    }
                }

                //Console.WriteLine(sentence.Sentiment);
            };

            _stream.UnmanagedEventReceived += (sender, eventArgs) => {
                Console.WriteLine("unmanaged event received");
            };
            _stream.DisconnectMessageReceived += (sender, disconnectedArgs) =>
            {
                Console.WriteLine("received disconnected message");
                //Console.WriteLine(disconnectedArgs.DisconnectMessage);
            };

            _stream.JsonObjectReceived += (sender, jsonArgs) =>
            {
                //Console.WriteLine(jsonArgs.Json);
            };

            _stream.KeepAliveReceived += (sender, eventArgs) => {
                Console.WriteLine("received keep alive");
            };

            _stream.LimitReached += (sender, eventArgs) => {
                Console.WriteLine("limit reached");
            };

            _stream.WarningFallingBehindDetected += (sender, eventArgs) => {
                Console.WriteLine("fall behind warning");
            };


            // create Http client to send requests to ingress service
            _client = new IngressClient(ingressServiceUrl, producerToken);

            // Use compression when sending data.
            _client.UseCompression = jsonValues.compressionGzip;

            Setup();


            /*
             *          // Send Type messages (both Static and Dynamic)
             *          _client.CreateTypes(new string[] { FirstStaticType.JsonSchema, SecondStaticType.JsonSchema } );
             *          _client.CreateTypes(new string[] { FirstDynamicType.JsonSchema, SecondDynamicType.JsonSchema, ThirdDynamicType.JsonSchema });
             *
             *          // Send Container messages
             *          Container[] streams = {
             *              new Container() { Id = "Container1", TypeId = "FirstDynamicType" },
             *              new Container() { Id = "Container2", TypeId = "FirstDynamicType" },
             *              new Container() { Id = "Container3", TypeId = "SecondDynamicType"},
             *              new Container() { Id = "Container4", TypeId = "ThirdDynamicType" }
             *          };
             *          _client.CreateContainers(streams);
             *
             *          // Send Assets in Data messages
             *          AssetLinkValues<FirstStaticType> assetParent = new AssetLinkValues<FirstStaticType>()
             *          {
             *              typeid = "FirstStaticType",
             *              Values = new List<FirstStaticType> { new FirstStaticType()
             *                  {  index="Asset1", name="Parent element", StringProperty="Parent element attribute value"  }
             *              }
             *          };
             *          _client.SendValuesAsync(new AssetLinkValues<FirstStaticType>[] { assetParent}).Wait();
             *
             *          AssetLinkValues<SecondStaticType> assetChild = new AssetLinkValues<SecondStaticType>()
             *          {
             *              typeid = "SecondStaticType",
             *              Values = new List<SecondStaticType> { new SecondStaticType()
             *                  { index="Asset2", name="Child element", StringProperty="Child element attribute value"  }
             *              }
             *          };
             *          _client.SendValuesAsync(new AssetLinkValues<SecondStaticType>[] { assetChild }).Wait();
             *
             *          // Send Asset-to-child-Asset Links
             *          AssetLinkValues<AFLink<StaticElement,StaticElement>> dataLink = new AssetLinkValues<AFLink<StaticElement, StaticElement>>()
             *          {
             *              typeid = "__Link",
             *              Values = new List<AFLink<StaticElement, StaticElement>>   {
             *                  new AFLink<StaticElement,StaticElement>() {source = new StaticElement() {typeid = "FirstStaticType", index = "_ROOT" }, target = new StaticElement() {typeid= "FirstStaticType", index= "Asset1" } },
             *                  new AFLink<StaticElement,StaticElement>() {source = new StaticElement() {typeid = "FirstStaticType", index = "Asset1" }, target = new StaticElement() {typeid= "SecondStaticType", index= "Asset2" } }
             *              }
             *          };
             *          _client.SendValuesAsync(new AssetLinkValues<AFLink<StaticElement, StaticElement>>[] { dataLink, }).Wait();
             *
             *          // Send Asset-to-Data (i.e. Dynamic Attribute) Links
             *          AssetLinkValues<AFLink<StaticElement, DynamicElement>> dynamic_dataLink = new AssetLinkValues<AFLink<StaticElement, DynamicElement>>()
             *          {
             *              typeid = "__Link",
             *              Values = new List<AFLink<StaticElement, DynamicElement>>   {
             *                  new AFLink<StaticElement, DynamicElement>(){ source = new StaticElement() { typeid = "FirstStaticType", index= "Asset1" },target= new DynamicElement() { containerid ="Container1" } },
             *                  new AFLink<StaticElement, DynamicElement>(){ source = new StaticElement() { typeid = "SecondStaticType", index= "Asset2" },target= new DynamicElement() { containerid ="Container2" } },
             *                  new AFLink<StaticElement, DynamicElement>(){ source = new StaticElement() { typeid = "SecondStaticType", index= "Asset2" },target= new DynamicElement() { containerid ="Container3" } },
             *                  new AFLink<StaticElement, DynamicElement>(){ source = new StaticElement() { typeid = "SecondStaticType", index= "Asset2" },target= new DynamicElement() { containerid ="Container4" } }
             *              }
             *          };
             *          _client.SendValuesAsync(new AssetLinkValues<AFLink<StaticElement, DynamicElement>>[] { dynamic_dataLink }).Wait();
             */

            // Setting handler for Ctrl+C to exit sending data loop
            bool           continueRunning = true;
            AutoResetEvent exitEvent       = new AutoResetEvent(false);

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                continueRunning = false;
                Console.Write("Stopping... ");
                eventArgs.Cancel = true;
                _stream.StopStream();
                exitEvent.Set();
            };

            _timer = new System.Timers.Timer(5000)
            {
                AutoReset = false
            };

            _timer.Elapsed += (s, e) => CheckTime();
            _timer.Start();

            _stream.StartStreamMatchingAnyCondition();

            exitEvent.WaitOne();

            return;

/*
 *          // simulate realtime data
 *          Random rint = new Random();
 *          Random rdouble = new Random();
 *          string string_boolean_value = "True";
 *          int    integer_enum_value = 0;
 *
 *          // Now send simulated relatime data continously
 *          while (continueRunning)
 *          {
 *              // Create set of integers to send to streams
 *              List<FirstDynamicType> values = new List<FirstDynamicType>();
 *              for(int i = 0; i < 3; i++)
 *              {
 *                  values.Add(new FirstDynamicType() { timestamp = DateTime.UtcNow, IntegerProperty = rint.Next() });
 *                  Thread.Sleep(10);  // Offset the time-stamps by 10 ms
 *              }
 *              DataValues vals1 = new DataValues() { ContainerId = streams[0].Id, Values = values };
 *              DataValues vals2 = new DataValues() { ContainerId = streams[1].Id, Values = values };
 *              // Now send them
 *              //client.SendValuesAsync(new DataValues[] { vals1, vals2 }).Wait();
 *
 *              // Create set of SecondDynamicType values to send to streams
 *              List<SecondDynamicType> fnumbers = new List<SecondDynamicType>();
 *              for (int i = 0; i < 3; i++)
 *              {
 *                  string_boolean_value = (string_boolean_value == "True") ? "False" : "True";
 *                  fnumbers.Add(new SecondDynamicType() { timestamp = DateTime.UtcNow, NumberProperty1 = rdouble.NextDouble(), NumberProperty2= rdouble.NextDouble(), StringEnum = string_boolean_value });
 *                  Thread.Sleep(10);  // Offset the time-stamps by 10 ms
 *              }
 *              DataValues nums = new DataValues() { ContainerId = streams[2].Id, Values = fnumbers };
 *              //client.SendValuesAsync(new DataValues[] { nums }).Wait();
 *
 *
 *              // Create set of ThirdDynamicType values to send to streams
 *              List<ThirdDynamicType> enumvalues = new List<ThirdDynamicType>();
 *              for (int i = 0; i < 3; i++)
 *              {
 *                  integer_enum_value = (integer_enum_value == 0) ? 1 : 0;
 *                  enumvalues.Add(new ThirdDynamicType() { timestamp = DateTime.UtcNow,  IntegerEnum = integer_enum_value });
 *                  Thread.Sleep(10);  // Offset the time-stamps by 10 ms
 *              }
 *              DataValues bvals = new DataValues() { ContainerId = streams[3].Id, Values = enumvalues };
 *              //client.SendValuesAsync(new DataValues[] { bvals }).Wait();
 *
 *              Thread.Sleep(delayInterval);
 *          }
 */
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
                                            .SetBasePath(Directory.GetCurrentDirectory())
                                            .AddJsonFile("appsettings.json");
            IConfiguration configuration = builder.Build();

            // ==== Client constants ====
            string tenantId     = configuration["TenantId"];
            string namespaceId  = configuration["NamespaceId"];
            string address      = configuration["Address"];
            string clientId     = configuration["ClientId"];
            string clientSecret = configuration["ClientSecret"];

            IngressClient client = new IngressClient(address, tenantId, namespaceId, clientId, clientSecret);

            // Use compression when sending data.  For such small sample messages, compression doesn't
            // save us much space, but we're doing it here for demonstration sake.
            client.UseCompression = true;


            // 1) Send the Types message
            client.CreateTypes(new string[] { SimpleType.JsonSchema });
            client.CreateTypes(new string[] { ComplexType.JsonSchema });


            // 2) Send the Containers message
            ContainerInfo stream1 = new ContainerInfo()
            {
                Id = "TestStream1", TypeId = "SimpleType"
            };
            ContainerInfo stream2 = new ContainerInfo()
            {
                Id = "TestStream2", TypeId = "SimpleType"
            };
            ContainerInfo stream3 = new ContainerInfo()
            {
                Id = "TestStream3", TypeId = "ComplexType"
            };

            client.CreateContainers(new ContainerInfo[] { stream1, stream2, stream3 });


            // 3) Send the Values messages
            StreamValues complexValue = new StreamValues()
            {
                ContainerId = stream3.Id,
                Values      = new List <ComplexType> {
                    ComplexType.CreateSampleValue()
                }
            };

            client.SendValuesAsync(new StreamValues[] { complexValue }).Wait();

            // Here we loop indefinitely, sending 10 time series events to two streams every second.
            while (true)
            {
                // Create our set of values to send to our streams
                List <SimpleType> values = new List <SimpleType>();
                for (int i = 0; i < 10; i++)
                {
                    values.Add(new SimpleType()
                    {
                        Time = DateTime.UtcNow, Value = i
                    });
                    Thread.Sleep(10);  // Offset the time-stamps by 10 ms
                }

                StreamValues vals1 = new StreamValues()
                {
                    ContainerId = stream1.Id, Values = values
                };
                StreamValues vals2 = new StreamValues()
                {
                    ContainerId = stream2.Id, Values = values
                };

                // Now send them
                client.SendValuesAsync(new StreamValues[] { vals1, vals2 }).Wait();

                Thread.Sleep(1000);
            }
        }