示例#1
0
        private void DataSynchEntity(object entity, string oper)
        {
            if (entity == null)
            {
                return;
            }
            RealtimeData data = new RealtimeData();

            data.Oper = oper;
            data.Type = "position";
            if (entity is OrgPosition)
            {
                OrgPosition        position  = entity as OrgPosition;
                List <OrgPosition> positions = new List <OrgPosition>();
                positions.Add(position);
                data.Data = positions;
            }
            else if (entity is List <OrgPosition> )
            {
                List <OrgPosition> positions = entity as List <OrgPosition>;
                data.Data = positions;
            }
            this._eventBus.PublishAsync(new RealtimeSynEvent(data));
            //RealtimeSynchServiceFactory.GetInstance().EnqueueQueue(data);
        }
示例#2
0
        private void DataSynchEntity(object entity, string oper)
        {
            if (entity == null)
            {
                return;
            }
            RealtimeData data = new RealtimeData();

            data.Oper = oper;
            data.Type = "dept";
            if (entity is OrgDept)
            {
                OrgDept        orgDept  = entity as OrgDept;
                List <OrgDept> orgDepts = new List <OrgDept>();
                orgDepts.Add(orgDept);
                data.Data = orgDepts;
            }
            else if (entity is List <OrgDept> )
            {
                List <OrgDept> orgDepts = entity as List <OrgDept>;
                data.Data = orgDepts;
            }

            RealtimeSynchServiceFactory.GetInstance().EnqueueQueue(data);
        }
        private DataTable ToDataTable(RealtimeData response, string name = "GA")
        {
            var requestResultTable = new DataTable(name);

            if (response != null)
            {
                requestResultTable.Columns.AddRange(response.ColumnHeaders.Select(x => new DataColumn(GaMetadata.RemoveRealtimePrefix(x.Name), GetDataType(x))).ToArray());

                if (response.Rows != null)
                {
                    foreach (var row in response.Rows)
                    {
                        var dtRow = requestResultTable.NewRow();

                        for (var idx = 0; idx != requestResultTable.Columns.Count; idx++)
                        {
                            var col = requestResultTable.Columns[idx];
                            if (col.DataType == typeof(DateTime))
                            {
                                dtRow.SetField(col, DateTime.ParseExact(row[idx], "yyyyMMdd", new DateTimeFormatInfo(), DateTimeStyles.AssumeLocal));
                            }
                            else
                            {
                                dtRow.SetField(col, row[idx]);
                            }
                        }
                        requestResultTable.Rows.Add(dtRow);
                    }
                }
                requestResultTable.AcceptChanges();
            }
            return(requestResultTable);
        }
示例#4
0
        private static List <string> CreateData(string metricName, RealtimeData data)
        {
            var rows = data.Rows.ToList();

            List <string> rts = new List <string>();

            foreach (var item in rows)
            {
                var t = new RealtimeElkData()
                {
                    MetricName = metricName,
                    Country    = item[0],
                    Region     = item[1],
                    City       = item[2],
                    DeviceType = item[3],
                    Loc        = new Location()
                    {
                        lat = item[4],
                        lon = item[5]
                    },
                    Value         = Convert.ToInt32(item[6]),
                    SiteProfileId = data.ProfileInfo.ProfileId,
                    ProfileName   = data.ProfileInfo.ProfileName,
                    timestamp     = DateTime.UtcNow.ToString("O")
                };

                rts.Add("{ \"index\":{ \"_id\": \"" + t.id + "\"} }");
                rts.Add(JsonConvert.SerializeObject(t));
            }

            return(rts);
        }
示例#5
0
        /// <summary>
        /// Requests data each time the period specified by Interval has elapsed.
        /// </summary>
        public async override Task RequestData()
        {
            try {
                Google.Apis.Analytics.v3.Data.RealtimeData rt   = GetRequest.Execute();
                List <Dictionary <string, string> >        data = RealtimeData.GetData(rt);

                // Gets the date of the latest dataset in order to only add newer data.
                List <IInfluxSeries> last = await InfluxClient.QueryMultiSeriesAsync(DatabaseName, "SELECT last(*) FROM " + MeasurementName);

                DateTime now    = DateTime.UtcNow;
                DateTime New    = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
                DateTime?latest = last.FirstOrDefault()?.Entries[0].Time;

                List <InfluxDatapoint <InfluxValueField> > list = new List <InfluxDatapoint <InfluxValueField> >();
                foreach (Dictionary <string, string> dict in data)
                {
                    if (latest == null)
                    {
                        list.Add((InfluxDatapoint <InfluxValueField>) typeof(T).GetMethod("CreateInfluxDatapoint").Invoke(null, new object[] { MeasurementName, dict }));
                    }
                    else
                    {
                        // Necessary since nanoseconds cannot be set and will cause one date to be greater than the other although all (visible) parameters are equal.
                        if (New.Subtract(new TimeSpan(0, Convert.ToInt32(dict["rt:minutesAgo"]), 0)) > latest)
                        {
                            list.Add((InfluxDatapoint <InfluxValueField>) typeof(T).GetMethod("CreateInfluxDatapoint").Invoke(null, new object[] { MeasurementName, dict }));
                        }
                    }
                    await WriteToDatabase(list);
                }
            }
            catch (Exception ex) {
                Console.WriteLine("Error trying to request Google Analytics data: " + ex.Message);
            }
        }
示例#6
0
        public IEnumerable <T> Convert(RealtimeData data)
        {
            var results = new List <T>();

            if (data.Rows != null)
            {
                foreach (var row in data.Rows)
                {
                    var result = new T();

                    for (var i = 0; i < row.Count; i++)
                    {
                        var header = data.ColumnHeaders[i];
                        var name   = GetPropertyName(header.Name);

                        var type     = typeof(T);
                        var property = type.GetProperty(name);
                        if (property != null)
                        {
                            property.SetValue(result, row[i], null);
                        }
                    }

                    results.Add(result);
                }
            }
            return(results);
        }
示例#7
0
        public RealtimeDataPoint GetRealtimeData(string[] dimensions, string[] metrics)
        {
            RealtimeDataPoint data = new RealtimeDataPoint();

            //Make initial call to service.
            //Then check if a next link exists in the response,
            //if so parse and call again using start index param.
            RealtimeData response = null;

            var request = BuildRealtimeRequest(ProfileID, dimensions, metrics);

            response           = request.Execute();
            data.ColumnHeaders = response.ColumnHeaders;

            if (response.Rows != null)
            {
                data.Rows.AddRange(response.Rows);
            }
            else
            {
                data.Rows.Add(new string[] { "0" });
            }

            return(data);
        }
        public void SetValues(RealtimeData data)
        {
            if (data == null || data.Rows == null)
                return;
            
            var userCount = data.TotalsForAllResults[GAMetrics.RealTimeActiveUsers];
            if (userCount != null)
                TotalUsers = Convert.ToInt32(userCount);

            int cityColumIndex = 0;
            int countColumIndex = 1;

            for (int i = 0; i < data.ColumnHeaders.Count; i++)
            {
                if (data.ColumnHeaders[i].Name == GADimensions.RealTimeCity)
                    cityColumIndex = i;
                else if (data.ColumnHeaders[i].Name == GAMetrics.RealTimeActiveUsers)
                    countColumIndex = i;
            }

            int cityCount = 0;
            foreach (var row in data.Rows)
            {
                if (cityCount < 5)
                {
                    string key = row[cityColumIndex];
                    int value = Convert.ToInt32(row[countColumIndex]);
                    Cities.Add(key, value);
                }
                else
                    break;
                cityCount++;
            }
        }
示例#9
0
 private void pushData(RecvRealtimeData rrd, RealtimeData rd)
 {
     lock (lockData)
     {
         this.dcPushData[rrd].Add(rd);
     }
 }
示例#10
0
        /// <summary>
        /// Returns real-time Google Analytics data for a view (profile).
        /// https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime/get
        ///
        ///
        /// Beta:
        /// The Real Time Reporting API is currently available as a developer preview in limited beta. If you're interested in signing up, request access to the beta.
        /// https://docs.google.com/forms/d/1qfRFysCikpgCMGqgF3yXdUyQW4xAlLyjKuOoOEFN2Uw/viewform
        /// Apply for access wait 24 hours and then try you will not hear from Google when you have been approved.
        ///
        /// Documentation: Dimension and metric reference https://developers.google.com/analytics/devguides/reporting/realtime/dimsmets/
        /// </summary>
        /// <param name="service">Valid authenticated Google analytics service</param>
        /// <param name="profileId">Profile id to request data from </param>
        /// <param name="metrics">Valid Real time Metrics (Required)</param>
        /// <param name="optionalValues">Optional values can be null</param>
        /// <returns>https://developers.google.com/analytics/devguides/reporting/realtime/v3/reference/data/realtime#resource</returns>
        public static RealtimeData Get(AnalyticsService service, string profileId, string metrics, OptionalValues optionalValues)
        {
            try
            {
                DataResource.RealtimeResource.GetRequest request = service.Data.Realtime.Get(String.Format("ga:{0}", profileId), metrics);
                request.MaxResults = 10000;


                if (optionalValues != null)
                {
                    request.Dimensions = optionalValues.Dimensions;
                    request.Sort       = optionalValues.Sort;
                    request.Filters    = optionalValues.Filter;
                }


                RealtimeData feed = request.Execute();

                return(feed);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
示例#11
0
        private GetUpcomingTrainsResponse.Types.UpcomingTrain ToUpcomingTrain(RealtimeData realtimeData)
        {
            TrainStatus status = TrainStatus.OnTime;

            if (realtimeData.ArrivalTimeMessage.Trim().Equals("0 min", StringComparison.InvariantCultureIgnoreCase))
            {
                status = TrainStatus.ArrivingNow;
            }
            else if (realtimeData.ArrivalTimeMessage.Trim().Equals("Delayed", StringComparison.InvariantCultureIgnoreCase))
            {
                status = TrainStatus.Delayed;
            }

            var upcomingTrain = new GetUpcomingTrainsResponse.Types.UpcomingTrain()
            {
                LineName         = realtimeData.Headsign,
                Headsign         = realtimeData.Headsign,
                ProjectedArrival = this.ToTimestamp(realtimeData.ExpectedArrival),
                LastUpdated      = this.ToTimestamp(realtimeData.LastUpdated),
                Status           = status
            };

            if (realtimeData.Route != null)
            {
                upcomingTrain.Route            = realtimeData.Route.Route;
                upcomingTrain.RouteDisplayName = realtimeData.Route.DisplayName;
                upcomingTrain.Direction        = RouteMappings.RouteDirectionToDirection[realtimeData.Route.Direction];
            }
            upcomingTrain.LineColors.Add(realtimeData.LineColors);
            return(upcomingTrain);
        }
示例#12
0
        public async Task <RealtimeData> AddSourcesAsync(RealtimeData data, CancellationToken token)
        {
            var refData = await GetReferenceData(token).ConfigureAwait(false);

            data.Sources = refData.CISSource.ToDictionary(r => r.code, r => r.name);
            return(data);
        }
示例#13
0
        public async Task <RealtimeData> AddReasonsAsync(RealtimeData data, CancellationToken token)
        {
            var refData = await GetReferenceData(token).ConfigureAwait(false);

            data.CancelReasons      = refData.CancellationReasons.ToDictionary(r => r.code, r => r.reasontext);
            data.LateRunningReasons = refData.LateRunningReasons.ToDictionary(r => r.code, r => r.reasontext);
            return(data);
        }
示例#14
0
        public static async Task test()
        {
            Console.WriteLine("Start");

            var context     = new WienerLinienContext("O56IE8eH7Kf5R5aQ");
            var allStations = await Stations.GetAllStationsAsync();

            //initialize the RealtimeData object using the created context
            var rtd = new RealtimeData(context);

            var listRbls = new List <int>();

            foreach (var v in allStations)
            {
                if (v.Name.Equals("Pilgramgasse"))
                {
                    foreach (var v2 in v.Platforms)
                    {
                        if (v2.Name.Equals("12A"))
                        {
                            listRbls.Add(v2.RblNumber);
                        }
                    }
                    break;
                }
            }

            //Create a Parameters object to include the Rbls  and get Realtime Data for them
            var parameters = new Parameters.MonitorParameters()
            {
                Rbls = listRbls
            };

            //Get the monitor informatino asynchronous, and save them as MonitorData class
            var monitorInfo = await rtd.GetMonitorDataAsync(parameters);

            foreach (var v in monitorInfo.Data.Monitors)
            {
                foreach (var v2 in v.Lines)
                {
                    Console.WriteLine();
                    Console.WriteLine(v2.Name);
                    foreach (var v3 in v2.Departures.Departure)
                    {
                        Console.WriteLine(v3.DepartureTime.Countdown);
                    }
                    Console.WriteLine();
                }
            }

            //Get the planned arrival time for the first line and the next vehicle arriving (index at Departure)
            //var plannedTime = monitorInfo.Data.Monitors[0].Lines[0].Departures.Departure[0].DepartureTime.TimePlanned;


            Console.WriteLine("Finished");
            Console.ReadKey();
        }
 /// <summary>
 /// 插入实时数据表(REALTIME_DATA)与历史数据表(HISTORICAL_DATA)
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 public string InsertData(RealtimeData entity)
 {
     try
     {
         return(_iRealtimeDataDao.Insert(entity));
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
示例#16
0
        private async Task ProcessNewMessage(Station station, Message message)
        {
            try
            {
                RouteDirection direction  = Enum.Parse <RouteDirection>(message.Label, true);
                DateTime       expiration = DateTime.UtcNow.AddMinutes(2);
                try
                {
                    expiration = message.ExpiresAtUtc.AddMinutes(2); // Add two minutes as a buffer.
                }
                catch (Exception) { /* Ignore. */ }
                ServiceBusMessage messageBody       = JsonConvert.DeserializeObject <ServiceBusMessage>(Encoding.UTF8.GetString(message.Body));
                Tuple <Station, RouteDirection> key = this.MakeKey(station, direction);

                List <RealtimeData> newData = (await Task.WhenAll(messageBody.Messages.Select(async realtimeMessage =>
                {
                    var realtimeData = new RealtimeData()
                    {
                        ExpectedArrival = realtimeMessage.LastUpdated.AddSeconds(realtimeMessage.SecondsToArrival),
                        ArrivalTimeMessage = realtimeMessage.ArrivalTimeMessage,
                        Headsign = realtimeMessage.Headsign,
                        LastUpdated = realtimeMessage.LastUpdated,
                        LineColors = realtimeMessage.LineColor.Split(',').Where(color => !string.IsNullOrWhiteSpace(color)).ToList(),
                        DataExpiration = expiration
                    };

                    RouteLine route = null;
                    try
                    {
                        route = await this.pathDataRepository.GetRouteFromTrainHeadsign(realtimeData.Headsign, realtimeData.LineColors);
                    }
                    catch (Exception ex)
                    {
                        Log.Logger.Here().Warning(ex, "Failed to lookup route during realtime message update.");
                    }
                    realtimeData.Route = route;
                    return(realtimeData);
                }))).ToList();
                this.realtimeData.AddOrUpdate(key, newData, (ignored, oldData) => newData[0].LastUpdated > oldData[0].LastUpdated ? newData : oldData);
            }
            catch (Exception ex)
            {
                Log.Logger.Here().Error(ex, $"Unexpected error reading a service bus message for {station}.");
            }
        }
示例#17
0
        private void DataSynchDynamicObject(dynamic dynamicData, string oper)
        {
            if (dynamicData == null)
            {
                return;
            }

            RealtimeData data = new RealtimeData();

            data.Oper = oper;
            data.Type = "position";
            List <dynamic> positions = new List <dynamic>();

            //positions.Add(BaseModel.ToEntity<OrgPosition>(dynamicData));
            positions.Add(dynamicData);
            data.Data = positions;

            RealtimeSynchServiceFactory.GetInstance().EnqueueQueue(data);
        }
示例#18
0
        private void DataSynchDynamicObject(dynamic dynamicData, string oper)
        {
            if (dynamicData == null)
            {
                return;
            }

            RealtimeData data = new RealtimeData();

            data.Oper = oper;
            data.Type = "dept";
            List <dynamic> orgDepts = new List <dynamic>();

            //orgDepts.Add(BaseModel.ToEntity<OrgDept>(dynamicData));
            orgDepts.Add(dynamicData);
            data.Data = orgDepts;
            this._eventBus.PublishAsync(new RealtimeSynEvent(data));
            //RealtimeSynchServiceFactory.GetInstance().EnqueueQueue(data);
        }
 void SendData(WebSocket w, RealtimeData data)
 {
     // Send JSON string
     w.SendString(JsonConvert.SerializeObject(data));
 }
        public ActionResult EditCarInfoForm(CarInfo carInfo, string Hid_TerNo, string Hid_OldCarno, string TypeName, string flag)
        {
            new LogMessage().Save("CarNo:" + carInfo.CarNo + ";");
            UserInfo user = (UserInfo)Session["LoginUser"];

            if (carInfo.Businessdivisionid != null || carInfo.Businessdivisionid.Trim() != "")
            {
                DeptInfo di = deptInfoBll.GetDeptInfo(carInfo.Businessdivisionid);
                carInfo.CarDeptcode = di.Businessdivisioncode;
            }
            carInfo.Description = carInfo.Description.Trim();

            string carhbinfo = "";

            if (carInfo.CarColor != "" || TypeName != "")
            {
                string cartypename = "";
                if (TypeName.Split('-').Length == 1)
                {
                    cartypename = TypeName.Split('-')[0];
                }
                else
                {
                    cartypename = TypeName.Split('-')[2] == null ? "" : TypeName.Split('-')[2];
                }
                carhbinfo = cartypename + "|" + carInfo.CarColor + "|||||||||||||||||||||||||||||";
            }

            RealtimeData rdinfo = realtimedatabll.GetRealtimeData(Hid_TerNo);

            if (rdinfo.Rawdataid != null && rdinfo.Rawdataid != "")
            {
                string NewCarno = carInfo.CarNo;
                carInfo.CarNo = Hid_OldCarno;
                string kku = carInfoBll.UpdateCarType(carInfo, TypeName);
                ViewBag.Result = kku;

                //修改联动车辆发送的指令
                Transfers.ClintSendCommData(1107, "551", "", Hid_OldCarno, "", "", "", "", "", "", "", carInfo.CarDeptcode, NewCarno, carhbinfo, carInfo.CarAdminName, carInfo.CarFrame, "", "", user.UserName);
                System.Threading.Thread.Sleep(2000);
            }
            else
            {
                ArrayList arr = new ArrayList();
                arr.Add(carInfo);
                string kku = carInfoBll.UpdateCarInfo(arr, TypeName);
                ViewBag.Result = kku;
                //修改普通车辆发送的指令
                TerminalInfoBLL      terbll      = new TerminalInfoBLL();
                IList <TerminalInfo> terinfolist = terbll.GetTerminalInfoByCarId(carInfo.CarId);
                foreach (TerminalInfo terinfo in terinfolist)
                {
                    if (terinfo != null && terinfo.TerNo != "")
                    {
                        Transfers.ClintSendCommData(1107, "50", "", terinfo.TerNo, "", "", "", "", "", "", "", carInfo.CarDeptcode, carInfo.CarNo, carhbinfo, carInfo.CarAdminName, carInfo.CarFrame, "", "", user.UserName);
                    }
                }
            }
            ViewBag.flag = flag;
            return(View());
        }
示例#21
0
        private void sendRd2Interface()
        {
            List <RealtimeData> ltTmpRd = new List <RealtimeData>();

            while (true)
            {
                int count = this.ltRd.Count;
                if (count <= 0)
                {
                    System.Threading.Thread.Sleep(10);

                    continue;
                }

                lock (lockHttp)
                {
                    ltTmpRd.AddRange(this.ltRd);
                    this.ltRd.Clear();
                }
                foreach (var item in ltTmpRd)
                {
                    //:集合竞价

                    /* use buy5c or sell5c
                     * if (0 == item.C)
                     * {
                     *  if (item.buy5c[0] != 0)
                     *  { }
                     * }
                     */

                    if (0 == item.H)
                    {
                        item.H = item.C;
                    }
                    if (0 == item.L)
                    {
                        item.L = item.C;
                    }
                    if (0 == item.O)
                    {
                        item.O = item.C;
                    }
                    ///:~

                    lock (lockRsrc)
                    {
                        if (this.dcCodeLastRd.ContainsKey(item.code))
                        {
                            RealtimeData rd = this.dcCodeLastRd[item.code];
                            if (isOpenCallAuctionTime(rd.dt) || isCloseCallAuctionTime(rd.dt, rd.code))
                            {
                                if (rd.buy5c != item.buy5c || rd.sell5c != item.sell5c || rd.buy5v != item.buy5v || rd.sell5v != item.sell5v || rd.C != item.C)
                                {
                                    this.dcCodeLastRd[item.code] = item;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if (rd.H != item.H || rd.L != item.L || rd.O != item.O || rd.C != item.C || rd.fd != item.fd)
                                {
                                    this.dcCodeLastRd[item.code] = item;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            this.dcCodeLastRd.Add(item.code, item);
                        }

                        if (this.dcCodeRRD.ContainsKey(item.code))
                        {
                            foreach (var rrd in this.dcCodeRRD[item.code])
                            {
                                pushData(rrd, item);
                            }
                        }
                    }
                }
                ltTmpRd.Clear();
            }
        }
示例#22
0
        static void Main(string[] args)
        {
            System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

            // Adding JSON file into IConfiguration.
            IConfiguration config = new ConfigurationBuilder().AddJsonFile("config/appsettings.json", true, true).Build();

            string[] scopes = new string[] { AnalyticsService.Scope.Analytics }; // view and manage your Google Analytics data

            var keyFilePath         = "config/analytics.p12";                    // Downloaded from https://console.developers.google.com
            var serviceAccountEmail = config["ServiceAccountEmail"];             // found https://console.developers.google.com

            //loading the Key file
            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            var credential  = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = scopes
            }.FromCertificate(certificate));

            var service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Analytics API Sample",
            });


            while (true)
            {
                try
                {
                    DataResource.RealtimeResource.GetRequest realtimeReq = service.Data.Realtime.Get(String.Format("ga:{0}", config["GAID"]), "rt:activeUsers");
                    realtimeReq.Dimensions = "rt:country,rt:region,rt:city,rt:deviceCategory,rt:latitude,rt:longitude";
                    realtimeReq.Sort       = "rt:activeUsers";

                    DataResource.RealtimeResource.GetRequest realtimePageViewsReq = service.Data.Realtime.Get(String.Format("ga:{0}", config["GAID"]), "rt:pageviews");
                    realtimePageViewsReq.Dimensions = "rt:country,rt:region,rt:city,rt:deviceCategory,rt:latitude,rt:longitude";
                    realtimePageViewsReq.Sort       = "rt:pageviews";

                    RealtimeData realtime          = realtimeReq.Execute();
                    RealtimeData realtimePageViews = realtimePageViewsReq.Execute();

                    Console.WriteLine(DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss"));
                    Console.WriteLine("Total Active Users: " + realtime.TotalsForAllResults.FirstOrDefault().Value);
                    Console.WriteLine("Total Page Views: " + realtimePageViews.TotalsForAllResults.FirstOrDefault().Value);

                    Console.WriteLine("-----------------------------------------");

                    var userData = CreateData("RealtimeActiveUsers", realtime);
                    var pageData = CreateData("RealtimePageViews", realtimePageViews);

                    using (var webClient = new WebClient())
                    {
                        webClient.Headers.Add("content-type", "application/json");
                        webClient.UploadString(config["ElasticSearchUrl"], String.Join("\r\n", userData) + "\r\n");

                        webClient.Headers.Add("content-type", "application/json");
                        webClient.UploadString(config["ElasticSearchUrl"], String.Join("\r\n", pageData) + "\r\n");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error:" + e.Message);
                }

                Thread.Sleep(Convert.ToInt32(config["IntervalMs"]));
            }
        }
        /// <summary>
        /// 同时向实时表和历史表插入数据。
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public string Insert(RealtimeData entity)
        {
            ISqlMapper NewMap = SqlMapper.Instance();

            try
            {
                NewMap.BeginTransaction();
                entity.Id = System.Guid.NewGuid().ToString();
                int count = ExecuteUpdateTrans("RealtimeData.UpdateRealtimeData", entity, NewMap);
                if (count == 0)
                {
                    ExecuteInsertTrans("RealtimeData.InsertRealtimeData", entity, NewMap);
                }
                HistoricalData hid = new HistoricalData();
                hid.Id              = System.Guid.NewGuid().ToString();
                hid.Rawdataid       = entity.Rawdataid;
                hid.TerNo           = entity.TerNo;
                hid.GenerationNum   = entity.GenerationNum;
                hid.Factorynum      = entity.Factorynum;
                hid.Rtime           = entity.Rtime;
                hid.Protocolversion = entity.Protocolversion;
                hid.Programverson   = entity.Programverson;
                hid.Gpsverson       = entity.Gpsverson;
                hid.Positioningtime = entity.Positioningtime;
                hid.TerStatus       = entity.TerStatus;
                hid.TerModel        = entity.TerModel;
                hid.Worktime        = entity.Worktime;
                hid.Sleeptime       = entity.Sleeptime;
                hid.Ntervalltime    = entity.Ntervalltime;
                hid.TerVbatt        = entity.TerVbatt;
                hid.Totalworktime   = entity.Totalworktime;
                hid.Blinddatanum    = entity.Blinddatanum;
                hid.TerStatrtimes   = entity.TerStatrtimes;
                hid.Ifblinddata     = entity.Ifblinddata;
                hid.Ifposition      = entity.Ifposition;
                hid.Northorsouth    = entity.Northorsouth;
                hid.Eastorwest      = entity.Eastorwest;
                hid.Latitude        = entity.Latitude;
                hid.Longitude       = entity.Longitude;
                hid.BaiduLatitude   = entity.BaiduLatitude;
                hid.BaiduLongitude  = entity.BaiduLongitude;
                hid.GoogleLatitude  = entity.GoogleLatitude;
                hid.GoogleLongitude = entity.GoogleLongitude;
                hid.Position        = entity.Position;
                hid.Speed           = entity.Speed;
                hid.Direction       = entity.Direction;
                hid.Height          = entity.Height;
                hid.Gpsant          = entity.Gpsant;
                hid.Usesatellite    = entity.Usesatellite;
                hid.Visualsatellite = entity.Visualsatellite;
                hid.Gpsrssi         = entity.Gpsrssi;
                hid.Gsmrssi         = entity.Gsmrssi;
                hid.Lca             = entity.Lca;
                hid.Cell            = entity.Cell;
                hid.Gsmrssi1        = entity.Gsmrssi1;
                hid.Lca1            = entity.Lca1;
                hid.Cell1           = entity.Cell1;
                hid.Gsmrssi2        = entity.Gsmrssi2;
                hid.Lca2            = entity.Lca2;
                hid.Cell2           = entity.Cell2;
                hid.Gsmrssi3        = entity.Gsmrssi3;
                hid.Lca3            = entity.Lca3;
                hid.Cell3           = entity.Cell3;
                hid.Province        = entity.Province;
                hid.City            = entity.City;
                hid.County          = entity.County;
                hid.Workstate       = entity.Workstate;
                hid.Postbacktimes   = entity.Postbacktimes;
                hid.Gsmrssi4        = entity.Gsmrssi4;
                hid.Lca4            = entity.Lca4;
                hid.Cell4           = entity.Cell4;
                hid.Gsmrssi5        = entity.Gsmrssi5;
                hid.Lca5            = entity.Lca5;
                hid.Cell5           = entity.Cell5;
                hid.Gsmrssi6        = entity.Gsmrssi6;
                hid.Lca6            = entity.Lca6;
                hid.Cell6           = entity.Cell6;

                hid.Accstate      = entity.Accstate;
                hid.Lat           = entity.Lat;
                hid.Lng           = entity.Lng;
                hid.Carworkvmp    = entity.Carworkvmp;
                hid.Carworktemp   = entity.Carworktemp;
                hid.RemainlPct    = entity.RemainlPct;
                hid.AddupDist     = entity.AddupDist;
                hid.ReplydataCode = entity.ReplydataCode;
                hid.ReplydataName = entity.ReplydataName;
                ExecuteInsertTrans("HistoricalData.InsertHistoricalData", hid, NewMap);
                NewMap.CommitTransaction();
                return("true");
            }
            catch (Exception e)
            {
                NewMap.RollBackTransaction();
                return(e.Message);
            }
        }
示例#24
0
        internal void SetRealtimeData(RealtimeData data)
        {
            int index = 0;

            SetRealtimeData(data, ref index);
        }
示例#25
0
        public string GetRealtimeData(string TerNo)
        {
            RealtimeData rd = realtimeDataBll.GetRealtimeData(TerNo);

            return(ConvertToJson(rd));
        }
        //public IList<HistoricalData> GetHistoricalDataList(object o)
        //{
        //return _iHistoricalDataDao.GetHistoricalDataList(o);
        //}

        public string Insert(RealtimeData entity)
        {
            HistoricalData hid = new HistoricalData();

            hid.Id              = System.Guid.NewGuid().ToString();
            hid.Rawdataid       = entity.Rawdataid;
            hid.TerNo           = entity.TerNo;
            hid.GenerationNum   = entity.GenerationNum;
            hid.Factorynum      = entity.Factorynum;
            hid.Rtime           = entity.Rtime;
            hid.Protocolversion = entity.Protocolversion;
            hid.Programverson   = entity.Programverson;
            hid.Gpsverson       = entity.Gpsverson;
            hid.Positioningtime = entity.Positioningtime;
            hid.TerStatus       = entity.TerStatus;
            hid.TerModel        = entity.TerModel;
            hid.Worktime        = entity.Worktime;
            hid.Sleeptime       = entity.Sleeptime;
            hid.Ntervalltime    = entity.Ntervalltime;
            hid.TerVbatt        = entity.TerVbatt;
            hid.Totalworktime   = entity.Totalworktime;
            hid.Blinddatanum    = entity.Blinddatanum;
            hid.TerStatrtimes   = entity.TerStatrtimes;
            hid.Ifblinddata     = entity.Ifblinddata;
            hid.Ifposition      = entity.Ifposition;
            hid.Northorsouth    = entity.Northorsouth;
            hid.Eastorwest      = entity.Eastorwest;
            hid.Latitude        = entity.Latitude;
            hid.Longitude       = entity.Longitude;
            hid.BaiduLatitude   = entity.BaiduLatitude;
            hid.BaiduLongitude  = entity.BaiduLongitude;
            hid.GoogleLatitude  = entity.GoogleLatitude;
            hid.GoogleLongitude = entity.GoogleLongitude;
            hid.Position        = entity.Position;
            hid.Speed           = entity.Speed;
            hid.Direction       = entity.Direction;
            hid.Height          = entity.Height;
            hid.Gpsant          = entity.Gpsant;
            hid.Usesatellite    = entity.Usesatellite;
            hid.Visualsatellite = entity.Visualsatellite;
            hid.Gpsrssi         = entity.Gpsrssi;
            hid.Gsmrssi         = entity.Gsmrssi;
            hid.Lca             = entity.Lca;
            hid.Cell            = entity.Cell;
            hid.Gsmrssi1        = entity.Gsmrssi1;
            hid.Lca1            = entity.Lca1;
            hid.Cell1           = entity.Cell1;
            hid.Gsmrssi2        = entity.Gsmrssi2;
            hid.Lca2            = entity.Lca2;
            hid.Cell2           = entity.Cell2;
            hid.Gsmrssi3        = entity.Gsmrssi3;
            hid.Lca3            = entity.Lca3;
            hid.Cell3           = entity.Cell3;
            hid.Province        = entity.Province;
            hid.City            = entity.City;
            hid.County          = entity.County;
            hid.Workstate       = entity.Workstate;
            hid.Postbacktimes   = entity.Postbacktimes;
            hid.Gsmrssi4        = entity.Gsmrssi4;
            hid.Lca4            = entity.Lca4;
            hid.Cell4           = entity.Cell4;
            hid.Gsmrssi5        = entity.Gsmrssi5;
            hid.Lca5            = entity.Lca5;
            hid.Cell5           = entity.Cell5;
            hid.Gsmrssi6        = entity.Gsmrssi6;
            hid.Lca6            = entity.Lca6;
            hid.Cell6           = entity.Cell6;
            hid.Accstate        = entity.Accstate;
            hid.Lat             = entity.Lat;
            hid.Lng             = entity.Lng;
            hid.Carworkvmp      = entity.Carworkvmp;
            hid.Carworktemp     = entity.Carworktemp;
            hid.RemainlPct      = entity.RemainlPct;
            hid.AddupDist       = entity.AddupDist;
            return(_iHistoricalDataDao.Insert(hid));
        }
示例#27
0
 protected virtual void SetRealtimeData(RealtimeData data, ref int index)
 {
 }
示例#28
0
        public static async Task test()
        {
            Console.WriteLine("Start");

            var context     = new WienerLinienContext("O56IE8eH7Kf5R5aQ");
            var allStations = await Stations.GetAllStationsAsync();

            //initialize the RealtimeData object using the created context
            var rtd = new RealtimeData(context);

            var listRbls = new List <int>();

            Console.WriteLine("Please enter the desired station (e.g. Pilgramgasse):");
            var station = Console.ReadLine();

            Console.WriteLine();

            // the desired station
            var SelectedStation = allStations.Find(x => station != null && x.Name.Contains(station));

            var listLines = new List <Station.Platform>();

            // gets every line once
            for (int i = 0; i < SelectedStation.Platforms.Count; i++)
            {
                if (i % 2 == 0)
                {
                    listLines.Add(SelectedStation.Platforms.ElementAt(i));
                }
            }

            // lists all possible lines
            listLines.ForEach(x => Console.WriteLine("- " + x.Name));

            Console.WriteLine("\nPlease enter the desired plattform (e.g. 14A):");
            var plattform = Console.ReadLine();;

            var StationLines = SelectedStation.Platforms.FindAll(x => x.Name.Equals(plattform));

            foreach (var x in StationLines)
            {
                listRbls.Add(x.RblNumber);
            }

            //Create a Parameters object to include the Rbls  and get Realtime Data for them
            var parameters = new Parameters.MonitorParameters()
            {
                Rbls = listRbls
            };

            //Get the monitor informatino asynchronous, and save them as MonitorData class
            var monitorInfo = await rtd.GetMonitorDataAsync(parameters);

            foreach (var m in monitorInfo.Data.Monitors)
            {
                foreach (var lineIterate in m.Lines)
                {
                    if (lineIterate.Name.Equals(plattform))
                    {
                        Console.WriteLine();
                        Console.WriteLine(lineIterate.Name + " " + lineIterate.Towards);
                        lineIterate.Departures.Departure.ForEach(x => Console.WriteLine(" " + x.DepartureTime.TimePlanned.Normalize().Substring(11, 5)));
                    }
                }
            }



            //Get the planned arrival time for the first line and the next vehicle arriving (index at Departure)
            //var plannedTime = monitorInfo.Data.Monitors[0].Lines[0].Departures.Departure[0].DepartureTime.TimePlanned;


            Console.WriteLine("Finished");
            Console.ReadKey();
        }