コード例 #1
0
 public virtual void RemoveUnitLocation(UnitLocation ul)
 {
     if (this.UnitLocations != null && this.UnitLocations.Contains(ul))
     {
         this.UnitLocations.Remove(ul);
     }
 }
コード例 #2
0
ファイル: GameMgr.cs プロジェクト: seonwifi/Unity
 public void StartGame(UnitLocation unitLocation)
 {
     m_unitLocation = unitLocation;
     //		for(int i = 0; i < 1; ++i)
     //		{
     //			Unit unit = UnitFactory.CreateUnit("TestUnit");
     //			if(unit)
     //			{
     //				unit.Position = m_unitLocation.m_armmyStartPos[0].position;
     //				unit.m_ai.SetEndTarget(m_unitLocation.m_armmyEndTarget.position);
     //				unit.m_UnitAttribute.HPIntMax = 200;
     //				unit.m_UnitAttribute.HP = 200;
     //				m_uniMgr.AddArmmy(unit);
     //			}
     //		}
     //
     //		for(int i = 0; i < 1; ++i)
     //		{
     //			Unit unit = UnitFactory.CreateUnit("TestUnit");
     //			if(unit)
     //			{
     //				unit.Position = m_unitLocation.m_enermyStartPos[0].position;
     //				unit.m_ai.SetEndTarget(m_unitLocation.m_enermyEndTarget.position);
     //				m_uniMgr.AddEnermy(unit);
     //			}
     //		}
 }
コード例 #3
0
 public virtual void AddUnitLocation(UnitLocation ul)
 {
     if (this.UnitLocations != null && !this.UnitLocations.Contains(ul))
     {
         this.UnitLocations.Add(ul);
     }
 }
コード例 #4
0
 public void DeleteUnitLocation(UnitLocation ul)
 {
     if (ul != null)
     {
         this.unitLocationRepo.Delete(ul);
     }
 }
コード例 #5
0
    public void StartGame(UnitLocation unitLocation)
    {
        m_unitLocation = unitLocation;
//		for(int i = 0; i < 1; ++i)
//		{
//			Unit unit = UnitFactory.CreateUnit("TestUnit");
//			if(unit)
//			{
//				unit.Position = m_unitLocation.m_armmyStartPos[0].position;
//				unit.m_ai.SetEndTarget(m_unitLocation.m_armmyEndTarget.position);
//				unit.m_UnitAttribute.HPIntMax = 200;
//				unit.m_UnitAttribute.HP = 200;
//				m_uniMgr.AddArmmy(unit);
//			}
//		}
//
//		for(int i = 0; i < 1; ++i)
//		{
//			Unit unit = UnitFactory.CreateUnit("TestUnit");
//			if(unit)
//			{
//				unit.Position = m_unitLocation.m_enermyStartPos[0].position;
//				unit.m_ai.SetEndTarget(m_unitLocation.m_enermyEndTarget.position);
//				m_uniMgr.AddEnermy(unit);
//			}
//		}
    }
コード例 #6
0
ファイル: Program.cs プロジェクト: ClayCountyBCC/AVLUpdate
        public static void Main()
        {
            //var now = DateTime.Now.ToUniversalTime();
            //var tickstart = DateTime.Parse("1/1/1970").ToUniversalTime();
            //double i = now.Subtract(tickstart).TotalMilliseconds;


            // Main loop here
            DateTime endTime = DateTime.Today.AddHours(5).AddMinutes(18);

            if (DateTime.Now.Hour >= 5)
            {
                endTime = DateTime.Today.AddDays(1).AddHours(5).AddMinutes(18); // 5 am
            }
            // init the base objects.
            var cad = new Program();
            var utc = new UnitTrackingControl();
            //var avl = new AirVantageControl();
            var fcc = new FleetCompleteControl();

            while (DateTime.Now < endTime) // we want this program to run from 6 AM to 5:55 AM
            {
                try
                {
                    // pull in the current state of the unit_tracking_data table
                    // this will also update the most recent unitUsing data.
                    //utc.UpdateTrackingData();

                    //utc.UpdateAirVantage(avl.Update()); // update the data from Airvantage every 5 minutes
                    // we update the AirVantage data before we update the GIS/AVL data because
                    // we might've updated a unit's imei / phone number in the mean time.

                    UnitLocation.GetAndSave(); // get / save AVL data

                    //utc.UpdateGISUnitLocations(UnitLocation.Get());// update the data from GIS every 10 seconds

                    fcc.Update(); // get / save FC data

                    //utc.UpdateFleetComplete(fcc.Update()); // update the fleet complete data every 30 seconds.

                    //utc.Save(Program.CS_Type.Tracking); // Save the data to SQL

                    cad.UpdateCadUnitLocations(); // get / save CAD data

                    utc.UpdateUnitLocations();    // update unit tracking

                    Thread.Sleep(5000);           // this may not be needed if we await/async these calls.
                }
                catch (Exception ex)
                {
                    new ErrorLog(ex);
                }
            }
        }
コード例 #7
0
 public ActionResult Create(int currentUnitId, UnitLocationViewModel vm)
 {
     if (ModelState.IsValid)
     {
         UnitLocation ul = new UnitLocation();
         Mapper.Map(vm, ul);
         ul.Unit     = this.orgTasks.GetUnit(vm.UnitId);
         ul.Location = this.locationTasks.GetLocation(vm.LocationId);
         this.orgTasks.SaveUnitLocation(ul);
         return(RedirectToAction("Details", "Units", new { id = currentUnitId, area = "Profiling" }));
     }
     return(Create(currentUnitId));
 }
コード例 #8
0
        public ActionResult Delete(int currentUnitId, int id)
        {
            UnitLocation ul = this.orgTasks.GetUnitLocation(id);
            Unit         u  = this.orgTasks.GetUnit(currentUnitId);

            if (ul != null && u != null)
            {
                this.orgTasks.DeleteUnitLocation(ul);
                return(RedirectToAction("Details", "Units", new { id = currentUnitId }));
            }
            else
            {
                return(new HttpNotFoundResult());
            }
        }
コード例 #9
0
ファイル: UnitsService.cs プロジェクト: lanicon/Core
        public async Task <UnitLocation> GetLatestUnitLocationAsync(int unitId, DateTime?timestamp = null)
        {
            UnitLocation location = null;

            if (timestamp == null)
            {
                location = await _unitLocationRepository.GetLastUnitLocationByUnitIdAsync(unitId);
            }
            else
            {
                location = await _unitLocationRepository.GetLastUnitLocationByUnitIdTimestampAsync(unitId, timestamp.Value);
            }


            return(location);
        }
コード例 #10
0
        public ActionResult Edit(int currentUnitId, int id)
        {
            UnitLocation ul = this.orgTasks.GetUnitLocation(id);
            Unit         u  = this.orgTasks.GetUnit(currentUnitId);

            if (ul != null && u != null)
            {
                ViewBag.CurrentUnit = u;
                UnitLocationViewModel vm = new UnitLocationViewModel(ul);
                return(View(vm));
            }
            else
            {
                return(new HttpNotFoundResult());
            }
        }
コード例 #11
0
 public EntityUnitDateDTO(UnitLocation ul)
 {
     if (ul != null)
     {
         this.Unit           = ul.Unit;
         this.DayOfStart     = ul.DayOfStart;
         this.MonthOfStart   = ul.MonthOfStart;
         this.YearOfStart    = ul.YearOfStart;
         this.DayOfEnd       = ul.DayOfEnd;
         this.MonthOfEnd     = ul.MonthOfEnd;
         this.YearOfEnd      = ul.YearOfEnd;
         this.DayAsOf        = ul.DayAsOf;
         this.MonthAsOf      = ul.MonthAsOf;
         this.YearAsOf       = ul.YearAsOf;
         this.SourceTypeName = typeof(UnitLocation).Name;
     }
 }
コード例 #12
0
        public UnitLocationViewModel(UnitLocation ul)
        {
            if (ul != null)
            {
                if (ul.Unit != null)
                {
                    this.UnitId   = ul.Unit.Id;
                    this.UnitName = ul.Unit.UnitName;
                }
                if (ul.Location != null)
                {
                    this.LocationId   = ul.Location.Id;
                    this.LocationName = ul.Location.LocationName;
                }
            }

            Mapper.Map <UnitLocation, UnitLocationViewModel>(ul, this);

            this.AsOfDate = new DateLabel(this.YearAsOf, this.MonthAsOf, this.DayAsOf, false).ToString();
        }
コード例 #13
0
ファイル: UnitsService.cs プロジェクト: mrpastewart/Core
        public UnitLocation GetLatestUnitLocation(int unitId, DateTime?timestamp = null)
        {
            UnitLocation location = null;

            if (timestamp == null)
            {
                location = (from ul in _unitLocationRepository.GetAll()
                            where ul.UnitId == unitId
                            orderby ul.UnitLocationId descending
                            select ul).FirstOrDefault();
            }
            else
            {
                location = (from ul in _unitLocationRepository.GetAll()
                            where ul.UnitId == unitId && ul.Timestamp > timestamp.Value
                            orderby ul.UnitLocationId descending
                            select ul).FirstOrDefault();
            }

            return(location);
        }
コード例 #14
0
 public EntityLocationDateDTO(UnitLocation ul)
 {
     if (ul != null && ul.Location != null)
     {
         this.Location       = ul.Location;
         this.SourceTypeName = typeof(UnitLocation).Name;
         if (ul.HasStartDate())
         {
             this.StartDate       = ul.GetStartDateTime();
             this.StartDateString = ul.GetStartDateString();
         }
         if (ul.HasEndDate())
         {
             this.EndDate       = ul.GetEndDateTime();
             this.EndDateString = ul.GetEndDateString();
         }
         if (ul.HasAsOfDate())
         {
             this.AsOfDate       = ul.GetAsOfDate();
             this.AsOfDateString = ul.GetAsOfDateString();
         }
     }
 }
コード例 #15
0
 public UnitLocation SaveUnitLocation(UnitLocation ul)
 {
     return(this.unitLocationRepo.SaveOrUpdate(ul));
 }
コード例 #16
0
ファイル: UnitsService.cs プロジェクト: mrpastewart/Core
        public UnitLocation AddUnitLocation(UnitLocation location)
        {
            _unitLocationRepository.SoftAddUnitLocation(location);

            return(location);
        }
コード例 #17
0
ファイル: TankPushProbots.cs プロジェクト: evilz/TyrSc2
        public override void OnFrame(Bot bot)
        {
            if (bot.Observation.ActionErrors != null)
            {
                foreach (ActionError error in bot.Observation.ActionErrors)
                {
                    DebugUtil.WriteLine("Error with ability " + error.AbilityId + ": " + error.Result);
                }
            }

            foreach (WorkerDefenseTask task in WorkerDefenseTask.Tasks)
            {
                task.CannonDefenseRadius = 20;
            }

            TransformTask.Task.ThorsToSingleTarget();

            if (FourRax.Get().Detected)
            {
                FourRaxSuspected = true;
            }
            if (!FourRaxSuspected)
            {
                Point2D enemyRamp             = bot.MapAnalyzer.GetEnemyRamp();
                int     enemyBarrackWallCount = 0;
                foreach (Unit enemy in bot.Enemies())
                {
                    if (enemyRamp == null)
                    {
                        break;
                    }
                    if (enemy.UnitType == UnitTypes.BARRACKS && SC2Util.DistanceSq(enemy.Pos, enemyRamp) <= 5.5 * 5.5)
                    {
                        enemyBarrackWallCount++;
                    }
                }
                if (enemyBarrackWallCount >= 2)
                {
                    WorkerScoutTask.Task.Stopped = true;
                    WorkerScoutTask.Task.Clear();
                    FourRaxSuspected = true;
                }
            }

            if (bot.Frame % 224 == 0)
            {
                if (bot.OrbitalAbilityManager.ScanCommands.Count == 0)
                {
                    UnitLocation scanTarget = null;
                    foreach (UnitLocation enemy in Bot.Main.EnemyMineManager.Mines)
                    {
                        scanTarget = enemy;
                        break;
                    }
                    if (scanTarget != null)
                    {
                        bot.OrbitalAbilityManager.ScanCommands.Add(new Managers.ScanCommand()
                        {
                            FromFrame = bot.Frame, Pos = SC2Util.To2D(scanTarget.Pos)
                        });
                    }
                }
            }

            if (bot.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) == 1 &&
                Completed(UnitTypes.SIEGE_TANK) > 0 &&
                bot.Frame <= 22.4 * 60 * 4 &&
                Count(UnitTypes.COMMAND_CENTER) < 3)
            {
                IdleTask.Task.OverrideTarget = SC2Util.Point((bot.MapAnalyzer.GetMainRamp().X + Natural.BaseLocation.Pos.X) / 2f, (bot.MapAnalyzer.GetMainRamp().Y + Natural.BaseLocation.Pos.Y) / 2f);
            }
            else if (FourRaxSuspected &&
                     Completed(UnitTypes.SIEGE_TANK) > 0 &&
                     Count(UnitTypes.COMMAND_CENTER) == 2)
            {
                IdleTask.Task.OverrideTarget = SC2Util.Point((NaturalDefensePos.X + Natural.BaseLocation.Pos.X) / 2f, (NaturalDefensePos.Y + Natural.BaseLocation.Pos.Y) / 2f);
            }
            else if (Count(UnitTypes.COMMAND_CENTER) > 3)
            {
                IdleTask.Task.OverrideTarget = OverrideDefenseTarget;
            }
            else
            {
                IdleTask.Task.OverrideTarget = null;
            }

            if (ReapersDetected)
            {
                SiegeTask.Task.Stopped = true;

                TimingAttackTask.Task.RequiredSize = 30;
                TimingAttackTask.Task.RetreatSize  = 8;
                TimingAttackTask.Task.Stopped      = false;
            }
            else
            {
                SiegeTask.Task.Stopped = true;

                if (Completed(UnitTypes.LIBERATOR) >= 4 ||
                    FoodUsed() >= 198)
                {
                    TimingAttackTask.Task.RequiredSize = 50;
                }
                else
                {
                    TimingAttackTask.Task.RequiredSize = 70;
                }
                TimingAttackTask.Task.RetreatSize       = 12;
                TimingAttackTask.Task.Stopped           = false;
                TimingAttackTask.Task.BeforeControllers = AttackMicroControllers;
            }

            /*
             * else
             * {
             *  TimingAttackTask.Task.Stopped = true;
             *
             *  if (Completed(UnitTypes.LIBERATOR) >= 4
             || FoodUsed() >= 198)
             ||     SiegeTask.Task.RequiredSize = 50;
             || else
             ||     SiegeTask.Task.RequiredSize = 70;
             || SiegeTask.Task.RetreatSize = 12;
             || SiegeTask.Task.Stopped = false;
             || SiegeTask.Task.CustomControllers = AttackMicroControllers;
             ||}*/

            bool attacking = (!TimingAttackTask.Task.Stopped && TimingAttackTask.Task.IsNeeded()) ||
                             (!SiegeTask.Task.Stopped && SiegeTask.Task.IsNeeded());

            foreach (Task task in VikingDefenseTasks)
            {
                task.Stopped = attacking;
            }
            foreach (Task task in TankDefenseTasks)
            {
                task.Stopped = attacking;
            }
            foreach (Task task in LiberatorDefenseTasks)
            {
                task.Stopped = attacking;
            }

            int defendingTanksPerBase = 2;

            if (Completed(UnitTypes.SIEGE_TANK) >= 4 * (Count(UnitTypes.COMMAND_CENTER) - 1))
            {
                defendingTanksPerBase = 4;
            }
            else if (Completed(UnitTypes.SIEGE_TANK) >= 3 * (Count(UnitTypes.COMMAND_CENTER) - 1))
            {
                defendingTanksPerBase = 3;
            }

            foreach (DefenseSquadTask task in TankDefenseTasks)
            {
                task.MaxDefenders = defendingTanksPerBase;
            }

            foreach (DefenseSquadTask task in DefenseSquadTask.Tasks)
            {
                task.Priority     = 4;
                task.MaxDefenders = 3;
                task.Stopped      = task.Base != Main;
            }

            DefenseTask.AirDefenseTask.ExpandDefenseRadius    = 20;
            DefenseTask.GroundDefenseTask.ExpandDefenseRadius = 20;
            DefenseTask.AirDefenseTask.MaxDefenseRadius       = 80;
            DefenseTask.GroundDefenseTask.MaxDefenseRadius    = 80;
            if (Count(UnitTypes.COMMAND_CENTER) > 2)
            {
                DefenseTask.GroundDefenseTask.MainDefenseRadius = 40;
                DefenseTask.AirDefenseTask.MainDefenseRadius    = 40;
            }
            else
            {
                DefenseTask.GroundDefenseTask.MainDefenseRadius = 30;
                DefenseTask.AirDefenseTask.MainDefenseRadius    = 30;
            }

            if (StrategyAnalysis.Bio.Get().Detected)
            {
                ReapersDetected = false;
            }
            else if ((bot.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) > 4 ||
                      bot.EnemyStrategyAnalyzer.Count(UnitTypes.BANSHEE) >= 1) &&
                     bot.Frame < 22.4 * 600)
            {
                ReapersDetected = true;
            }
            BunkerDefendersTask.Task.LeaveBunkers = !StrategyAnalysis.Bio.Get().Detected &&
                                                    bot.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) >= 1 &&
                                                    (bot.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) >= 2 || bot.Frame <= 22.4 * 60 * 4);

            if (ReapersDetected)
            {
                DefenseSquadTask.Enable(CycloneDefenseTasks, false, false);
            }
            else
            {
                foreach (DefenseSquadTask task in CycloneDefenseTasks)
                {
                    task.Stopped = true;
                    task.Clear();
                }
            }

            if (bot.EnemyStrategyAnalyzer.Count(UnitTypes.STARPORT_TECH_LAB)
                + bot.EnemyStrategyAnalyzer.Count(UnitTypes.BANSHEE) > 0 ||
                (bot.EnemyStrategyAnalyzer.Count(UnitTypes.FACTORY) > 0 && bot.Frame <= 22.4 * 60 * 2.5))
            {
                SuspectCloackedBanshees = true;
            }

            if (FourRaxSuspected)
            {
                bot.OrbitalAbilityManager.SaveEnergy = 0;
            }
            else
            {
                bot.OrbitalAbilityManager.SaveEnergy = 50;
            }

            if (bot.TargetManager.PotentialEnemyStartLocations.Count == 1 &&
                !ScanTimingsSet &&
                bot.Frame >= 22.4 * 60 * 2.25 &&
                !FourRaxSuspected
                )
            {
                ScanTimingsSet = true;
                bot.OrbitalAbilityManager.ScanCommands.Add(new ScanCommand()
                {
                    Pos       = bot.TargetManager.PotentialEnemyStartLocations[0],
                    FromFrame = (int)(22.4 * 60 * 2.5)
                });
            }
        }
コード例 #18
0
ファイル: SystemQueueLogic.cs プロジェクト: guyt101z/Core
        public static bool ProcessSystemQueueItem(CqrsEvent qi)
        {
            bool success = true;

            if (qi != null)
            {
                switch ((CqrsEventTypes)qi.Type)
                {
                case CqrsEventTypes.None:
                    break;

                case CqrsEventTypes.UnitLocation:
                    UnitLocation unitLocation = null;
                    try
                    {
                        unitLocation = ObjectSerialization.Deserialize <UnitLocation>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (unitLocation != null)
                    {
                        IUnitsService unitService;
                        try
                        {
                            unitService = Bootstrapper.GetKernel().Resolve <IUnitsService>();
                            unitService.AddUnitLocation(unitLocation);
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            unitService = null;
                        }
                    }
                    break;

                case CqrsEventTypes.PushRegistration:

                    PushUri data = null;
                    try
                    {
                        data = ObjectSerialization.Deserialize <PushUri>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (data != null)
                    {
                        var pushService     = Bootstrapper.GetKernel().Resolve <IPushService>();
                        var resgriterResult = pushService.Register(data).Result;

                        pushService = null;
                    }
                    break;

                case CqrsEventTypes.UnitPushRegistration:
                    PushRegisterionEvent unitData = null;
                    try
                    {
                        unitData = ObjectSerialization.Deserialize <PushRegisterionEvent>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (unitData != null)
                    {
                        PushUri pushUri = new PushUri();
                        pushUri.PushUriId    = unitData.PushUriId;
                        pushUri.UserId       = unitData.UserId;
                        pushUri.PlatformType = unitData.PlatformType;
                        pushUri.PushLocation = unitData.PushLocation;
                        pushUri.DepartmentId = unitData.DepartmentId;
                        pushUri.UnitId       = unitData.UnitId;
                        pushUri.DeviceId     = unitData.DeviceId;
                        pushUri.Uuid         = unitData.Uuid;

                        var pushService = Bootstrapper.GetKernel().Resolve <IPushService>();
                        var unitResult  = pushService.RegisterUnit(pushUri).Result;

                        pushService = null;
                    }
                    break;

                case CqrsEventTypes.StripeChargeSucceeded:
                    var succeededCharge = Stripe.Mapper <StripeCharge> .MapFromJson(qi.Data);

                    if (succeededCharge != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripePayment(succeededCharge);
                    }
                    break;

                case CqrsEventTypes.StripeChargeFailed:
                    var failedCharge = Stripe.Mapper <StripeCharge> .MapFromJson(qi.Data);

                    if (failedCharge != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeChargeFailed(failedCharge);
                    }
                    break;

                case CqrsEventTypes.StripeChargeRefunded:
                    var refundedCharge = Stripe.Mapper <StripeCharge> .MapFromJson(qi.Data);

                    if (refundedCharge != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeSubscriptionRefund(refundedCharge);
                    }
                    break;

                case CqrsEventTypes.StripeSubUpdated:
                    var updatedSubscription = Stripe.Mapper <StripeSubscription> .MapFromJson(qi.Data);

                    if (updatedSubscription != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeSubscriptionUpdate(updatedSubscription);
                    }
                    break;

                case CqrsEventTypes.StripeSubDeleted:
                    var deletedSubscription = Stripe.Mapper <StripeSubscription> .MapFromJson(qi.Data);

                    if (deletedSubscription != null)
                    {
                        var paymentProviderService = Bootstrapper.GetKernel().Resolve <IPaymentProviderService>();

                        paymentProviderService.ProcessStripeSubscriptionCancellation(deletedSubscription);
                    }
                    break;

                case CqrsEventTypes.ClearDepartmentCache:

                    int departmentId;

                    if (int.TryParse(qi.Data, out departmentId))
                    {
                        var userProfileService = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                        //var departmentSettingsService = Bootstrapper.GetKernel().Resolve<IDepartmentSettingsService>();
                        var subscriptionService = Bootstrapper.GetKernel().Resolve <ISubscriptionsService>();
                        //var scheduledTasksService = Bootstrapper.GetKernel().Resolve<IScheduledTasksService>();
                        var departmentService   = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                        var actionLogsService   = Bootstrapper.GetKernel().Resolve <IActionLogsService>();
                        var customStatesService = Bootstrapper.GetKernel().Resolve <ICustomStateService>();
                        var usersService        = Bootstrapper.GetKernel().Resolve <IUsersService>();

                        subscriptionService.ClearCacheForCurrentPayment(departmentId);
                        departmentService.InvalidateDepartmentUsersInCache(departmentId);
                        departmentService.InvalidateDepartmentInCache(departmentId);
                        departmentService.InvalidatePersonnelNamesInCache(departmentId);
                        userProfileService.ClearAllUserProfilesFromCache(departmentId);
                        usersService.ClearCacheForDepartment(departmentId);
                        actionLogsService.InvalidateActionLogs(departmentId);
                        customStatesService.InvalidateCustomStateInCache(departmentId);
                        departmentService.InvalidateDepartmentMembers();

                        userProfileService  = null;
                        subscriptionService = null;
                        departmentService   = null;
                        actionLogsService   = null;
                        customStatesService = null;
                        usersService        = null;
                    }
                    else
                    {
                    }
                    break;

                case CqrsEventTypes.NewChatMessage:
                    NewChatNotificationEvent newChatEvent = null;

                    if (qi != null && !String.IsNullOrWhiteSpace(qi.Data))
                    {
                        try
                        {
                            newChatEvent = ObjectSerialization.Deserialize <NewChatNotificationEvent>(qi.Data);
                        }
                        catch (Exception ex)
                        {
                        }

                        if (newChatEvent != null)
                        {
                            var userProfileService   = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                            var communicationService = Bootstrapper.GetKernel().Resolve <ICommunicationService>();
                            var usersService         = Bootstrapper.GetKernel().Resolve <IUsersService>();


                            if (newChatEvent != null && newChatEvent.RecipientUserIds != null && newChatEvent.RecipientUserIds.Count > 0)
                            {
                                List <UserProfile> profiles = new List <UserProfile>();
                                if (newChatEvent.RecipientUserIds.Count == 1)
                                {
                                    profiles.Add(userProfileService.GetProfileByUserId(newChatEvent.RecipientUserIds.First()));
                                }
                                else
                                {
                                    profiles.AddRange(userProfileService.GetSelectedUserProfiles(newChatEvent.RecipientUserIds));
                                }

                                var sendingUserProfile = userProfileService.GetProfileByUserId(newChatEvent.SendingUserId);

                                var chatResult = communicationService.SendChat(newChatEvent.Id, newChatEvent.SendingUserId, newChatEvent.GroupName, newChatEvent.Message, sendingUserProfile, profiles).Result;
                            }

                            userProfileService   = null;
                            communicationService = null;
                            usersService         = null;
                        }
                    }
                    break;

                case CqrsEventTypes.TroubleAlert:
                    TroubleAlertEvent troubleAlertEvent = null;
                    try
                    {
                        troubleAlertEvent = ObjectSerialization.Deserialize <TroubleAlertEvent>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (troubleAlertEvent != null && troubleAlertEvent.DepartmentId.HasValue)
                    {
                        var userProfileService        = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                        var communicationService      = Bootstrapper.GetKernel().Resolve <ICommunicationService>();
                        var usersService              = Bootstrapper.GetKernel().Resolve <IUsersService>();
                        var departmentService         = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                        var unitsService              = Bootstrapper.GetKernel().Resolve <IUnitsService>();
                        var departmentGroupService    = Bootstrapper.GetKernel().Resolve <IDepartmentGroupsService>();
                        var callsService              = Bootstrapper.GetKernel().Resolve <ICallsService>();
                        var departmentSettingsService = Bootstrapper.GetKernel().Resolve <IDepartmentSettingsService>();
                        var geoLocationProvider       = Bootstrapper.GetKernel().Resolve <IGeoLocationProvider>();

                        var admins = departmentService.GetAllAdminsForDepartment(troubleAlertEvent.DepartmentId.Value);
                        var unit   = unitsService.GetUnitById(troubleAlertEvent.UnitId);
                        List <UserProfile> profiles = new List <UserProfile>();
                        Call   call             = null;
                        string departmentNumber = "";
                        string callAddress      = "No Call Address";
                        string unitAproxAddress = "Unknown Unit Address";

                        departmentNumber = departmentSettingsService.GetTextToCallNumberForDepartment(troubleAlertEvent.DepartmentId.Value);

                        if (admins != null)
                        {
                            profiles.AddRange(userProfileService.GetSelectedUserProfiles(admins.Select(x => x.Id).ToList()));
                        }

                        if (unit != null)
                        {
                            if (unit.StationGroupId.HasValue)
                            {
                                var groupAdmins = departmentGroupService.GetAllAdminsForGroup(unit.StationGroupId.Value);

                                if (groupAdmins != null)
                                {
                                    profiles.AddRange(userProfileService.GetSelectedUserProfiles(groupAdmins.Select(x => x.UserId).ToList()));
                                }
                            }

                            if (troubleAlertEvent.CallId.HasValue && troubleAlertEvent.CallId.GetValueOrDefault() > 0)
                            {
                                call = callsService.GetCallById(troubleAlertEvent.CallId.Value);

                                if (!String.IsNullOrEmpty(call.Address))
                                {
                                    callAddress = call.Address;
                                }
                                else if (!String.IsNullOrEmpty(call.GeoLocationData))
                                {
                                    string[] points = call.GeoLocationData.Split(char.Parse(","));

                                    if (points != null && points.Length == 2)
                                    {
                                        callAddress = geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1]));
                                    }
                                }
                            }

                            if (!String.IsNullOrWhiteSpace(troubleAlertEvent.Latitude) && !String.IsNullOrWhiteSpace(troubleAlertEvent.Longitude))
                            {
                                unitAproxAddress = geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(troubleAlertEvent.Latitude), double.Parse(troubleAlertEvent.Longitude));
                            }

                            communicationService.SendTroubleAlert(troubleAlertEvent, unit, call, departmentNumber, troubleAlertEvent.DepartmentId.Value, callAddress, unitAproxAddress, profiles);
                        }
                    }

                    break;

                case CqrsEventTypes.AuditLog:
                    AuditEvent auditEvent = null;
                    try
                    {
                        auditEvent = ObjectSerialization.Deserialize <AuditEvent>(qi.Data);
                    }
                    catch (Exception ex)
                    {
                    }

                    if (auditEvent != null)
                    {
                        var auditLogsRepository = Bootstrapper.GetKernel().Resolve <IGenericDataRepository <AuditLog> >();
                        var userProfileService  = Bootstrapper.GetKernel().Resolve <IUserProfileService>();

                        var profile = userProfileService.GetProfileByUserId(auditEvent.UserId);

                        var auditLog = new AuditLog();
                        auditLog.DepartmentId = auditEvent.DepartmentId;
                        auditLog.UserId       = auditEvent.UserId;
                        auditLog.LogType      = (int)auditEvent.Type;

                        switch (auditEvent.Type)
                        {
                        case AuditLogTypes.DepartmentSettingsChanged:
                            auditLog.Message = string.Format("{0} updated the department settings", profile.FullName.AsFirstNameLastName);
                            var compareLogic = new CompareLogic();
                            ComparisonResult auditCompareResult = compareLogic.Compare(auditEvent.Before, auditEvent.After);
                            auditLog.Data = auditCompareResult.DifferencesString;
                            break;

                        case AuditLogTypes.UserAdded:
                            if (auditEvent.After != null && auditEvent.After.GetType().BaseType == typeof(IdentityUser))
                            {
                                var newProfile = userProfileService.GetProfileByUserId(((IdentityUser)auditEvent.After).UserId);
                                auditLog.Message = string.Format("{0} added new user {1}", profile.FullName.AsFirstNameLastName, newProfile.FullName.AsFirstNameLastName);

                                auditLog.Data = $"New UserId: {newProfile.UserId}";
                            }
                            break;

                        case AuditLogTypes.UserRemoved:

                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(UserProfile))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} removed user {(((UserProfile)auditEvent.Before).FullName.AsFirstNameLastName)}";
                                auditLog.Data    = "No Data";
                            }

                            break;

                        case AuditLogTypes.GroupAdded:
                            if (auditEvent.After != null && auditEvent.After.GetType() == typeof(DepartmentGroup))
                            {
                                if (((DepartmentGroup)auditEvent.After).Type.HasValue && ((DepartmentGroup)auditEvent.After).Type.Value == (int)DepartmentGroupTypes.Station)
                                {
                                    auditLog.Message = $"{profile.FullName.AsFirstNameLastName} added station group {((DepartmentGroup)auditEvent.After).Name}";
                                }
                                else
                                {
                                    auditLog.Message = $"{profile.FullName.AsFirstNameLastName} added organizational group {((DepartmentGroup)auditEvent.After).Name}";
                                }

                                auditLog.Data = $"GroupId: {((DepartmentGroup)auditEvent.After).DepartmentGroupId}";
                            }
                            break;

                        case AuditLogTypes.GroupRemoved:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(DepartmentGroup))
                            {
                                auditLog.Message = string.Format("{0} removed group {1}", profile.FullName.AsFirstNameLastName, ((DepartmentGroup)auditEvent.Before).Name);
                                auditLog.Data    = "No Data";
                            }
                            break;

                        case AuditLogTypes.GroupChanged:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(DepartmentGroup) && auditEvent.After != null &&
                                auditEvent.After.GetType() == typeof(DepartmentGroup))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated group {((DepartmentGroup)auditEvent.After).Name}";
                                var compareLogicGroup = new CompareLogic();

                                ComparisonResult resultGroup = compareLogicGroup.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultGroup.DifferencesString;
                            }
                            break;

                        case AuditLogTypes.UnitAdded:
                            if (auditEvent.After != null && auditEvent.After.GetType() == typeof(Unit))
                            {
                                auditLog.Message = string.Format("{0} added unit {1}", profile.FullName.AsFirstNameLastName, ((Unit)auditEvent.After).Name);
                                auditLog.Data    = $"UnitId: {((Unit)auditEvent.After).UnitId}";
                            }
                            break;

                        case AuditLogTypes.UnitRemoved:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(Unit))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} removed unit {((Unit)auditEvent.Before).Name}";
                                auditLog.Data    = "No Data";
                            }
                            break;

                        case AuditLogTypes.UnitChanged:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(Unit) && auditEvent.After != null && auditEvent.After.GetType() == typeof(Unit))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated unit {((Unit)auditEvent.After).Name}";

                                var compareLogicUnit        = new CompareLogic();
                                ComparisonResult resultUnit = compareLogicUnit.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultUnit.DifferencesString;
                            }
                            break;

                        case AuditLogTypes.ProfileUpdated:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(UserProfile) && auditEvent.After != null && auditEvent.After.GetType() == typeof(UserProfile))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated the profile for {((UserProfile)auditEvent.After).FullName.AsFirstNameLastName}";

                                var compareLogicProfile        = new CompareLogic();
                                ComparisonResult resultProfile = compareLogicProfile.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultProfile.DifferencesString;
                            }
                            break;

                        case AuditLogTypes.PermissionsChanged:
                            if (auditEvent.Before != null && auditEvent.Before.GetType() == typeof(Permission) && auditEvent.After != null && auditEvent.After.GetType() == typeof(Permission))
                            {
                                auditLog.Message = $"{profile.FullName.AsFirstNameLastName} updated the department permissions";

                                var compareLogicProfile        = new CompareLogic();
                                ComparisonResult resultProfile = compareLogicProfile.Compare(auditEvent.Before, auditEvent.After);
                                auditLog.Data = resultProfile.DifferencesString;
                            }
                            break;
                        }

                        if (String.IsNullOrWhiteSpace(auditLog.Data))
                        {
                            auditLog.Data = "No Data";
                        }

                        if (!String.IsNullOrWhiteSpace(auditLog.Message))
                        {
                            auditLog.LoggedOn = DateTime.UtcNow;
                            auditLogsRepository.SaveOrUpdate(auditLog);
                        }
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(success);
        }
コード例 #19
0
        public async Task <ActionResult> SetUnitLocation(UnitLocationInput locationInput, CancellationToken cancellationToken)
        {
            var unit = await _unitsService.GetUnitByIdAsync(locationInput.Uid);

            if (unit == null)
            {
                return(NotFound());
            }

            if (unit.DepartmentId != DepartmentId)
            {
                return(Unauthorized());
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    CqrsEvent    locationEvent = new CqrsEvent();
                    UnitLocation location      = new UnitLocation();
                    location.UnitId = locationInput.Uid;

                    if (locationInput.Tms.HasValue)
                    {
                        location.Timestamp = locationInput.Tms.Value;
                    }
                    else
                    {
                        location.Timestamp = DateTime.UtcNow;
                    }

                    if (!String.IsNullOrWhiteSpace(locationInput.Lat) && locationInput.Lat != "NaN" && !String.IsNullOrWhiteSpace(locationInput.Lon) && locationInput.Lon != "NaN")
                    {
                        location.Latitude  = decimal.Parse(locationInput.Lat);
                        location.Longitude = decimal.Parse(locationInput.Lon);

                        if (!String.IsNullOrWhiteSpace(locationInput.Acc) && locationInput.Acc != "NaN")
                        {
                            location.Accuracy = decimal.Parse(locationInput.Acc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alt) && locationInput.Alt != "NaN")
                        {
                            location.Altitude = decimal.Parse(locationInput.Alt);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alc) && locationInput.Alc != "NaN")
                        {
                            location.AltitudeAccuracy = decimal.Parse(locationInput.Alc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Spd) && locationInput.Spd != "NaN")
                        {
                            location.Speed = decimal.Parse(locationInput.Spd);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Hdn) && locationInput.Hdn != "NaN")
                        {
                            location.Heading = decimal.Parse(locationInput.Hdn);
                        }

                        locationEvent.Type = (int)CqrsEventTypes.UnitLocation;
                        locationEvent.Data = ObjectSerialization.Serialize(location);
                        await _cqrsProvider.EnqueueCqrsEventAsync(locationEvent);

                        return(CreatedAtAction(nameof(SetUnitLocation), new { id = locationInput.Uid }, locationEvent));
                    }
                    else
                    {
                        return(Ok());
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    return(BadRequest());
                }
            }

            return(BadRequest());
        }
コード例 #20
0
        public HttpResponseMessage SetUnitLocation(UnitLocationInput locationInput)
        {
            var unit = _unitsService.GetUnitById(locationInput.Uid);

            if (unit == null)
            {
                throw HttpStatusCode.NotFound.AsException();
            }

            if (unit.DepartmentId != DepartmentId)
            {
                throw HttpStatusCode.Unauthorized.AsException();
            }

            if (this.ModelState.IsValid)
            {
                try
                {
                    CqrsEvent    locationEvent = new CqrsEvent();
                    UnitLocation location      = new UnitLocation();
                    location.UnitId = locationInput.Uid;

                    if (locationInput.Tms.HasValue)
                    {
                        location.Timestamp = locationInput.Tms.Value;
                    }
                    else
                    {
                        location.Timestamp = DateTime.UtcNow;
                    }

                    if (!String.IsNullOrWhiteSpace(locationInput.Lat) && locationInput.Lat != "NaN" && !String.IsNullOrWhiteSpace(locationInput.Lon) && locationInput.Lon != "NaN")
                    {
                        location.Latitude  = decimal.Parse(locationInput.Lat);
                        location.Longitude = decimal.Parse(locationInput.Lon);

                        if (!String.IsNullOrWhiteSpace(locationInput.Acc) && locationInput.Acc != "NaN")
                        {
                            location.Accuracy = decimal.Parse(locationInput.Acc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alt) && locationInput.Alt != "NaN")
                        {
                            location.Altitude = decimal.Parse(locationInput.Alt);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Alc) && locationInput.Alc != "NaN")
                        {
                            location.AltitudeAccuracy = decimal.Parse(locationInput.Alc);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Spd) && locationInput.Spd != "NaN")
                        {
                            location.Speed = decimal.Parse(locationInput.Spd);
                        }

                        if (!String.IsNullOrWhiteSpace(locationInput.Hdn) && locationInput.Hdn != "NaN")
                        {
                            location.Heading = decimal.Parse(locationInput.Hdn);
                        }

                        locationEvent.Type = (int)CqrsEventTypes.UnitLocation;
                        locationEvent.Data = ObjectSerialization.Serialize(location);
                        _cqrsProvider.EnqueueCqrsEvent(locationEvent);

                        return(Request.CreateResponse(HttpStatusCode.Created));
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotModified));
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogException(ex);
                    throw HttpStatusCode.InternalServerError.AsException();
                }
            }

            throw HttpStatusCode.BadRequest.AsException();
        }
コード例 #21
0
ファイル: UnitsService.cs プロジェクト: lanicon/Core
 public async Task <UnitLocation> AddUnitLocationAsync(UnitLocation location, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await _unitLocationRepository.SaveOrUpdateAsync(location, cancellationToken));
 }