Inheritance: Invert.StateMachine.State
Beispiel #1
0
        private void btnCancel_Click(object sender, EventArgs e)
        {
            stop = null;

            this.Close();
            this.Dispose();
        }
Beispiel #2
0
 public void AddStop(string tripName, Stop newStop)
 {
     var theTrip = GetTripByName(tripName);
     newStop.Order = theTrip.Stops.Any()? theTrip.Stops.Max(s => s.Order) + 1 : 1;
     theTrip.Stops.Add(newStop);
     //context.Stops.Add(newStop);
 }
Beispiel #3
0
        public myStopCtl()
        {
            InitializeComponent();

            current = null;
            lstAllStops = null;
        }
Beispiel #4
0
 private static TaskManager CreateTaskManager(ApplicationSection configuration)
 {
     const int sleeptimeLoopTime = 100;
     ISleep sleep = new Sleeper();
     IStop stop = new Stop();
     Service service = new Service(configuration.Port);
     return new TaskManager(log, sleeptimeLoopTime, sleep, stop, service);
 }
        /// <summary>
        /// Creates new instance of <c>GanttElementFrameworkElement.</c>.
        /// </summary>
        /// <param name="stop">Stop.</param>
        public GanttElementFrameworkElement(Stop stop)
        {
            Debug.Assert(stop != null);
            _stop = stop;

            _children = new VisualCollection(this);

            _CreateVisuals();
        }
Beispiel #6
0
        public void ItShouldHandleStop()
        {
            var sampleGuid = Guid.NewGuid();
            var sampleCommand = new Stop { Id = sampleGuid };
            var expectedEvent = new Stopped { Id = sampleGuid };

            sut.Publish(sampleCommand);

            publishedEvent.ShouldBeEquivalentTo(expectedEvent);
        }
 // PUT /api/notatwitterapi/5
 public HttpResponseMessage Put(int id, Stop value)
 {
     if (ModelState.IsValid)
     {
         _notatweetRepository.InsertOrUpdate(value);
         _notatweetRepository.Save();
         return new HttpResponseMessage(HttpStatusCode.NoContent);
     }
     throw new HttpResponseException(HttpStatusCode.BadRequest);
 }
Beispiel #8
0
        static bool DoIdle(Stop stop)
        {
            System.Threading.Thread.Sleep(1);	// 避免CPU资源过度耗费

            Application.DoEvents();	// 出让界面控制权
            if (stop != null && stop.State != 0)
                return true;

            System.Threading.Thread.Sleep(1);	// 避免CPU资源过度耗费
            return false;
        }
Beispiel #9
0
        public void Can_Set_Stop_Geography()
        {
            // Arrange
            var stop = new Stop();
            stop.StopGeography = SqlGeography.STGeomFromText(
                new SqlChars("POLYGON((10 10, 20 10, 30 20, 10 10))"), 4326);

            // Assert
            Assert.AreNotEqual(null, stop.StopGeography);
            Assert.AreNotEqual(null, stop.StopBin);
        }
Beispiel #10
0
        public void ItShouldHandleStop()
        {
            var sampleGuid = Guid.NewGuid();
            var sampleCommand = new Stop { Id = sampleGuid };
            var expectedEvent = new Stopped { Id = sampleGuid };

            sut.Publish(sampleCommand);

            var publishedEvent = publishedEvents.Single(@event => @event.GetType() == typeof(Stopped));
            publishedEvent.ShouldBeEquivalentTo(expectedEvent);
        }
Beispiel #11
0
        public void addEta(Route r, Stop s, int eta)
        {
            List<int> l;

            if (!m_etas.TryGetValue(new Key(r.Id, s.Id), out l))
            {
                l = new List<int>();
                m_etas.Add(new Key(r.Id, s.Id), l);
            }

            l.Add(eta);
        }
Beispiel #12
0
        public void Can_Get_Stop_Geography()
        {
            // Arrange
            var stop = new Stop();
            stop.StopGeography = SqlGeography.STGeomFromText(
                new SqlChars("POLYGON((10 10, 20 10, 30 20, 10 10))"), 4326);

            var anotherStop = new Stop();
            anotherStop.StopBin = SqlGeography.STPolyFromText(stop.StopGeography.STAsText(), 4326).STAsBinary().Buffer;

            // Assert
            Assert.AreNotEqual(null, stop.StopGeography);
            Assert.AreNotEqual(null, anotherStop.StopGeography);
        }
Beispiel #13
0
    public static int Main(String[] args) {              

        Stop tm = new Stop();
	try
	{

		ThreadPool.QueueUserWorkItem(new WaitCallback(tm.RunTest));
		Thread.Sleep(3000);
	}
	catch
	{
		return -1;
	}
	return 100;
    }
Beispiel #14
0
 public static TaskManager CreateTaskManager(SqlToGraphiteSection configuration)
 {
     var cacheLength = new TimeSpan(0, configuration.ConfigCacheLengthMinutes, 0);
     var stop = new Stop();
     IDataClientFactory dataClientFactory = new DataClientFactory(log);
     IGraphiteClientFactory graphiteClientFactory = new GraphiteClientFactory(log);
     var configMapper = new ConfigMapper(configuration.Hostname, stop, dataClientFactory, graphiteClientFactory, log);
     var configReader = new ConfigReader(configuration.ConfigUri,configuration.ConfigUsername,configuration.ConfigPassword);
     var cache = new Cache(cacheLength, log);
     var sleeper = new Sleeper();
     var knownGraphiteClients = new KnownGraphiteClients();
     var cr = new ConfigRepository(configReader, knownGraphiteClients, cache, sleeper, log, configuration.MinutesBetweenRetryToGetConfigOnError);
     var configController = new ConfigController(configMapper, log, cr);
     return new TaskManager(log, configController, configuration.ConfigUri, stop, sleeper, configuration.CheckConfigUpdatedEveryMinutes);
 }
        /// <summary>
        /// Initializes a new instance of the <c>StopGanttItem</c> class.
        /// </summary>
        public StopGanttItemElement(Stop stop, IGanttItem parent)
        {
            Debug.Assert(stop != null);
            Debug.Assert(parent != null);

            // Initialize stop.
            _stop = stop;
            _route = stop.Route;

            // Subscribe on stop and route changes to notify about updates.
            _route.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_RoutePropertyChanged);
            _stop.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_StopPropertyChanged);

            // Initialize parent.
            _parent = parent;
        }
Beispiel #16
0
        private bool Add(/*CustomerDTO stop*/)
        {
            // initialize only once
            if (LstAllStops == null)
            {
                throw new Exception("Please provide all possible stops for the user to choose from.");
            }

            FrmStop frmStop = new FrmStop(LstAllStops);
            frmStop.ShowDialog();
            tmpStop = frmStop.GetSelectedStop();

            // only add when the user selected a valid stop
            if (tmpStop != null) { selectedStops.Add(tmpStop); SelectedStops = selectedStops; }
            frmStop.Close();
            frmStop.Dispose();

            return false;
        }
 public void Should_try_controller()
 {
     var log = LogManager.GetLogger("log");
     log4net.Config.XmlConfigurator.Configure();
     //var host = "metrics.london.ttldev.local";
     //var port = 2003;
     //var connectionString = "Data Source=nuget.london.ttldev.local;Initial Catalog=GoReportingSvn3;User Id=sa;Password=!bcde1234;";
     //var sqlGetter = new SqlGetter(connectionString, host, port, log);
     //var sql = "SELECT [Assigned],DateDiff(s,[Scheduled],[Assigned]) FROM [GoReportingSvn3].[dbo].[V_BuildStateTransition] where Scheduled > '2012-01-01'";
     //sqlGetter.Process("owain.test.Tlsvn3.Assigned", sql);
     var ds = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.244.127.11)(PORT=1532)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=tracslg2)));User Id=temp_ttl_user;Password=tt1r34dj0b;";
     var taskParam = new TaskParams("ThePath", "SELECT concat(dm_code,concat('_',current_ds_code)) AS dm, COUNT(DISTINCT (d.ID)) AS dm_count FROM DELIVERIES D WHERE d.tr_ID >= (SELECT TR_ID FROM TRANSACTION_FIRSTOFDAY WHERE date_of_tr = TRUNC(SYSDATE)) GROUP BY dm_code, current_ds_code", ds, "Oracle", "name", "graphiteudp");
     var tasks = new List<ITask> { new Task(taskParam, new DataClientFactory(log), new GraphiteClientFactory(log), new GraphiteParams("hostname", 1234), log) };
     var set = new TaskSet(tasks, new Stop(), 1000);
     var sleep = new Sleeper();
     var stop = new Stop();
     var controller = new Controller(set, sleep, stop, log);
     controller.Process();
 }
Beispiel #18
0
    // POST /api/notatwitterapi
    public HttpResponseMessage Post(Stop value)
    {
        if (ModelState.IsValid)
        {
            _notatweetRepository.InsertOrUpdate(value);
            _notatweetRepository.Save();

            //Created!
            var response = new HttpResponseMessage(HttpStatusCode.Created);

            //Let them know where the new NotATweet is
            string uri = Url.Route(null, new { id = value.Id });
            response.Headers.Location = new Uri(Request.RequestUri, uri);

            return response;

        }
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }
        public static TaskManager CreateTaskManager(SqlToGraphiteSection configuration)
        {
            var cacheLength = new TimeSpan(0, configuration.ConfigCacheLengthMinutes, 0);
            var stop = new Stop();
            var directoryImpl = new DirectoryImpl();
            var assemblyResolver = new AssemblyResolver(directoryImpl, log);
            IEncryption encryption = new Encryption();
            IDataClientFactory dataClientFactory = new DataClientFactory(log, assemblyResolver, encryption);
            IGraphiteClientFactory graphiteClientFactory = new GraphiteClientFactory(log);

            var configReader = new ConfigHttpReader(configuration.ConfigUri, configuration.ConfigUsername, configuration.ConfigPassword);
            var cache = new Cache(cacheLength, log);
            var sleeper = new Sleeper();
            var genericSer = new GenericSerializer(Global.GetNameSpace());
            var cr = new ConfigRepository(configReader, cache, sleeper, log, configuration.MinutesBetweenRetryToGetConfigOnError, genericSer);
            var configMapper = new ConfigMapper(configuration.Hostname, stop, dataClientFactory, graphiteClientFactory, log, cr);
            var roleConfigFactory = new RoleConfigFactory();
            var environment = new Environment();
            var taskSetBuilder = new TaskSetBuilder();
            var configController = new ConfigController(configMapper, log, cr, roleConfigFactory, environment, taskSetBuilder);
            return new TaskManager(log, configController, configuration.ConfigUri, stop, sleeper, configuration.CheckConfigUpdatedEveryMinutes);
        }
Beispiel #20
0
 public virtual Visual FindLastTarget(Visual scope, Stop currentStop, DependencyProperty navigationModeProperty, IStopComparerProvider stopComparerProvider)
 {
     return(scope.VisualParent != null?
            KeyboardNavigationTarget.FindLastTarget(scope.VisualParent, currentStop, navigationModeProperty, stopComparerProvider) :
                KeyboardNavigationTarget.FindLastContainedTarget(scope, currentStop, navigationModeProperty, stopComparerProvider));
 }
Beispiel #21
0
 public static void CallStopStatusChanged(this Strategy s, Stop stop)
 {
     //StrategyOnStopStatusChangedMethod?.Invoke(s, new[] { stop });
     OnStopStatusChangedAction(s, stop);
 }
Beispiel #22
0
 public override Visual FindLastTarget(Visual scope, Stop currentStop, DependencyProperty navigationModeProperty, IStopComparerProvider stopComparerProvider)
 {
     return(KeyboardNavigationTarget.FindLastContainedTarget(scope, currentStop, navigationModeProperty, stopComparerProvider));
 }
Beispiel #23
0
 protected override void OnStopExecuted(Stop stop)
 {
     // 止损出场
     //StrategyHelper.ClosePosition(Position, "止损");
 }
Beispiel #24
0
        //[ValidateAntiForgeryToken]
        //[AllowAnonymous]
        public async Task <ActionResult> Create([Bind(Include = "ID,JsonStop,JsonInstrumentation,latitude,longitude,beat,UserProfileID,PersonCount")] Stop stop)
        {
            if (ConfigurationManager.AppSettings["requireGroupMembership"] == "true")
            {
                HomeController.UserAuth user = new HomeController.UserAuth();
                user = HomeController.AuthorizeUser(User.Identity.Name.ToString());

                if (!user.authorized && !user.authorizedAdmin)
                {
                    //return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                    return(RedirectToAction("Unauthorized", "Home"));
                }
                uid = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == User.Identity.Name.ToString());
            }
            else
            {
                uid = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == "AnonymousUser");
            }

            //stop.ID = Guid.NewGuid();
            stop.Time          = DateTime.Now;
            stop.Latitude      = string.IsNullOrEmpty(stop.Latitude) ? null : stop.Latitude;
            stop.Longitude     = string.IsNullOrEmpty(stop.Longitude) ? null : stop.Longitude;
            stop.Beat          = string.IsNullOrEmpty(stop.Beat) ? null : stop.Beat;
            stop.UserProfileID = uid.UserProfileID;

            stop.JsonStop = Regex.Replace(stop.JsonStop, @"\p{Cs}", ""); // remove emojies

            //Todo: extract info from JsonStop
            CommonRoutines cr = new CommonRoutines();

            string[] OfficerIDDateTime = cr.getOfficerIDDateTime(stop.JsonStop);

            // Dedupe. Check for existing before proceeding. Using only OfficerID & Date/Time per DOJ service validation. Comparing the
            // whole json payload would potentially introduce duplicate OfficerID & Date/Time combinations.
            string officerID = OfficerIDDateTime[0];
            string stopDate  = OfficerIDDateTime[1];
            string StopTime  = OfficerIDDateTime[2];
            bool   exist     = db_lookup.StopOfficerIDDateTime_JSON_vw
                               .Any(x => x.officerID == officerID && x.stopDate == stopDate && x.StopTime == StopTime);

            if (!exist)
            {
                db.Stop.Add(stop);

                try
                {
                    db.SaveChanges();
                    //return RedirectToAction("Index");
                    string dojJson = cr.dojTransform(stop, "I");
                    stop.JsonDojStop     = dojJson;
                    db.Entry(stop).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
                catch (Exception ex)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
                }
            }
            else
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Conflict));
            }
        }
Beispiel #25
0
 private static void AddStop2(Strategy s, Stop stop)
 {
     s.AddStop(stop);
     StrategyServer.SaveStop(stop);
 }
 public void Dispose()
 {
     Timer.Dispose();
     Stop?.Invoke();
 }
Beispiel #27
0
        private void ConfigureThenRoute()
        {
            // Guard against error conditions.
            if (_routeParameters == null)
            {
                ShowMessage("Not ready yet", "Sample isn't ready yet; define route parameters first.");
                return;
            }

            if (_stopsOverlay.Graphics.Count < 2)
            {
                ShowMessage("Not enough stops", "Add at least two stops before solving a route.");
                return;
            }

            // Clear any existing route from the map.
            _routeOverlay.Graphics.Clear();

            // Configure the route result to include directions and stops.
            _routeParameters.ReturnStops      = true;
            _routeParameters.ReturnDirections = true;

            // Create a list to hold stops that should be on the route.
            List <Stop> routeStops = new List <Stop>();

            // Create stops from the graphics.
            foreach (Graphic stopGraphic in _stopsOverlay.Graphics)
            {
                // Note: this assumes that only points were added to the stops overlay.
                MapPoint stopPoint = (MapPoint)stopGraphic.Geometry;

                // Create the stop from the graphic's geometry.
                Stop routeStop = new Stop(stopPoint);

                // Set the name of the stop to its position in the list.
                routeStop.Name = $"{_stopsOverlay.Graphics.IndexOf(stopGraphic) + 1}";

                // Add the stop to the list of stops.
                routeStops.Add(routeStop);
            }

            // Configure the route parameters with the stops.
            _routeParameters.ClearStops();
            _routeParameters.SetStops(routeStops);

            // Create a list to hold barriers that should be routed around.
            List <PolygonBarrier> routeBarriers = new List <PolygonBarrier>();

            // Create barriers from the graphics.
            foreach (Graphic barrierGraphic in _barriersOverlay.Graphics)
            {
                // Get the polygon from the graphic.
                Polygon barrierPolygon = (Polygon)barrierGraphic.Geometry;

                // Create a barrier from the polygon.
                PolygonBarrier routeBarrier = new PolygonBarrier(barrierPolygon);

                // Add the barrier to the list of barriers.
                routeBarriers.Add(routeBarrier);
            }

            // Configure the route parameters with the barriers.
            _routeParameters.ClearPolygonBarriers();
            _routeParameters.SetPolygonBarriers(routeBarriers);

            // If the user allows stops to be re-ordered, the service will find the optimal order.
            _routeParameters.FindBestSequence = AllowReorderStopsCheckbox.IsChecked == true;

            // If the user has allowed re-ordering, but has a definite start point, tell the service to preserve the first stop.
            _routeParameters.PreserveFirstStop = PreserveFirstStopCheckbox.IsChecked == true;

            // If the user has allowed re-ordering, but has a definite end point, tell the service to preserve the last stop.
            _routeParameters.PreserveLastStop = PreserveLastStopCheckbox.IsChecked == true;

            // Calculate and show the route.
            CalculateAndShowRoute();
        }
 public void SetStop(Stop stop)
 {
     Stop = stop;
 }
 public KalmanVehicleStopDetail(Stop stop, long time, KalmanVehicle vehicle)
 {
     Stop    = stop;
     Time    = time;
     Vehicle = vehicle;
 }
Beispiel #30
0
 public static double StraightLineDistanceTo(this Stop stop, GeoCoordinate coordinate)
 {
     return(stop.StraightLineDistanceTo(coordinate.Latitude, coordinate.Longitude));
 }
 /// <summary>
 /// Creates new instance of <c>GanttElementAdorner</c> class.
 /// </summary>
 public LabelSequenceAdornment(Stop stop)
     : base(stop)
 {
 }
 private bool EqualsStop(Stop x, Stop y)
 {
     return(true);
 }
Beispiel #33
0
	public override void OnStopExecuted(Stop stop)
	{
		Sell(Qty, "Stop Exit");
	}
        private void Publish(Stop command)
        {
            var @event = mappingEngine.DynamicMap <Stopped>(command);

            bus.Publish(@event);
        }
Beispiel #35
0
        public override string ToString()
        {
            var optional_step = Step == 1 ? "" : $":{Step}";

            return($"{(Start == 0 ? "" : Start.ToString())}:{(Stop == null ? "" : Stop.ToString())}{optional_step}");
        }
        async void Button_Clicked(System.Object sender, System.EventArgs e)
        {
            // Assign the map to the MapView.
            MainMapView.Map = new Map(BasemapStyle.ArcGISNavigation);
            await MainMapView.Map.LoadAsync();

            //MapPoint mapCenterPoint = new MapPoint(, SpatialReferences.WebMercator);
            await MainMapView.SetViewpointAsync(new Viewpoint(52.0135053, 4.3367553, 72223.819286));

            // Create the route task, using the online routing service.
            RouteTask routeTask = await RouteTask.CreateAsync(_routingUri);

            // Get the default route parameters.
            RouteParameters routeParams = await routeTask.CreateDefaultParametersAsync();

            // Explicitly set values for parameters.
            routeParams.ReturnDirections       = true;
            routeParams.ReturnStops            = true;
            routeParams.ReturnRoutes           = true;
            routeParams.OutputSpatialReference = SpatialReferences.Wgs84;

            // Create stops for each location.
            Stop stop1 = new Stop(_conventionCenter)
            {
                Name = "Delft Netherlands"
            };
            Stop stop2 = new Stop(_memorial)
            {
                Name = "Rotterdam Netherlands"
            };
            //Stop stop3 = new Stop(_aerospaceMuseum) { Name = "Amsterdam Netherlands" };

            // Assign the stops to the route parameters.
            List <Stop> stopPoints = new List <Stop> {
                stop1, stop2
            };

            routeParams.SetStops(stopPoints);

            // Get the route results.
            _routeResult = await routeTask.SolveRouteAsync(routeParams);

            _route = _routeResult.Routes[0];

            // Add a graphics overlay for the route graphics.
            MainMapView.GraphicsOverlays.Add(new GraphicsOverlay());

            // Add graphics for the stops.
            SimpleMarkerSymbol stopSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.OrangeRed, 20);

            MainMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_conventionCenter, stopSymbol));
            MainMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_memorial, stopSymbol));
            //MainMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_aerospaceMuseum, stopSymbol));

            // Create a graphic (with a dashed line symbol) to represent the route.
            _routeAheadGraphic = new Graphic(_route.RouteGeometry)
            {
                Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.BlueViolet, 5)
            };

            // Create a graphic (solid) to represent the route that's been traveled (initially empty).
            _routeTraveledGraphic = new Graphic {
                Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.LightBlue, 3)
            };

            // Add the route graphics to the map view.
            MainMapView.GraphicsOverlays[0].Graphics.Add(_routeAheadGraphic);
            MainMapView.GraphicsOverlays[0].Graphics.Add(_routeTraveledGraphic);

            // Set the map viewpoint to show the entire route.
            await MainMapView.SetViewpointGeometryAsync(_route.RouteGeometry, 100);

            // Enable the navigation button.
            StartNavigationButton.IsEnabled = true;
        }
Beispiel #37
0
        private string dojTransform(Stop stop)
        {
            ExtractJNode eJson, deJson;

            string jsonStop = stop.JsonStop;

            try
            {

                JObject o = JObject.Parse(jsonStop);
                eJson = new ExtractJNode("ori", o);
                string ori = eJson.traverseNode();
                eJson = new ExtractJNode("date", o);
                string date = eJson.traverseNode();

                //date = DateTime.Parse(date).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

                DateTime dateValue;
                if (DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
                {
                    date = dateValue.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
                }
                else if (DateTime.TryParseExact(date, "yy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
                {
                    date = dateValue.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
                }
                else
                {
                    //throw Exception;
                }

                eJson = new ExtractJNode("time", o);
                string time = eJson.traverseNode();
                eJson = new ExtractJNode("stopDuration", o);
                string stopDuration = eJson.traverseNode();
                eJson = new ExtractJNode("officerID", o);
                string officerID = eJson.traverseNode();
                eJson = new ExtractJNode("ExpYears", o);
                string ExpYears = eJson.traverseNode();
                eJson = new ExtractJNode("officerAssignment.key", o);
                string OFKey = eJson.traverseNode();
                eJson = new ExtractJNode("officerAssignment.otherType", o);
                string OFOtherType = eJson.traverseNode();

                eJson = new ExtractJNode("location.intersection", o);
                string intersection = eJson.traverseNode();
                eJson = new ExtractJNode("location.blockNumber", o);
                string blockNumber = eJson.traverseNode();
                eJson = new ExtractJNode("location.landMark", o);
                string landMark = eJson.traverseNode();
                eJson = new ExtractJNode("location.streetName", o);
                string streetName = eJson.traverseNode();
                eJson = new ExtractJNode("location.highwayExit", o);
                string highwayExit = eJson.traverseNode();

                // Generate Location
                string location = intersection;
                if (blockNumber != "")
                    location += " " + blockNumber;
                if (landMark != "")
                    location += " " + landMark;
                if (streetName != "")
                    location += " " + streetName;
                if (highwayExit != "")
                    location += " " + highwayExit;
                eJson = new ExtractJNode("location.city.codes.code", o);
                string city = eJson.traverseNode();

                eJson = new ExtractJNode("location.school", o);
                string isSchool = "";

                if (eJson.traverseNode() == "True")
                {
                    isSchool = "Y";
                }
                eJson = new ExtractJNode("location.schoolName.codes.code", o);
                string schoolNameCode = eJson.traverseNode();

                eJson = new ExtractJNode("stopInResponseToCFS", o);
                string stopInResponseToCFS = "N";

                if (eJson.traverseNode() == "True")
                {
                    stopInResponseToCFS = "Y";
                }

                JObject jsonObject = JObject.FromObject(new
                {
                    //stopdatarecord = new
                    //{
                    LEARecordID = stop.ID.ToString(),
                    BatchID = "",
                    ORI = ori,
                    TX_Type = "I",
                    Is_NFIA = "",
                    SDate = date,
                    STime = time,
                    SDur = stopDuration,
                    Officer = new
                    {
                        UID = officerID,
                        Proxy = "",
                        ExpYears,
                        AT = OFKey,
                        ATOth = OFOtherType,
                    },
                    Location = new
                    {
                        Loc = location,
                        City = city,
                        K12_Flag = isSchool,
                        K12Code = schoolNameCode,
                    },
                    Is_ServCall = stopInResponseToCFS,
                    ListPerson_Stopped = new
                    {
                        Person_Stopped = new JArray(),
                    }
                });
                string jString = JsonConvert.SerializeObject(jsonObject);

                JArray personList = (JArray)o["ListPerson_Stopped"];

                JObject stopdatarecord = (JObject)jsonObject["ListPerson_Stopped"];

                int pid = 0;
                int i = 0;
                foreach (JObject item in personList)
                {
                    //eJson = new ExtractJNode("PID", item);
                    //string PID = eJson.traverseNode();

                    //PID value should not exceed 99
                    if (pid < 100)
                    {
                        pid++;

                        eJson = new ExtractJNode("perceivedRace.key", item);
                        string pRace = eJson.traverseNode();
                        string[] ethnList = pRace.Split(',');

                        eJson = new ExtractJNode("perceivedAge", item);
                        string perceivedAge = eJson.traverseNode();

                        eJson = new ExtractJNode("perceivedLimitedEnglish", item);
                        string perceivedLimitedEnglish = "N";
                        if (eJson.traverseNode() == "True")
                        {
                            perceivedLimitedEnglish = "Y";
                        }

                        eJson = new ExtractJNode("perceivedOrKnownDisability.key", item);
                        string prcvDisability = eJson.traverseNode();
                        string[] prcvDisabltyList = prcvDisability.Split(',');

                        eJson = new ExtractJNode("Gend", item);
                        string Gend = eJson.traverseNode();

                        eJson = new ExtractJNode("gendNC", item);
                        string GendNC = eJson.traverseNode();

                        eJson = new ExtractJNode("perceivedLgbt", item);
                        string perceivedLgbt = "N";
                        if (eJson.traverseNode() == "Yes")
                        {
                            perceivedLgbt = "Y";
                        }

                        eJson = new ExtractJNode("Is_Stud", item);
                        string Is_Stud = "";
                        if (isSchool == "Y")
                        {
                            if (eJson.traverseNode() == "True")
                                Is_Stud = "Y";
                            else
                                Is_Stud = "N";

                        }

                        eJson = new ExtractJNode("reasonForStop.key", item);
                        string StReas = eJson.traverseNode();

                        eJson = new ExtractJNode("reasonForStopExplanation", item);
                        string StReas_N = eJson.traverseNode();


                        eJson = new ExtractJNode("basisForSearch.key", item);
                        string BasSearch = eJson.traverseNode();
                        string[] BasSearchList = BasSearch.Split(',');

                        eJson = new ExtractJNode("basisForSearchBrief", item);
                        string BasSearch_N = eJson.traverseNode();

                        eJson = new ExtractJNode("basisForPropertySeizure.key", item);
                        string BasSeiz = eJson.traverseNode();
                        string[] BasSeizList = BasSeiz.Split(',');

                        eJson = new ExtractJNode("typeOfPropertySeized.key", item);
                        string PropType = eJson.traverseNode();
                        string[] PropTypeList = PropType.Split(',');

                        eJson = new ExtractJNode("contrabandOrEvidenceDiscovered.key", item);
                        string Cb = eJson.traverseNode();
                        string[] CbList = Cb.Split(',');
                        string pidStr = pid.ToString();


                        JArray listP = (JArray)stopdatarecord["Person_Stopped"];
                        listP.Add(new JObject(new JProperty("PID", pidStr),
                                              new JProperty("Perc",
                                                new JObject(new JProperty("ListEthn",
                                                                new JObject(new JProperty("Ethn", new JArray(ethnList)))),
                                                            new JProperty("Age", perceivedAge),
                                                            new JProperty("Is_LimEng", perceivedLimitedEnglish),
                                                            new JProperty("ListDisb",
                                                                    new JObject(new JProperty("Disb", new JArray(prcvDisabltyList)))),
                                                            new JProperty("Gend", Gend),
                                                            new JProperty("GendNC", GendNC),
                                                            new JProperty("LGBT", perceivedLgbt))),
                                              new JProperty("Is_Stud", Is_Stud),
                                              new JProperty("PrimaryReason",
                                                new JObject(new JProperty("StReas", StReas),
                                                            new JProperty("StReas_N", StReas_N))),
                                              new JProperty("ListActTak",
                                                new JObject(new JProperty("ActTak", new JArray()))),
                                              new JProperty("ListBasSearch",
                                                new JObject(new JProperty("BasSearch", BasSearchList))),
                                              new JProperty("BasSearch_N", BasSearch_N),
                                              new JProperty("ListBasSeiz",
                                                new JObject(new JProperty("BasSeiz", BasSeizList))),
                                              new JProperty("ListPropType",
                                                new JObject(new JProperty("PropType", PropTypeList))),
                                              new JProperty("ListCB",
                                                new JObject(new JProperty("Cb", CbList))),
                                              new JProperty("ListResult",
                                                new JObject(new JProperty("Result", new JArray())))));



                        i = pid - 1;

                        //Action Taken
                        eJson = new ExtractJNode("actionsTakenDuringStop.key", item);
                        string ActTak = eJson.traverseNode();
                        string[] ActTakList = ActTak.Split(';');

                        JObject ListActTakO = (JObject)listP[i]["ListActTak"];
                        JArray listAct = (JArray)ListActTakO["ActTak"];
                        for (int j = 0; j < ActTakList.Length; j++)
                        {
                            string[] CD_Con = ActTakList[j].Split(',');
                            if (CD_Con.Length == 2)
                                listAct.Add(new JObject(new JProperty("Act_CD", CD_Con[0]),
                                                    new JProperty("Is_Con", CD_Con[1])));
                            else
                                listAct.Add(new JObject(new JProperty("Act_CD", CD_Con[0]),
                                                    new JProperty("Is_Con", "na")));
                        }

                        deJson = new ExtractJNode("reasonForStop.details.key", item);
                        JObject PrimaryReason = (JObject)listP[i]["PrimaryReason"];
                        string key = "";
                        string reasonCode = "";

                        // Traffic Violation
                        if (StReas == "1")
                        {
                            key = deJson.traverseNode();
                            PrimaryReason.Add(new JProperty("Tr_ID", key));
                        }

                        eJson = new ExtractJNode("reasonForStop.codes.code", item);
                        if (StReas == "1")
                        {
                            reasonCode = eJson.traverseNode();
                            PrimaryReason.Add(new JProperty("Tr_O_CD", reasonCode));
                        }

                        // Reasonable Suspicion
                        if (StReas == "2")
                        {
                            key = deJson.traverseNode();
                            string[] keys = key.Split(',');
                            PrimaryReason.Add(new JProperty("ListSusp_T",
                                                new JObject(new JProperty("Susp_T", keys))));
                        }

                        eJson = new ExtractJNode("reasonForStop.codes.code", item);
                        if (StReas == "2")
                        {
                            reasonCode = eJson.traverseNode();
                            string[] codes = reasonCode.Split(',');
                            PrimaryReason.Add(new JProperty("Susp_O_CD", codes));
                        }

                        // Education Code
                        if (StReas == "7")
                        {
                            key = deJson.traverseNode();
                            PrimaryReason.Add(new JProperty("EDU_sec_CD", key));
                        }

                        eJson = new ExtractJNode("reasonForStop.codes.code", item);
                        if (StReas == "7")
                        {
                            reasonCode = eJson.traverseNode();
                            PrimaryReason.Add(new JProperty("EDU_subDiv_CD", reasonCode));

                        }
                        JArray resultOfStopList = (JArray)item["resultOfStop"];

                        foreach (JObject resultItem in resultOfStopList)
                        {
                            JObject resultRecord = (JObject)listP[i]["ListResult"];
                            JArray listR = (JArray)resultRecord["Result"];

                            eJson = new ExtractJNode("key", resultItem);
                            string Result = eJson.traverseNode();
                            string[] ResultList = Result.Split(',');
                            foreach (string unit in ResultList)
                            {
                                eJson = new ExtractJNode("codes.code", resultItem);
                                string Res_O_CD = eJson.traverseNode();
                                string[] Res_O_CDList = Res_O_CD.Split(',');
                                listR.Add(new JObject(new JProperty("ResCD", unit),
                                                        new JProperty("Res_O_CD", Res_O_CDList)));
                            }

                        }



                        jString = JsonConvert.SerializeObject(jsonObject);
                    }
                }


                string sJSON = JsonConvert.SerializeObject(jsonObject);
                return sJSON;
            }
            catch (Exception error)
            {
                string err = error.Message;
                throw error;
            }
        }
Beispiel #38
0
 /// <inheritdoc />
 protected override void OnStop(Stop stop)
 {
     // No actions to perform
 }
Beispiel #39
0
 public override Visual FindPreviousTarget(Visual scope, Stop currentStop, DependencyProperty navigationModeProperty, IStopComparerProvider stopComparerProvider)
 {
     return(KeyboardNavigationTarget.FindPreviousContainedTarget(scope, currentStop, navigationModeProperty, stopComparerProvider) ??
            (scope.VisualParent != null ? KeyboardNavigationTarget.FindPreviousTarget(scope.VisualParent, new Stop(currentStop.Element, KeyboardNavigation.GetTabIndex(scope)), navigationModeProperty, stopComparerProvider) : null)); // translate currentStop and forward request to parent
 }
        /// <summary>
        /// Initializes a new instance of the <c>DriveTimeGanttItemElement</c> class.
        /// </summary>
        public DriveTimeGanttItemElement(Stop stop, IGanttItem parent)
        {
            // Creates route drive time as a gantt item element.
            _stop = stop;
            _route = stop.Route; // Cache route value.
            _parent = parent;

            // Subscribe on stop changes to notify about updates.
            _route.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_RoutePropertyChanged);
            _stop.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(_StopPropertyChanged);
        }
Beispiel #41
0
 public override Visual FindPreviousTarget(Visual scope, Stop currentStop, DependencyProperty navigationModeProperty, IStopComparerProvider stopComparerProvider)
 {
     return(KeyboardNavigationTarget.FindPreviousContainedTarget(scope, currentStop, navigationModeProperty, stopComparerProvider) ?? currentStop.Element); // stay at the edge
 }
 public void ScheduleForStop(GeoCoordinate location, Stop stop)
 {
     webservice.ScheduleForStop(
         location,
         stop,
         delegate(List<RouteSchedule> schedule, Exception error)
         {
             if (ScheduleForStop_Completed != null)
             {
                 ScheduleForStop_Completed(this, new ViewModel.EventArgs.ScheduleForStopEventArgs(stop, schedule, error));
             }
         }
     );
 }
Beispiel #43
0
 public override Visual FindPreviousTarget(Visual scope, Stop currentStop, DependencyProperty navigationModeProperty, IStopComparerProvider stopComparerProvider)
 {
     // forward the request to the parent
     return(scope.VisualParent != null?KeyboardNavigationTarget.FindPreviousTarget(scope.VisualParent, currentStop, navigationModeProperty, stopComparerProvider) : null);
 }
        /// <summary>
        /// Exports the specified stop into a serializable stop info object.
        /// </summary>
        /// <param name="stop">The reference to the stop object to be exported.</param>
        /// <param name="sortedRouteStops">A collection of route stops sorted by their sequence
        /// numbers.</param>
        /// <param name="exportOrderProperties">The reference to the collection
        /// of custom order properties to be exported.</param>
        /// <param name="addressProperties">The reference to the collection
        /// of order address properties to be exported.</param>
        /// <param name="capacityProperties">The reference to the collection
        /// of order capacity properties to be exported.</param>
        /// <param name="customProperties">The reference to the collection
        /// of custom order properties to be exported.</param>
        /// <param name="settings">Current solver settings to be used for retrieving stop
        /// properties.</param>
        /// <returns>A stop info object corresponding to the specified stop.</returns>
        private static StopInfo _ExportStop(
            Stop stop,
            IList<Stop> sortedRouteStops,
            IEnumerable<OrderPropertyInfo> exportOrderProperties,
            IEnumerable<OrderPropertyInfo> addressProperties,
            IEnumerable<OrderPropertyInfo> capacityProperties,
            IEnumerable<OrderPropertyInfo> customProperties,
            SolverSettings settings)
        {
            Debug.Assert(stop != null);
            Debug.Assert(sortedRouteStops != null);
            Debug.Assert(sortedRouteStops.All(s => s != null));
            Debug.Assert(sortedRouteStops.All(s => stop.Route == s.Route));

            var commentsProperties = _GetOrderProperties(stop, exportOrderProperties);

            var result = new StopInfo
            {
                Name = _GetStopName(stop, sortedRouteStops),
                Location = _GetStopLocation(stop, sortedRouteStops),
                Address = _GetOrderProperties(stop, addressProperties),
                Capacities = _GetOrderProperties(stop, capacityProperties),
                CustomOrderProperties = _GetOrderProperties(stop, customProperties),
                OrderComments = _GetOrderComments(commentsProperties),
                ArriveTime = stop.ArriveTime,
            };

            // Fill optional order-specific or depot-specific properties.
            var order = stop.AssociatedObject as Order;
            var depot = stop.AssociatedObject as Location;

            if (order != null)
            {
                _FillOrderProperties(order, settings, result);
            }
            else if (depot != null)
            {
                _FillDepotProperties(depot, settings, result);
            }

            return result;
        }
        /// <summary>
        /// Gets location of the specified stop.
        /// </summary>
        /// <param name="stop">The reference to stop to get location for.</param>
        /// <param name="sortedRouteStops">The collection of route stops sorted by their
        /// sequence numbers for the route containing the <paramref name="stop"/>.</param>
        /// <returns></returns>
        private static Point _GetStopLocation(Stop stop, IList<Stop> sortedRouteStops)
        {
            Debug.Assert(stop != null);
            Debug.Assert(sortedRouteStops != null);
            Debug.Assert(sortedRouteStops.All(item => item != null));
            Debug.Assert(sortedRouteStops.All(item => item.Route == stop.Route));

            var mapLocation = stop.MapLocation;
            if (mapLocation.HasValue)
            {
                return mapLocation.Value;
            }

            if (stop.StopType != StopType.Lunch)
            {
                throw new InvalidOperationException(
                    Properties.Messages.Error_GrfExporterNoLocationForStop); // exception
            }

            // find stop index in collection
            var firstStopIndex = sortedRouteStops.First().SequenceNumber;
            var currentIndex = stop.SequenceNumber - firstStopIndex;
            var stopWithLocation = SolveHelper.GetActualLunchStop(sortedRouteStops, currentIndex);
            if (!stopWithLocation.MapLocation.HasValue)
            {
                throw new InvalidOperationException(
                    Properties.Messages.Error_GrfExporterNoLocationForStop); // exception
            }

            return stopWithLocation.MapLocation.Value;
        }
        /// <summary>
        /// Creates dot symbol.
        /// </summary>
        /// <param name="orderOrStop">Order or stop.</param>
        /// <returns>Dot symbol.</returns>
        public static Control CreateDotSymbol(Stop stop)
        {
            // Fill necessary attributes.
            Color color = Color.FromRgb(stop.Route.Color.R, stop.Route.Color.G, stop.Route.Color.B);
            bool isLocked = stop.IsLocked;
            bool isViolated = stop.IsViolated;
            int? sequenceNumber = stop.OrderSequenceNumber;

            return _CreateMapSymbol(CUSTOM_ORDER_SYMBOL_CONTROL_TEMPLATE, color, isLocked,
                isViolated, sequenceNumber);
        }
Beispiel #47
0
 private static Visual FindLastTarget(Visual scope, Stop currentStop, DependencyProperty navigationModeProperty, IStopComparerProvider stopComparerProvider)
 {
     return(GetNavigation(scope, navigationModeProperty).FindLastTarget(scope, currentStop, navigationModeProperty, stopComparerProvider));
 }
Beispiel #48
0
 /// <inheritdoc />
 protected override void OnServiceStop(Stop stop)
 {
     // Forward stop message
     this.Send(stop, this.managedComponents);
 }
        /// <summary>
        /// Gets properties dictionary for the specified stop built of the specified order property
        /// info objects.
        /// </summary>
        /// <param name="stop">The reference to the stop object to get properties for.</param>
        /// <param name="orderPropertiesToExport">The reference to the collection
        /// of custom order properties to be exported.</param>
        /// <returns>A dictionary with properties for an order associated with the specified
        /// stop.</returns>
        private static AttrDictionary _GetOrderProperties(
            Stop stop,
            IEnumerable<OrderPropertyInfo> orderPropertiesToExport)
        {
            Debug.Assert(stop != null);
            Debug.Assert(orderPropertiesToExport != null);
            Debug.Assert(orderPropertiesToExport.All(info => info != null));

            var properties = new AttrDictionary();
            var order = stop.AssociatedObject as Order;
            if (order == null)
            {
                return properties;
            }

            object value = null;

            foreach (var info in orderPropertiesToExport)
            {
                if (info.Name == Order.PropertyNamePlannedDate)
                    value = stop.ArriveTime;
                else
                    value = Order.GetPropertyValue(order, info.Name);

                if (value != null && value.ToString().Length > 0)
                {
                    properties.Add(info.Title, value);
                }
            }

            return properties;
        }
Beispiel #50
0
        // 获得一个日志文件的尺寸
        // return:
        //      -2  此类型的日志尚未启用
        //      -1  error
        //      0   file not found
        //      1   found
        static int GetFileSize(
            Stop stop,
            LibraryChannel channel,
            string strCacheDir,
            string strLogFileName,
            LogType logType,
            out long lServerFileSize,
            out long lCacheFileSize,
            out string strError)
        {
            strError        = "";
            lServerFileSize = 0;
            lCacheFileSize  = 0;

            string strCacheFilename = PathUtil.MergePath(strCacheDir, strLogFileName);

            FileInfo fi = new FileInfo(strCacheFilename);

            if (fi.Exists == true)
            {
                lCacheFileSize = fi.Length;
            }

            stop.SetMessage("正获得日志文件 " + strLogFileName + " 的尺寸...");

            string strXml = "";
            long   lAttachmentTotalLength = 0;

            byte[] attachment_data = null;

            string strStyle = "level-0";

            if ((logType & LogType.AccessLog) != 0)
            {
                strStyle += ",accessLog";
            }

            // 获得日志文件尺寸
            // return:
            //      -1  error
            //      0   file not found
            //      1   succeed
            //      2   超过范围
            long lRet = channel.GetOperLog(
                stop,
                strLogFileName,
                -1, // lIndex,
                -1, // lHint,
                strStyle,
                "", // strFilter
                out strXml,
                out lServerFileSize,
                0,  // lAttachmentFragmentStart,
                0,  // nAttachmentFramengLength,
                out attachment_data,
                out lAttachmentTotalLength,
                out strError);

            if (lRet == 0)
            {
                lServerFileSize = 0;
                Debug.Assert(lServerFileSize == 0, "");
                return(0);
            }
            if (lRet != 1)
            {
                return(-1);
            }
            if (lServerFileSize == -1)
            {
                strError = "日志尚未启用";
                return(-2);
            }
            Debug.Assert(lServerFileSize >= 0, "");
            return(1);
        }
        /// <summary>
        /// Gets name for the specified stop.
        /// </summary>
        /// <param name="stop">The reference to the stop object to get name for.</param>
        /// <param name="routeStops">The collection of route stops sorted by their
        /// sequence numbers for the route containing the <paramref name="stop"/>.</param>
        /// <returns>Name of the specified stop.</returns>
        private static string _GetStopName(Stop stop, IList<Stop> routeStops)
        {
            Debug.Assert(stop != null);
            Debug.Assert(routeStops != null);
            Debug.Assert(routeStops.Contains(stop));

            var order = stop.AssociatedObject as Order;
            if (order != null)
            {
                return order.Name;
            }

            var location = stop.AssociatedObject as Location;
            if (location != null)
            {
                var name = location.Name;
                if (stop == routeStops.First())
                    name = string.Format(Properties.Resources.StartLocationString, name);
                else if (stop == routeStops.Last())
                    name = string.Format(Properties.Resources.FinishLocationString, name);
                else
                    name = string.Format(Properties.Resources.RenewalLocationString, name);

                return name;
            }

            // in case of a break
            return stop.Name;
        }
Beispiel #52
0
        // 保存资源
        // parameters:
        //      strLocalPath    打算写入 metadata 的 localpath。如果为 null 表示不使用此参数
        // return:
        //		-1	error
        //		0	发现上载的文件其实为空,不必保存了
        //		1	已经保存
        public static int SaveObjectFile(
            LibraryChannel channel,
            Stop stop,
            string strResPath,
            string strLocalFileName,
            byte[] timestamp,
            string strMime,
            string strLocalPath,
            out string strError)
        {
            strError = "";

            // 检测文件尺寸
            FileInfo fi = new FileInfo(strLocalFileName);

            if (fi.Exists == false)
            {
                strError = "文件 '" + strLocalFileName + "' 不存在...";
                return(-1);
            }

            string[] ranges = null;

            if (fi.Length == 0)
            { // 空文件
                ranges    = new string[1];
                ranges[0] = "";
            }
            else
            {
                string strRange = "";
                strRange = "0-" + Convert.ToString(fi.Length - 1);

                // 按照100K作为一个chunk
                ranges = RangeList.ChunkRange(strRange,
                                              channel.UploadResChunkSize // 100 * 1024
                                              );
            }

            byte[] output_timestamp = null;

            string strLastModifyTime = DateTime.UtcNow.ToString("u");

REDOWHOLESAVE:
            string strWarning = "";

            for (int j = 0; j < ranges.Length; j++)
            {
REDOSINGLESAVE:

                if (stop != null && stop.State != 0)
                {
                    strError = "用户中断";
                    return(-1);
                }

                string strWaiting = "";
                if (j == ranges.Length - 1)
                {
                    strWaiting = " 请耐心等待...";
                }

                string    strPercent = "";
                RangeList rl         = new RangeList(ranges[j]);
                if (rl.Count >= 1)
                {
                    double ratio = (double)((RangeItem)rl[0]).lStart / (double)fi.Length;
                    strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%";
                }

                if (stop != null)
                {
                    stop.SetMessage("正在上载 " + ranges[j] + "/"
                                    + Convert.ToString(fi.Length)
                                    + " " + strPercent + " " + strLocalFileName + strWarning + strWaiting);
                }

                long lRet = channel.SaveResObject(
                    stop,
                    strResPath,
                    strLocalFileName,
                    strLocalPath,
                    strMime,
                    ranges[j],
                    j == ranges.Length - 1 ? true : false, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间
                    timestamp,
                    out output_timestamp,
                    out strError);

                timestamp = output_timestamp;

                strWarning = "";

                if (lRet == -1)
                {
                    if (channel.ErrorCode == LibraryClient.localhost.ErrorCode.TimestampMismatch)
                    {
                        timestamp = new byte[output_timestamp.Length];
                        Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length);
                        strWarning = " (时间戳不匹配, 自动重试)";
                        if (ranges.Length == 1 || j == 0)
                        {
                            goto REDOSINGLESAVE;
                        }
                        goto REDOWHOLESAVE;
                    }

                    return(-1);
                }
            }

            return(1);   // 已经保存
        }
 /// <summary>
 /// Creates label sequence symbol.
 /// </summary>
 /// <param name="stop">Stop.</param>
 /// <returns>Symbol.</returns>
 public static Control CreateLabelSequenceSymbol(Stop stop)
 {
     return _CreateMapSymbol(
         LABEL_SEQUENCE_CONTROL_TEMPLATE,
         Color.FromRgb(stop.Route.Color.R, stop.Route.Color.G, stop.Route.Color.B),
         stop.IsLocked,
         stop.IsViolated,
         stop.OrderSequenceNumber);
 }
Beispiel #54
0
        private void StopRecording()
        {
            acceptNewRecords = false;

            Stop?.Invoke(this, EventArgs.Empty);
        }
        public void TestingSequences()
        {
            Employee p1 = new Employee()
            {
                Id = 1
            };
            Employee p2 = new Employee()
            {
                Id = 1
            };

            // Equals will return true for two objects that reference the same objects.
            Console.WriteLine("p1 equals p1 -> {0}", p1.Equals(p1));

            // It will not return true if the objects have the same values
            // but have different references (are differenct objects)
            Console.WriteLine("p1 equals p2 -> {0}", p1.Equals(p2));

            Console.WriteLine();

            var listOneP1 = new List <Employee> {
                p1
            };
            var listTwoP1 = new List <Employee> {
                p1
            };

            // SequenceEqual will return true for two sequences that reference the same objects.
            // (There is only one instance of p1)
            Console.WriteLine("listOneP1 equals listTwoP1 -> {0}", listOneP1.SequenceEqual(listTwoP1));


            var listThreeP2 = new List <Employee> {
                p2
            };

            // It will not return true if the objects have the same values but have different references
            Console.WriteLine("listOneP1 equals listThreeP2 -> {0}", listOneP1.SequenceEqual(listThreeP2));


            Console.WriteLine();
            // unless... you implement IEquatable<T> and specify which properties to compare
            Stop stop1 = new Stop {
                StopID = 1
            };

            Stop stop2 = new Stop {
                StopID = 1
            };

            var listOneStop1 = new List <Stop> {
                stop1
            };
            var listTwoStop2 = new List <Stop> {
                stop2
            };

            Console.WriteLine("listOneStop1 equals listTwoStop2 -> {0}", listOneStop1.SequenceEqual(listTwoStop2));

            Console.WriteLine();
            // fyi, constructor populates collection with some stops
            var stops1 = new Stops();
            var stops2 = new Stops();

            // this will be true because Stop implements IEquatable<T>
            Console.WriteLine("stops1 equals stops2 -> {0}", stops1.SequenceEqual(stops2));

            Console.WriteLine();

            //var s1 = "tony";
            //var s2 = "tony";

            //Console.WriteLine("s1 equals s2 -> {0}", s1.Equals(s2));
        }
Beispiel #56
0
 public IComparer <Stop> CreateComparer(Stop currentStop)
 {
     return(createComparer(currentStop));
 }
 public void ArrivalsForStop(GeoCoordinate location, Stop stop)
 {
     webservice.ArrivalsForStop(
         location,
         stop,
         delegate(List<ArrivalAndDeparture> arrivals, Exception error)
         {
             if (ArrivalsForStop_Completed != null)
             {
                 ArrivalsForStop_Completed(this, new ViewModel.EventArgs.ArrivalsForStopEventArgs(stop, arrivals, error));
             }
         }
     );
 }
        void busServiceModel_CombinedInfoForLocation_Completed(object sender, EventArgs.CombinedInfoForLocationEventArgs e)
        {
            e.stops.Sort(new StopDistanceComparer(e.location));
            e.routes.Sort(new RouteDistanceComparer(e.location));

            int stopCount = 0;

            foreach (Stop stop in e.stops)
            {
                if (stopCount > maxStops)
                {
                    break;
                }

                Stop currentStop = stop;
                UIAction(() => StopsForLocation.Add(currentStop));
                stopCount++;
            }

            int routeCount = 0;

            foreach (Route route in e.routes)
            {
                if (routeCount > maxRoutes)
                {
                    break;
                }

                DisplayRoute currentDisplayRoute = new DisplayRoute()
                {
                    Route = route
                };
                DisplayRouteForLocation.Working.Add(currentDisplayRoute);
                routeCount++;
            }

            // Done with work in the background.  Flush the results out to the UI.  This is quick.
            object testref = null;

            UIAction(() =>
            {
                DisplayRouteForLocation.Toggle();
                testref = new object();
            }
                     );

            // hack to wait for the UI action to complete
            // note this executes in the background, so it's fine to be slow.
            int execcount = 0;

            while (testref == null)
            {
                execcount++;
                Thread.Sleep(100);
            }

            // finally, queue up more work
            lock (DisplayRouteForLocation.CurrentSyncRoot)
            {
                foreach (DisplayRoute r in DisplayRouteForLocation.Current)
                {
                    directionHelper[r.Route.id] = r.RouteStops;

                    operationTracker.WaitForOperation(string.Format("StopsForRoute_{0}", r.Route.id), "Loading route details...");
                    busServiceModel.StopsForRoute(LocationTracker.CurrentLocation, r.Route);
                }
            }

            operationTracker.DoneWithOperation("CombinedInfoForLocation");
        }
Beispiel #59
0
        // return:
        //      -1  出错
        //      0   放弃或中断
        //      1   成功
        public static int ExportToExcel(
            Stop stop,
            List<ListViewItem> items,
            out string strError)
        {
            strError = "";
            if (items == null || items.Count == 0)
            {
                strError = "items == null || items.Count == 0";
                return -1;
            }
            ListView list = items[0].ListView;

            // 询问文件名
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Title = "请指定要输出的 Excel 文件名";
            dlg.CreatePrompt = false;
            dlg.OverwritePrompt = true;
            // dlg.FileName = this.ExportExcelFilename;
            // dlg.InitialDirectory = Environment.CurrentDirectory;
            dlg.Filter = "Excel 文件 (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            dlg.RestoreDirectory = true;

            if (dlg.ShowDialog() != DialogResult.OK)
                return 0;

            XLWorkbook doc = null;

            try
            {
                doc = new XLWorkbook(XLEventTracking.Disabled);
                File.Delete(dlg.FileName);
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                return -1;
            }

            IXLWorksheet sheet = null;
            sheet = doc.Worksheets.Add("表格");
            // sheet.Style.Font.FontName = this.Font.Name;

            if (stop != null)
                stop.SetProgressRange(0, items.Count);

            // 每个列的最大字符数
            List<int> column_max_chars = new List<int>();

            List<XLAlignmentHorizontalValues> alignments = new List<XLAlignmentHorizontalValues>();
            foreach (ColumnHeader header in list.Columns)
            {
                if (header.TextAlign == HorizontalAlignment.Center)
                    alignments.Add(XLAlignmentHorizontalValues.Center);
                else if (header.TextAlign == HorizontalAlignment.Right)
                    alignments.Add(XLAlignmentHorizontalValues.Right);
                else
                    alignments.Add(XLAlignmentHorizontalValues.Left);

                column_max_chars.Add(0);
            }


            string strFontName = list.Font.FontFamily.Name;

            int nRowIndex = 1;
            int nColIndex = 1;
            foreach (ColumnHeader header in list.Columns)
            {
                IXLCell cell = sheet.Cell(nRowIndex, nColIndex).SetValue(header.Text);
                cell.Style.Alignment.WrapText = true;
                cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                cell.Style.Font.Bold = true;
                cell.Style.Font.FontName = strFontName;
                cell.Style.Alignment.Horizontal = alignments[nColIndex - 1];
                nColIndex++;
            }
            nRowIndex++;

            //if (stop != null)
            //    stop.SetMessage("");
            foreach (ListViewItem item in items)
            {
                Application.DoEvents();

                if (stop != null
    && stop.State != 0)
                {
                    strError = "用户中断";
                    return 0;
                }

                // List<CellData> cells = new List<CellData>();

                nColIndex = 1;
                foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
                {
                    // 统计最大字符数
                    int nChars = column_max_chars[nColIndex - 1];
                    if (subitem.Text != null && subitem.Text.Length > nChars)
                    {
                        column_max_chars[nColIndex - 1] = subitem.Text.Length;
                    }
                    IXLCell cell = sheet.Cell(nRowIndex, nColIndex).SetValue(subitem.Text);
                    cell.Style.Alignment.WrapText = true;
                    cell.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    cell.Style.Font.FontName = strFontName;
                    cell.Style.Alignment.Horizontal = alignments[nColIndex - 1];
                    nColIndex++;
                }

                if (stop != null)
                    stop.SetProgressValue(nRowIndex-1);

                nRowIndex++;
            }

            if (stop != null)
                stop.SetMessage("正在调整列宽度 ...");
            Application.DoEvents();

            double char_width = GetAverageCharPixelWidth(list);

            // 字符数太多的列不要做 width auto adjust
            const int MAX_CHARS = 30;   // 60
            int i = 0;
            foreach (IXLColumn column in sheet.Columns())
            {
                int nChars = column_max_chars[i];
                if (nChars < MAX_CHARS)
                    column.AdjustToContents();
                else
                    column.Width = (double)list.Columns[i].Width / char_width;  // Math.Min(MAX_CHARS, nChars);
                i++;
            }

            // sheet.Columns().AdjustToContents();

            // sheet.Rows().AdjustToContents();

            doc.SaveAs(dlg.FileName);
            doc.Dispose();
            return 1;
        }
        public long GetItemId(int position)
        {
            Stop stop = stops[position];

            return(Convert.ToInt32(stop.Code));
        }