示例#1
0
 public void HandleError(object sender, EventArgs args)
 {
     log.Error("The error is occured", Server.GetLastError());
     ActionProcessor.LastAction = Server.GetLastError().Message;
     ActionProcessor.GetHolder().IsError = true;
     Application["LastError"] = Server.GetLastError();
 }
示例#2
0
        public static void Save(Requester requester)
        {
            log.DebugFormat("Save requester with id '{0}'", requester.ID);
            var service = ServiceManager.GetService <RequesterService>();
            var dto     = new DataConverter <Requester>().Convert <RequesterDTO>(requester);
            int?requesterId;

            if (requester.IsNew)
            {
                requesterId = service.Create(dto);
            }
            else
            {
                service.Update(dto);
                requesterId = dto.ID;
                DataPortal.Instance.ResetCachedValue(typeof(Requester), requesterId);
            }

            var actionProcessor = new ActionProcessor();

            requester.ID     = requesterId;
            requester.UserID = requesterId;
            ActionTypeEnum actionTypeEnum = requester.IsNew ? ActionTypeEnum.Add : ActionTypeEnum.Update;

            actionProcessor.ProcessAction(actionTypeEnum, requester);
        }
示例#3
0
        public static void DoPreProcessing()
        {
            string commandFile = @"E:\SourceCode\40copoka\DPP\Source\UnitTests\CommandLineAction.UnitTest\Output\CommandLineAction.UnitTest.exe";

            var action = new ActionParam <string>()
            {
                ParamName = ActionParamNamesCore.Action,
                Value     = ActionsCore.RunCommandLine
            };

            var prm = new IActionParam[]
            {
                action,
                new ActionParam <string>()
                {
                    ParamName = ActionParamNamesCore.PathToFile, Value = commandFile
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParamNamesCore.DataValue, Value = string.Empty
                },
                new ActionParam <ActionProcessCommandLineDelegate>()
                {
                    ParamName = ActionParamNamesCore.OutputDataReceivedDelegate, Value = OnOutputCommandLine
                },
                new ActionParam <ActionProcessCommandLineDelegate>()
                {
                    ParamName = ActionParamNamesCore.ErrorDataReceivedDelegate, Value = OnErrorCommandLine
                }
            };

            var procc = new ActionProcessor(prm);
            var res   = procc.Process <StringActionResult>();
        }
示例#4
0
 public ConnectionToClient(ILog log, IDatabase data, ISubscriber sub)
 {
     logger                = log;
     database              = data;
     subscriber            = sub;
     actionProcessor       = new ActionProcessor(log, data, sub, this);
     userInputInterpretter = new UserInputInterpretter();
 }
        public async Task Test_ActionProcessor_No_Actions()
        {
            var appSettings = new ApplicationSettings();
            var sut         = new ActionProcessor(ServiceProvider, LoggerFactory, appSettings);

            await sut.ExecuteAsync();

            Assert.True(Logger.LoggedMessages.Count == 1);
            Assert.Equal(LogLevel.Error, Logger.LoggedMessages[0].LogLevel);
        }
示例#6
0
        private IActionProcessor GetProcessor(bool start = true, bool withRecovery = false)
        {
            var processor = new ActionProcessor(_requirements, Sys);

            if (start)
            {
                processor.Start(withRecovery);
            }

            return(processor);
        }
示例#7
0
 public World(View view)
 {
     View = view;
     Map  = new Map(view);
     Map.TrySpawnAt(Map.Size / 2, Map.Size / 2, out Player);
     for (int i = 0; i < numberOfGlobs; i++)
     {
         Entities.Add(Map.Spawn <Glob>());
     }
     ActionProcessor = new ActionProcessor(this, Map);
 }
示例#8
0
    private void requestSource_Updated(object sender, TpObjectDataSourceEventArgs e)
    {
        var requester = (Requester)e.BusinessObject;

        ActionProcessor.ReplaceLastAction("You were registered successfully");

        LastActionLabel.DoReset = false;

        FormsAuthentication.RedirectFromLoginPage(requester.ID.ToString(), false);
        Globals.IsLogOut = false;
    }
示例#9
0
        public void Process()
        {
            var gotCalled = false;
            var ap        = new ActionProcessor <int>(async(i) =>
            {
                gotCalled = true;
                return(await Task.FromResult <bool>(true));
            });

            ap.Process(0).Wait();

            Assert.IsTrue(gotCalled);
        }
示例#10
0
        private IActionProcessor GetProcessor(bool start = true, bool withRecovery = false)
        {
            var requirements = new TestProcessorRequirements(new PreliminaryContractActionPipelineConfiguration(_kernel), _requestPersistence, _statePersistence, null, _responseObserver);

            var processor = new ActionProcessor(requirements, Sys);

            if (start)
            {
                processor.Start(withRecovery);
            }

            return(processor);
        }
        public async Task Test_ActionProcessor_Action_None_Enabled()
        {
            var appSettings = new ApplicationSettings();

            Fixture.AddManyTo(appSettings.Actions, 23);
            appSettings.Actions.ForEach(action => action.Enabled = false);
            var sut = new ActionProcessor(ServiceProvider, LoggerFactory, appSettings);

            await sut.ExecuteAsync();

            Assert.True(Logger.LoggedMessages.Count == 1);
            Assert.Equal(LogLevel.Error, Logger.LoggedMessages[0].LogLevel);
        }
        public async Task Test_ActionProcessor_Action_Run_Enabled_No_Service_Found()
        {
            const int actionCount = 8;
            var       appSettings = new ApplicationSettings();

            Fixture.AddManyTo(appSettings.Actions, actionCount);
            appSettings.Actions.ForEach(x => x.FailOnError = false);

            var sut = new ActionProcessor(ServiceProvider, LoggerFactory, appSettings);

            await sut.ExecuteAsync();

            Assert.Equal(actionCount, Logger.LoggedMessages.Count(l => l.LogLevel == LogLevel.Error));
        }
        public async Task Test_ActionProcessor_Specific_Action_Found_Warn_Others_Not_Found()
        {
            var appSettings = new ApplicationSettings();

            Fixture.AddManyTo(appSettings.Actions, 25);
            appSettings.Actions.ForEach(x => x.FailOnError = false);

            var sut = new ActionProcessor(ServiceProvider, LoggerFactory, appSettings);

            await sut.ExecuteAsync(new List <string> {
                appSettings.Actions.First().Name, Fixture.Create("Action")
            });

            Assert.Equal(1, Logger.LoggedMessages.Count(l => l.LogLevel == LogLevel.Warning));
        }
        public async Task Test_ActionProcessor_Specific_Action_Not_Found()
        {
            var appSettings = new ApplicationSettings();

            Fixture.AddManyTo(appSettings.Actions, 25);

            var sut = new ActionProcessor(ServiceProvider, LoggerFactory, appSettings);

            await sut.ExecuteAsync(new List <string>
            {
                Fixture.Create("Action"),
                Fixture.Create("Action")
            });

            Assert.True(Logger.LoggedMessages.Count == 1);
            Assert.Equal(LogLevel.Error, Logger.LoggedMessages[0].LogLevel);
        }
示例#15
0
        public static void Save(Request request)
        {
            var service = ServiceManager.GetService <RequestService>();
            var dto     = new DataConverter <Request>().Convert <RequestDTO>(request);

            dto.SourceType = RequestSourceEnum.External;
            var actionTypeEnum = request.IsNew ? ActionTypeEnum.Add : ActionTypeEnum.Update;

            try
            {
                if (request.IsNew)
                {
                    request.ID        = service.Save(dto, Requester.Logged.ID, request.IsUrgent);
                    request.RequestID = request.ID;
                }
                else
                {
                    request.LastEditorID = Requester.Logged.ID;
                    service.Update(dto);
                }

                var actionProcessor = new ActionProcessor();

                actionProcessor.ProcessAction(actionTypeEnum, request);
            }
            catch (Exception ex)
            {
                log.Debug("Error catched", ex);

                var error = ex.Message;

                if (ex.Message.Contains("AccessDeniedException"))
                {
                    error = "The request was not posted. Access is denied.";
                }

                if (ex.Message.Contains("password is invalid"))
                {
                    error = "The request was not posted. The provided password is invalid.";
                }

                ActionProcessor.SetLastAction(error, null, ActionTypeEnum.None);
                ActionProcessor.IsError = true;
            }
        }
示例#16
0
        public virtual void Process(TPacket packet)
        {
            Check.Require(packet != null);
            if (FilterProcessor != null)
            {
                FilterProcessor.Process(packet);
            }

            if (packet.HasError)
            {
                return;
            }

            if (ActionProcessor != null)
            {
                ActionProcessor.Process(packet);
            }
        }
示例#17
0
    protected void OnUpdatedItem(object sender, FormViewUpdatedEventArgs e)
    {
        if (e.Exception != null)
        {
            e.ExceptionHandled      = true;
            e.KeepInEditMode        = true;
            ActionProcessor.IsError = true;

            Exception exception = e.Exception;

            while (exception.InnerException != null)
            {
                exception = exception.InnerException;
            }

            ActionProcessor.ReplaceLastAction(exception.Message);
        }
    }
示例#18
0
        public void Requesting_an_action_that_requires_creation_via_the_action_factory_should_succeed()
        {
            var kernel           = new StandardKernel();
            var statePersistence = new TestActionIoC();

            kernel.Bind <TestActionIoC>().ToConstant(statePersistence);

            var requirements = new TestRequirements(kernel);
            var processor    = new ActionProcessor(requirements, Sys);

            processor.Start(false);
            var response = processor.ProcessAction(new ActionRequest <IntegerPayload>(nameof(Add), IntegerPayload.New(0))).Result;

            AwaitAssert(() => {
                Assert.AreEqual(1, (statePersistence?.LastPayload as IntegerPayload)?.Value);
            },
                        TimeSpan.FromSeconds(1));
        }
示例#19
0
        public Player(PlayerModel descriptor, PlayerConnection connection)
        {
            _descriptor        = descriptor;
            _connection        = connection;
            _connection.Player = this;
            this.State         = ActorStates.Idle;

            this.Descriptor.CollisionBounds = new Rect(16, 52, 16, 20);

            this.CollisionBody = new CollisionBody(this);

            _inventory        = new Inventory(this);
            _equipment        = new Equipment(this);
            _networkComponent = new PlayerNetworkComponent(this, connection);
            _packetHandler    = new PlayerPacketHandler(this);
            _actionProcessor  = new ActionProcessor <Player>(this);

            _eventHandlers = new Dictionary <string, List <Action <EventArgs> > >();

            Script script = Engine.Services.Get <ScriptManager>().CreateScript(Constants.FILEPATH_SCRIPTS + "player.py");

            _script = script;

            try
            {
                this.Behavior = script.GetVariable <ActorBehaviorDefinition>("BehaviorDefinition");
            }
            catch { }

            if (this.Behavior == null)
            {
                Engine.Services.Get <Logger>().LogEvent("Error hooking player behavior definition.", LogTypes.ERROR, new Exception("Error hooking player behavior definition."));
            }
            else
            {
                this.Behavior.OnCreated(this);
                this.Behavior.EventOccured += this.BehaviorDescriptor_EventOccured;
            }

            this.Descriptor.Stats.Changed += (o, args) =>
            {
                this.NetworkComponent.SendPlayerStats();
            };
        }
示例#20
0
 public void runCode()
 {
     alpha.GetComponent <Alpha>().currentStack = new List <Action>();
     for (int i = 0; i < 6; i++)
     {
         alpha.GetComponent <Alpha>().currentStack.AddRange(ActionProcessor.processFunction(currentHand[i], 2f / 6));
     }
     alpha.GetComponent <Alpha>().processing = true;
     if (currentDeck.Count == 0)
     {
         currentDeck = new List <FunctionBullet>(inventory);
     }
     for (int i = 0; i < 6; i++)
     {
         int randomCard = (int)UnityEngine.Random.Range(0, currentDeck.Count);
         currentHand[i] = currentDeck[randomCard];
         currentDeck.RemoveAt(randomCard);
     }
 }
示例#21
0
        public void CopySrtmRasterToStoreage(IEnumerable <string> rasterFiles, bool replaceExisted)
        {
            if (rasterFiles == null)
            {
                throw new FileLoadException("Srtm files were not defined");
            }

            var action = new ActionParam <string>()
            {
                ParamName = ActionParamNamesCore.Action,
                Value     = ActionsEnum.demCopyRaster.ToString()
            };

            var prm = new IActionParam[]
            {
                action,
                new ActionParam <IEnumerable <string> >()
                {
                    ParamName = ActionParameters.Files, Value = rasterFiles.ToArray()
                },
                new ActionParam <bool>()
                {
                    ParamName = ActionParameters.ReplaceOnExists, Value = replaceExisted
                },
                new ActionParam <ResterStorageTypesEnum>()
                {
                    ParamName = ActionParameters.ResterStorageType, Value = ResterStorageTypesEnum.Srtm
                },
            };

            var procc = new ActionProcessor(prm);
            var res   = procc.Process <CopyRasterResult>();

            foreach (var line in res.Result.Log)
            {
                log.InfoEx(line);
            }

            if (res.Result.CopoedFiles.Count() != rasterFiles.Count())
            {
                throw new FormatException("Not all SRTM files were coppied");
            }
        }
示例#22
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("You should define at least 3 parameters");
                return;
            }

            var action = new ActionParam <string>()
            {
                ParamName = ActionParamNamesCore.Action,
                Value     = ActionsEnum.bsp.ToString()
            };


            var prm = new List <IActionParam> {
                action,
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.FeatureClass, Value = args[0]
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.ProfileSource, Value = args[1]
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.DataWorkSpace, Value = args[2]
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.OutGraphName, Value = args.Length > 3 ? args[3] : null
                }
            };


            var procc = new ActionProcessor(prm);
            var res   = procc.Process <StringActionResult>();

            Console.WriteLine(res.Result);
        }
        public async Task Test_ActionProcessor_Action_Run()
        {
            const int actionCount          = 8;
            bool      processPackageCalled = false;
            var       appSettings          = new ApplicationSettings();

            Fixture.AddManyTo(appSettings.Actions, actionCount);
            appSettings.Actions.ForEach(action => action.Enabled = false);
            appSettings.Actions[4].Enabled = true;
            appSettings.Actions[4].Type    = DummyActionFactory.ActionType;
            DummyAction.ProcessPackageFunc = (package, packageEvent) =>
            {
                processPackageCalled = true;
                return(true);
            };
            var sut = new ActionProcessor(ServiceProvider, LoggerFactory, appSettings);

            await sut.ExecuteAsync();

            Assert.True(processPackageCalled, "Action never ran ProcessPackage");
        }
示例#24
0
        protected override void Render(HtmlTextWriter writer)
        {
            HorizontalAlign = HorizontalAlign.Center;

            Label label = new Label();

            label.ID  = "lblLastAction";
            BackColor = Color.Gold;
            Style.Add("padding-left", "100px");
            Style.Add("padding-right", "100px");
            Style.Add("padding-top", "2px");
            Style.Add("padding-bottom", "2px");
            Style.Add("margin-top", "12px");

            if (ActionProcessor.IsError)
            {
                BackColor = Color.LightPink;
            }

            if (ActionProcessor.LastAction != null)
            {
                label.Text = ActionProcessor.LastAction;
                Controls.Add(label);

                ProcessLastEntity();

                if (DoReset)
                {
                    ActionProcessor.Clear();
                }

                Style.Remove("display");
            }
            else
            {
                Style.Add("display", "none");
            }

            base.Render(writer);
        }
示例#25
0
        public SlackBot(IEnumerable <IApi> apis, IConfigurationRoot config, string webhook, string channelId, string channelName, string botName, string token, ILog logger, System.Action onClose)
        {
            _logger      = logger;
            _channelId   = channelId;
            _channelName = channelName;
            _botName     = botName;
            _token       = token;
            _webhook     = webhook;
            _start       = DateTime.Now;
            _onClose     = onClose;

            _api = new SlackApi(_webhook);

            _processor = new ActionProcessor((text) =>
            {
                _logger.Debug(text);
//#if DEBUG
//                _api.SendMessage(_channelName, text, Emoji.Ghost, _botName, _logger);
//#endif
            });

            RegisterApi(apis, config);
        }
示例#26
0
        public Client()
        {
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //Code to be inserted in Main(). When server and Client apps will be separated

            Console.WriteLine(
                "Input your query for server.\nIt can consist of commands separated by ',' ' '.' , new line or tab:\n");
            Console.WriteLine("1)Increment");
            Console.WriteLine("2)Decrement");
            Console.WriteLine("3)Flush");
            string Request = Console.ReadLine();
            ActionProcessor ap = new ActionProcessor();
            try
            {
                ap.PerformRequest(Request);
            }
            catch (TooManyActionsException e)
            {
                Console.WriteLine(e.Message);
            }

            //End of Main() code
        }
示例#27
0
        public void Save()
        {
            var serviceWse = ServiceManager.GetService <CommentService>();

            var commentDto = new DataConverter <Comment>().Convert <CommentDTO>(this);

            try
            {
                bool isNew = !commentDto.ID.HasValue || commentDto.ID.Value <= 0;
                if (isNew)
                {
                    serviceWse.Create(commentDto);
                }
                else
                {
                    serviceWse.Update(commentDto);
                }

                var actionProcessor = new ActionProcessor();
                actionProcessor.ProcessAction(isNew ? ActionTypeEnum.Add : ActionTypeEnum.Update, this);
            }
            catch (Exception e)
            {
                log.Debug("Error catched", e);

                if (e.Message.Contains("should not be empty"))
                {
                    ActionProcessor.LastAction = ("The description of comment should not be empty");
                    ActionProcessor.IsError    = true;
                }
                else
                {
                    throw;
                }
            }
        }
示例#28
0
    protected void requestSource_OnSelected(object sender, TpObjectDataSourceEventArgs e)
    {
        if (e.BusinessObject != null)
        {
            IEnumerator enumerator = ((IEnumerable)e.BusinessObject).GetEnumerator();
            if (enumerator.MoveNext())
            {
                var entity = enumerator.Current as Request;

                //If no entity found using current query and user is logged as Anonymous
                if (!entity.ID.HasValue && Requester.IsLoggedAsAnonymous)
                {
                    if (e.SelectParams.Contains("RequestId"))
                    {
                        var requestId = e.SelectParams["RequestId"] as int?;
                        if (requestId != null)
                        {
                            //If such entity exist - redirects to login page for try to access this request
                            if (Hd.Portal.Request.Retrieve(requestId, true) != null)
                            {
                                Globals.IsLogOut = true;
                                FormsAuthentication.RedirectToLoginPage();                                //Globals.CurrentQueryString);
                                return;
                            }
                        }
                    }
                }

                if (IsNotSavedRequest(entity) || !PermissionManager.HaveRightToViewRequest(entity))
                {
                    ActionProcessor.ReplaceLastAction("Request not found");
                    Response.Redirect(Requester.IsLogged ? "~/MyRequests.aspx" : "~/Default.aspx");
                }
            }
        }
    }
示例#29
0
        public ProfileSession GenerateProfile(
            string profileSource,
            IEnumerable <IPolyline> profileLines,
            ProfileSettingsTypeEnum profileSettingsTypeEnum,
            int sessionId, string sessionName)
        {
            string profileSourceName = GdbAccess.Instance.AddProfileLinesToCalculation(profileLines);

            var action = new ActionParam <string>()
            {
                ParamName = ActionParamNamesCore.Action,
                Value     = ActionsEnum.bsp.ToString()
            };


            string sdtnow    = MilSpace.DataAccess.Helper.GetTemporaryNameSuffix();
            var    resuTable = $"{MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection}\\StackProfile{sdtnow}";
            var    profileLineFeatureClass = GdbAccess.Instance.GetProfileLinesFeatureClass(profileSourceName);


            var prm = new List <IActionParam>
            {
                action,
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.FeatureClass, Value = profileLineFeatureClass
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.ProfileSource, Value = profileSource
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.DataWorkSpace, Value = resuTable
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.OutGraphName, Value = ""
                }
            };


            var procc = new ActionProcessor(prm);
            var res   = procc.Process <BoolResult>();

            if (!res.Result)
            {
                if (res.Exception != null)
                {
                    throw res.Exception;
                }
                //TODO: Log error
                throw new Exception(res.ErrorMessage);
            }


            //Take the table and import the data
            ISpatialReference currentSpatialreference = profileLines.First().SpatialReference;

            try
            {
                ITable        profiletable = GdbAccess.Instance.GetProfileTable($"StackProfile{sdtnow}");
                IFeatureClass lines        = GdbAccess.Instance.GetCalcProfileFeatureClass(profileSourceName);

                IQueryFilter queryFilter = new QueryFilter()
                {
                    WhereClause = WhereAllRecords
                };

                ICursor featureCursor = profiletable.Search(queryFilter, true);
                IRow    profileRow;

                int distanceFld = profiletable.FindField(FIRST_DIST_Field);
                int zFld        = profiletable.FindField(FIRST_Z_Field);
                int idFld       = profiletable.FindField(LINE_ID_Field);


                List <ProfileSurface> profileSurfaces = new List <ProfileSurface>();

                ProfileSession session = new ProfileSession()
                {
                    ProfileSurfaces = profileSurfaces.ToArray(),
                    ProfileLines    = GetProfileLines(lines).ToArray(),
                    SessionId       = sessionId,
                    SessionName     = sessionName,
                    DefinitionType  = profileSettingsTypeEnum
                };


                Dictionary <int, List <ProfileSurfacePoint> > surface = new Dictionary <int, List <ProfileSurfacePoint> >();

                int       curLine    = -1;
                IPolyline line       = null;
                IPoint    firstPoint = null;

                while ((profileRow = featureCursor.NextRow()) != null)
                {
                    int lineId = Convert.ToInt32(profileRow.Value[idFld]);

                    var profileLine = session.ProfileLines.FirstOrDefault(l => l.Id == lineId);

                    if (profileLine == null)
                    {
                        throw new MilSpaceProfileLineNotFound(lineId, profileLineFeatureClass);
                    }


                    List <ProfileSurfacePoint> points;
                    if (!surface.ContainsKey(lineId))
                    {
                        points = new List <ProfileSurfacePoint>();
                        surface.Add(lineId, points);
                    }
                    else
                    {
                        points = surface[lineId];
                    }

                    if (curLine != lineId)
                    {
                        curLine    = lineId;
                        line       = lines.GetFeature(profileLine.Id).Shape as IPolyline;
                        firstPoint = line.FromPoint;
                    }

                    var profilePoint = EsriTools.GetPointFromAngelAndDistance(firstPoint, profileLine.Angel, (double)profileRow.Value[distanceFld]);
                    profilePoint.Project(EsriTools.Wgs84Spatialreference);

                    points.Add(new ProfileSurfacePoint
                    {
                        Distance = (double)profileRow.Value[distanceFld],
                        Z        = (double)profileRow.Value[zFld],
                        X        = profilePoint.X,
                        Y        = profilePoint.Y
                    });
                }

                //TODO: Clean memo using Marhsaling IRow

                session.ProfileSurfaces = surface.Select(r => new ProfileSurface
                {
                    LineId = r.Key,
                    ProfileSurfacePoints = r.Value.ToArray()
                }
                                                         ).ToArray();

                //Write to DB
                if (!MilSpaceProfileFacade.SaveProfileSession(session))
                {
                    return(null);
                }


                return(session);
            }
            catch (MilSpaceDataException ex)
            {
                //TODO: Log error
                throw ex;
            }
            catch (Exception ex)
            {
                //TODO: Log error
                throw ex;
            }
        }
示例#30
0
        public void GenerateProfile(string profileSource,
                                    IEnumerable <ILine> profileLines)
        {
            string profileSourceName = GdbAccess.Instance.AddProfileLinesToCalculation(profileLines);

            var action = new ActionParam <string>()
            {
                ParamName = ActionParamNamesCore.Action,
                Value     = ActionsEnum.bsp.ToString()
            };


            string sdtnow    = MilSpace.DataAccess.Helper.GetTemporaryNameSuffix();
            var    resuTable = $"{MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection}\\StackProfile{sdtnow}";
            var    profileLineFeatureClass = GdbAccess.Instance.GetProfileLinesFeatureClass(profileSourceName);


            var prm = new List <IActionParam>
            {
                action,
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.FeatureClass, Value = profileLineFeatureClass
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.ProfileSource, Value = profileSource
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.DataWorkSpace, Value = resuTable
                },
                new ActionParam <string>()
                {
                    ParamName = ActionParameters.OutGraphName, Value = ""
                }
            };


            var procc = new ActionProcessor(prm);
            var res   = procc.Process <BoolResult>();

            if (!res.Result)
            {
                if (res.Exception != null)
                {
                    throw res.Exception;
                }
                //TODO: Log error
                throw new Exception(res.ErrorMessage);
            }

            //Teke the table and import the data


            try
            {
                ITable profiletable = GdbAccess.Instance.GetProfileTable($"StackProfile{sdtnow}");

                IQueryFilter queryFilter = new QueryFilter()
                {
                    WhereClause = "OBJECTID > 0"
                };

                ICursor featureCursor = profiletable.Search(queryFilter, true);
                IRow    profileRow;

                int distanceFld = profiletable.FindField(FIRST_DIST_Field);
                int zFld        = profiletable.FindField(FIRST_Z_Field);
                int idFld       = profiletable.FindField(LINE_ID_Field);


                List <ProfileSurface> profileSurfaces = new List <ProfileSurface>();

                ProfileSession session = new ProfileSession()
                {
                    ProfileSurface = profileSurfaces.ToArray()
                };


                Dictionary <int, List <ProfileSurfacePoint> > surface = new Dictionary <int, List <ProfileSurfacePoint> >();


                while ((profileRow = featureCursor.NextRow()) != null)
                {
                    int lineId = Convert.ToInt32(profileRow.Value[idFld]);
                    List <ProfileSurfacePoint> points;
                    if (!surface.ContainsKey(lineId))
                    {
                        points = new List <ProfileSurfacePoint>();
                        surface.Add(lineId, points);
                    }
                    else
                    {
                        points = surface[lineId];
                    }

                    points.Add(new ProfileSurfacePoint
                    {
                        Distance = (double)profileRow.Value[distanceFld],
                        Z        = (double)profileRow.Value[zFld]
                    });
                }

                //TODO: Clean memo using Marhsaling IRow

                session.ProfileSurface = surface.Select(r => new ProfileSurface

                {
                    LineId = r.Key,
                    ProfileSurfacePoints = r.Value.ToArray()
                }
                                                        ).ToArray();


                XmlSerializer serializer = new XmlSerializer(typeof(ProfileSession));

                TextWriter writer = new StreamWriter(@"E:\SourceCode\Copoka\Tmp\temp.xml");

                serializer.Serialize(writer, session);
                writer.Close();
                writer.Dispose();
            }
            catch (Exception ex)
            {
                //TODO: Log error
                throw ex;
            }
        }
示例#31
0
        public void TestProcessZipActionForContainer()
        {
            IPolicyCache policyCache = TestHelpers.CreatePolicyCache(new string[] { m_testPath + "Zip Policy Set.policy" });
            Assert.IsNotNull(policyCache);
            Assert.AreEqual(1, policyCache.PolicySets.Count);

            PolicyEngineCache policyEngineCache = new PolicyEngineCache(policyCache, null);
            ConditionProcessor conditionProcessor = new ConditionProcessor(policyEngineCache, null);

            List<string> attachments = new List<string>();
            attachments.Add(Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\TestDocuments\TestProfanity.doc"));
            attachments.Add(Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\projects\Hygiene\src\TestDocuments\Dirty.doc"));

            IUniversalRequestObject uro = TestHelpers.CreateSmtpUro(attachments);

            // PROCESS CONDITIONS
            IContainer container;
            PolicyResponseObject pro = conditionProcessor.Process(RunAt.Client, uro, out container);
            Assert.IsNotNull(pro);

            // PROCESS ROUTING
            RoutingProcessor routingProcessor = new RoutingProcessor(policyEngineCache);
            Assert.IsNotNull(routingProcessor.Process(pro));

            Assert.AreEqual(3, pro.ContentCollection.Count);
            Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
            Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
            Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[2].Type);

            // PROCESS ACTIONS
            ActionProcessor actionProcessor = new ActionProcessor(policyCache, policyEngineCache);
            actionProcessor.ProcessActions(pro);

            ContentItem contentItem = pro.ContentCollection[0] as ContentItem;
            Assert.IsNotNull(contentItem);
            Collection<IPolicyResponseAction> actionCollection = contentItem.PolicySetCollection[0].PolicyReportCollection[0].ActionCollection;
            // Actions not longer re-routed in action processor. Actions will be re-routed in action executor.
            Assert.IsNull(actionCollection);
            //Assert.IsNotNull(actionCollection);
            //Assert.AreEqual(1, actionCollection.Count);

            //contentItem = pro.ContentCollection[1] as ContentItem;
            //Assert.IsNotNull(contentItem);
            //actionCollection = contentItem.PolicySetCollection[0].PolicyReportCollection[0].ActionCollection;
            //Assert.IsNotNull(actionCollection);
            //Assert.AreEqual(1, actionCollection.Count);

            //contentItem = pro.ContentCollection[2] as ContentItem;
            //Assert.IsNotNull(contentItem);
            //actionCollection = contentItem.PolicySetCollection[0].PolicyReportCollection[0].ActionCollection;
            //Assert.IsNotNull(actionCollection);
            //Assert.AreEqual(1, actionCollection.Count);
        }
示例#32
0
		public void Test_06_ExecuteAction_SMTP_ZipPolicy_HasZip()
		{
			IPolicyCache policyCache = TestHelpers.CreatePolicyCache(
				new string[] { Path.Combine(POLICY_FOLDER, "TestActionProcessor - Zip Policy Set.policy") });

			Assert.IsNotNull(policyCache);
			Assert.AreEqual(1, policyCache.PolicySets.Count);

			PolicyEngineCache policyEngineCache = new PolicyEngineCache(policyCache, null);
			ConditionProcessor conditionProcessor = new ConditionProcessor(policyEngineCache, null);

			List<string> attachments = new List<string>();
			attachments.Add(Path.Combine(TEST_FOLDER, "TestProfanity.doc"));
			attachments.Add(Path.Combine(TEST_FOLDER, "I am a dirty zip.zip"));

			IUniversalRequestObject uro = TestHelpers.CreateSmtpUro(attachments);

			// PROCESS CONDITIONS
			IContainer container;
			PolicyResponseObject pro = conditionProcessor.Process(RunAt.Client, uro, out container);
			Assert.IsNotNull(pro);

			// PROCESS ROUTING
			RoutingProcessor routingProcessor = new RoutingProcessor(policyEngineCache);
			Assert.IsNotNull(routingProcessor.Process(pro));

			Assert.AreEqual(4, pro.ContentCollection.Count);
			Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
			Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
			Assert.AreEqual(FileType.ZIP.ToString(), pro.ContentCollection[2].Type);
			Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[3].Type);

			Assert.AreEqual(2, pro.UniversalRequestObject.Attachments.Count);
			Assert.AreEqual("TestProfanity.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[0].Name));
			Assert.AreEqual("I am a dirty zip.zip", Path.GetFileName(pro.UniversalRequestObject.Attachments[1].Name));

			// PROCESS ACTIONS
			ActionProcessor actionProcessor = new ActionProcessor(policyCache, policyEngineCache);
			actionProcessor.ProcessActions(pro);
			ActionUtils.PopulateResolvedActionCollection(pro);

			// EXECUTE ACTIONS
			ActionExecuter executer = new ActionExecuter(null);
			IUniversalRequestObject outputUro = executer.ExecuteActions(pro, ref container);

			Assert.AreEqual(4, pro.ContentCollection.Count);
			Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
			Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
			Assert.AreEqual(FileType.ZIP.ToString(), pro.ContentCollection[2].Type);
			Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[3].Type);

			Assert.AreEqual(2, outputUro.Attachments.Count);
			Assert.AreEqual("TestProfanity.zip", outputUro.Attachments[0].Name);
			Assert.AreEqual("I am a dirty zip.zip", outputUro.Attachments[1].Name);
		}
示例#33
0
		public void Test_10_ExecuteAction_SMTP_Default_Policy_And_ZIP_Policy()
		{
			IPolicyCache policyCache = TestHelpers.CreatePolicyCache(new string[] { 
				Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\Projects\Hygiene\Policies\p5default.policy"),
				Path.Combine(POLICY_FOLDER, "TestActionProcessor - Zip Policy Set.policy") });

			Assert.IsNotNull(policyCache);
			Assert.AreEqual(2, policyCache.PolicySets.Count);

			PolicyEngineCache policyEngineCache = new PolicyEngineCache(policyCache, null);
			ConditionProcessor conditionProcessor = new ConditionProcessor(policyEngineCache, null);

			List<string> attachments = new List<string>();
			attachments.Add(Path.Combine(TEST_FOLDER, "TestProfanity.doc"));
			attachments.Add(Path.Combine(TEST_FOLDER, "Dirty.doc"));
			attachments.Add(Path.Combine(TEST_FOLDER, "TestDoc.ppt"));

			IUniversalRequestObject uro = TestHelpers.CreateSmtpUro(attachments);

			// PROCESS CONDITIONS
			IContainer container;
			PolicyResponseObject pro = conditionProcessor.Process(RunAt.Client, uro, out container);
			Assert.IsNotNull(pro);

			// PROCESS ROUTING
			RoutingProcessor routingProcessor = new RoutingProcessor(policyEngineCache);
			Assert.IsNotNull(routingProcessor.Process(pro));

			Assert.AreEqual(4, pro.ContentCollection.Count);
			Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
			Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
			Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[2].Type);
			Assert.AreEqual(FileType.PowerPoint.ToString(), pro.ContentCollection[3].Type);

			Assert.AreEqual(3, pro.UniversalRequestObject.Attachments.Count);
			Assert.AreEqual("TestProfanity.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[0].Name));
			Assert.AreEqual("Dirty.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[1].Name));
			Assert.AreEqual("TestDoc.ppt", Path.GetFileName(pro.UniversalRequestObject.Attachments[2].Name));

			// PROCESS ACTIONS
			ActionProcessor actionProcessor = new ActionProcessor(policyCache, policyEngineCache);
			actionProcessor.ProcessActions(pro);
			ActionUtils.PopulateResolvedActionCollection(pro);

			// EXECUTE ACTIONS
			ActionExecuter executer = new ActionExecuter(null);
			IUniversalRequestObject outputUro = executer.ExecuteActions(pro, ref container);

			//Assert.AreEqual(4, pro.ContentCollection.Count);
			//Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
			//Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
			//Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[2].Type);
			//Assert.AreEqual(FileType.PowerPoint.ToString(), pro.ContentCollection[3].Type);

			Assert.AreEqual(2, outputUro.Attachments.Count);
			Assert.AreEqual("TestDoc.ppt", outputUro.Attachments[0].Name);
			Assert.AreEqual("attachments.zip", outputUro.Attachments[1].Name);

			File outputFile = new File(outputUro.Attachments[1].Data, outputUro.Attachments[0].Name);
			Assert.IsNotNull(outputFile);
			outputFile.ExpandContainer(outputFile.Password);
			Assert.AreEqual(2, outputFile.Files.Count);
			Assert.AreEqual("TestProfanity.doc", outputFile.Files[0].DisplayName);
			Assert.AreEqual("Dirty.doc", outputFile.Files[1].DisplayName);
		}
示例#34
0
		public void Test_05_ExecuteAction_SMTP_ZipPolicy()
		{
			IPolicyCache policyCache = TestHelpers.CreatePolicyCache(
				new string[] { Path.Combine(POLICY_FOLDER, "TestActionProcessor - Zip Policy Set.policy") });

			Assert.IsNotNull(policyCache);
			Assert.AreEqual(1, policyCache.PolicySets.Count);

			PolicyEngineCache policyEngineCache = new PolicyEngineCache(policyCache, null);
			ConditionProcessor conditionProcessor = new ConditionProcessor(policyEngineCache, null);

			List<string> attachments = new List<string>();
			using (LocalCopyOfFileManager lcfm = new LocalCopyOfFileManager())
			{
				string folderName = lcfm.ManagedFolder;

				string fileName = Path.Combine(folderName, "TestProfanity.doc");
				System.IO.File.Copy(Path.Combine(TEST_FOLDER, "TestProfanity.doc"), fileName);
				attachments.Add(fileName);
				fileName = Path.Combine(folderName, "Dirty.doc");
				System.IO.File.Copy(Path.Combine(TEST_FOLDER, "Dirty.doc"), fileName);
				attachments.Add(fileName);
				fileName = Path.Combine(folderName, "TestDoc.ppt");
				System.IO.File.Copy(Path.Combine(TEST_FOLDER, "TestDoc.ppt"), fileName);
				attachments.Add(fileName);

				IUniversalRequestObject uro = TestHelpers.CreateSmtpUro(attachments);

				// PROCESS CONDITIONS
				IContainer container;
				PolicyResponseObject pro = conditionProcessor.Process(RunAt.Client, uro, out container);
				Assert.IsNotNull(pro);

				// PROCESS ROUTING
				RoutingProcessor routingProcessor = new RoutingProcessor(policyEngineCache);
				Assert.IsNotNull(routingProcessor.Process(pro));

				Assert.AreEqual(4, pro.ContentCollection.Count);
				Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
				Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
				Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[2].Type);
				Assert.AreEqual(FileType.PowerPoint.ToString(), pro.ContentCollection[3].Type);

				Assert.AreEqual(3, pro.UniversalRequestObject.Attachments.Count);
				Assert.AreEqual("TestProfanity.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[0].Name));
				Assert.AreEqual("Dirty.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[1].Name));
				Assert.AreEqual("TestDoc.ppt", Path.GetFileName(pro.UniversalRequestObject.Attachments[2].Name));

				// PROCESS ACTIONS
				ActionProcessor actionProcessor = new ActionProcessor(policyCache, policyEngineCache);
				actionProcessor.ProcessActions(pro);

				ActionUtils.PopulateResolvedActionCollection(pro);

				// EXECUTE ACTIONS
				ActionExecuter executer = new ActionExecuter(null);
				executer.ExecuteActions(pro, ref container);

				Assert.AreEqual(4, pro.ContentCollection.Count);
				Assert.AreEqual(FileType.Email.ToString(), pro.ContentCollection[0].Type);
				Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[1].Type);
				Assert.AreEqual(FileType.WordDocument.ToString(), pro.ContentCollection[2].Type);
				Assert.AreEqual(FileType.PowerPoint.ToString(), pro.ContentCollection[3].Type);

				Assert.AreEqual(3, pro.UniversalRequestObject.Attachments.Count);
				Assert.AreEqual("TestProfanity.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[0].Name));
				Assert.AreEqual("Dirty.doc", Path.GetFileName(pro.UniversalRequestObject.Attachments[1].Name));
				Assert.AreEqual("TestDoc.ppt", Path.GetFileName(pro.UniversalRequestObject.Attachments[2].Name));
			}
		}
示例#35
0
        public void IsIQueueSetup()
        {
            var ap = new ActionProcessor <object>(async(obj) => { return(await Task.FromResult <bool>(true)); });

            Assert.IsNotNull(ap as IProcessor <object>);
        }