Exemple #1
0
        /// <summary>
        /// Fills the device topic dictionary.
        /// </summary>
        private void FillDeviceTopics()
        {
            // topic example:
            // Communicator/line001/device001/Sin
            foreach (ILineContext lineContext in CommContext.GetCommLines())
            {
                string lineTopic = dsOptions.PublishOptions.RootTopic +
                                   CommUtils.GetLineLogFileName(lineContext.CommLineNum, "") + "/";

                IEnumerable <DeviceLogic> devices = deviceFilter == null
                    ? lineContext.SelectDevices()
                    : lineContext.SelectDevices(d => deviceFilter.Contains(d.DeviceNum));

                foreach (DeviceLogic deviceLogic in devices)
                {
                    string       deviceTopic  = lineTopic + CommUtils.GetDeviceLogFileName(deviceLogic.DeviceNum, "") + "/";
                    DeviceTopics deviceTopics = new();

                    foreach (DeviceTag deviceTag in deviceLogic.DeviceTags)
                    {
                        if (!string.IsNullOrEmpty(deviceTag.Code))
                        {
                            deviceTopics[deviceTag.Code] = deviceTopic + deviceTag.Code;
                        }
                    }

                    if (deviceTopics.Count > 0)
                    {
                        topicByDevice[deviceLogic.DeviceNum] = deviceTopics;
                    }
                }
            }
        }
Exemple #2
0
                #pragma warning restore CA1506

        /// <inheritdoc />
        public async Task <ISessionController> Reattach(ReattachInformation reattachInformation, CancellationToken cancellationToken)
        {
            if (reattachInformation == null)
            {
                throw new ArgumentNullException(nameof(reattachInformation));
            }

            SessionController result    = null;
            var basePath                = reattachInformation.IsPrimary ? reattachInformation.Dmb.PrimaryDirectory : reattachInformation.Dmb.SecondaryDirectory;
            var chatJsonTrackingContext = await chat.TrackJsons(basePath, reattachInformation.ChatChannelsJson, reattachInformation.ChatCommandsJson, cancellationToken).ConfigureAwait(false);

            try
            {
                var byondLock = await byond.UseExecutables(Version.Parse(reattachInformation.Dmb.CompileJob.ByondVersion), cancellationToken).ConfigureAwait(false);

                try
                {
                    var context = new CommContext(ioManager, loggerFactory.CreateLogger <CommContext>(), basePath, reattachInformation.ServerCommandsJson);
                    try
                    {
                        var process = processExecutor.GetProcess(reattachInformation.ProcessId);

                        if (process != null)
                        {
                            try
                            {
                                networkPromptReaper.RegisterProcess(process);
                                result = new SessionController(reattachInformation, process, byondLock, byondTopicSender, chatJsonTrackingContext, context, chat, loggerFactory.CreateLogger <SessionController>(), null, null);

                                process   = null;
                                context   = null;
                                byondLock = null;
                                chatJsonTrackingContext = null;
                            }
                            finally
                            {
                                process?.Dispose();
                            }
                        }
                    }
                    finally
                    {
                        context?.Dispose();
                    }
                }
                finally
                {
                    byondLock?.Dispose();
                }
            }
            finally
            {
                chatJsonTrackingContext?.Dispose();
            }

            return(result);
        }
        /// <summary>
        /// Sets the appropriate server file path for the connection
        /// and initializes the connection uri.
        /// </summary>
        public override void Execute()
        {
            bool IsConnected = false;

            Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Entered.", PayflowConstants.SEVERITY_DEBUG);
            if (!InProgress)
            {
                return;
            }
            try
            {
                Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Initializing Connection.", PayflowConstants.SEVERITY_INFO);
                //Begin Payflow Timeout Check Point 2
                long TimeRemainingMsec;
                bool TimedOut = PayflowUtility.IsTimedOut(mConnection.TimeOut, mConnection.StartTime, out TimeRemainingMsec);
                if (TimedOut)
                {
                    String      AddlMessage = "Input timeout value in millisec : " + Connection.TimeOut.ToString();
                    ErrorObject Err         = PayflowUtility.PopulateCommError(PayflowConstants.E_TIMEOUT_WAIT_RESP, null, PayflowConstants.SEVERITY_FATAL, IsXmlPayRequest, AddlMessage);
                    if (!CommContext.IsCommunicationErrorContained(Err))
                    {
                        CommContext.AddError(Err);
                    }
                }
                else
                {
                    mConnection.TimeOut = TimeRemainingMsec;
                }
                //End Payflow Timeout Check Point 2
                IsConnected = mConnection.ConnectToServer();
            }
            catch (Exception Ex)
            {
                Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Error occurred While Initializing Connection.", PayflowConstants.SEVERITY_ERROR);
                Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Exception " + Ex.ToString(), PayflowConstants.SEVERITY_ERROR);
                IsConnected = false;
            }
            //catch
            //{
            //    IsConnected = false;
            //}
            finally
            {
                if (IsConnected)
                {
                    Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Connection Initialization =  Success", PayflowConstants.SEVERITY_INFO);
                    SetStateSuccess();
                }
                else
                {
                    Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Initialized Connection = Failure", PayflowConstants.SEVERITY_INFO);
                    SetStateFail();
                }
            }

            Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Exiting.", PayflowConstants.SEVERITY_DEBUG);
        }
Exemple #4
0
        public void CommandTest()
        {
            var context = new CommContext("AA 0A $1 0B $2 0C $3 BB");

            context.Command.Length.Should().Be(2 + 2 + 2 + 2 + 4 + 2 + 6 + 2);
            var cmd = context.Command.Build(11, 222, 333);

            cmd.Should().Be("AA0A 0B 0B 00DE 0C 00014D BB".Replace(" ", ""));
        }
        public override async Task <bool> SendAsync(CommContext context)
        {
            var cmdStr = context.Command.Build();

            await _client.SendAsync(cmdStr).ConfigureAwait(false);

            context.SendTime = DateTime.Now;
            _history.OnNext(context);

            return(await Task.FromResult(true).ConfigureAwait(false));
        }
        public override async Task <bool> SendAsync(CommContext context)
        {
            var cmdStr = context.Command.Build();
            var bs     = cmdStr.HexToByte();

            context.SendTime = DateTime.Now;
            _history.OnNext(context);

            _sp.Write(bs, 0, bs.Length);
            await Task.Delay(50);

            return(true);
        }
Exemple #7
0
        public override void Handle(CommContext context)
        {
            IBot bot = context.LockBot(BotId);

            if (bot != null)
            {
                context.Send(new BotLocked {
                    BotId = BotId
                });
            }
            else
            {
                context.Send(new BotLockFailed {
                    BotId = BotId
                });
            }
        }
Exemple #8
0
        public async Task <InfoModel <OutPutContentInfoItem> > GetInfo([FromForm] string Id)
        {
            var T = await ContentContext.GetInfo(HttpContext.RequestServices, Id);

            T.Ver();
            var list = await CommContext.GetListPageWithContentID(
                HttpContext.RequestServices,
                new PageInfo(0, 1000),
                Id
                );

            return(new InfoModel <OutPutContentInfoItem>()
            {
                Data = new OutPutContentInfoItem()
                {
                    Content = T.GetEntity().Content.HtmlDecode(),
                    ContentId = T.GetKey(),
                    CreateTiem = T.GetEntity().CreateDate.ToString("yyyy-MM-dd hh:mm:ss"),
                    HeadImage = new TempFileInfo()
                    {
                        ServerDirPath = T.GetDownFileDir(),
                        ServerFileName = T.GetEntity().Image,
                    },
                    Title = T.GetEntity().Title,
                    Status = T.GetEntity().Status,
                    Introduce = T.GetEntity().Introduce,
                    ExamineList = HttpContext.RequestServices.GetDataTypeForConstant <ContentStatusType>().DataType.ConvertAll(T =>
                    {
                        return new TypeForName <int, string>()
                        {
                            Id = T.Id,
                            Name = T.Value
                        };
                    }),
                    CommList = (await Task.WhenAll(list.ConvertAll(async K => {
                        return new Comminfo()
                        {
                            Content = K.GetEntity().Content,
                            DateTime = K.GetEntity().CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                            Name = await K.GetCreateName()
                        };
                    }))).ToList()
                }
            });
        }
Exemple #9
0
        public async Task <InfoModel <bool> > EditComm([FromBody] InputComm model)
        {
            var info = await CommContext.Sub(
                HttpContext.RequestServices,
                "",
                model.ContentId,
                model.Content,
                DateTime.Now,
                (await UserInfoForLogin).GetKey(),
                HttpContext.Connection.RemoteIpAddress.ToString(),
                DateTime.Now
                );

            return(new InfoModel <bool>()
            {
                Data = true
            });
        }
Exemple #10
0
        public void ResponseTest()
        {
            var ctx1      = new CommContext("AA0A$10B$20C$3BB", "AA0A$10B$20C$3BB", 1000);
            var intParams = new[] { 11, 222, 333 };

            ctx1.Response.GetIntValues(ctx1.Command.Build(intParams)).Should().BeEquivalentTo(intParams);
            ctx1.Response.GetStrValues(ctx1.Command.Build(intParams)).Should().BeEquivalentTo("0B", "00DE", "00014D");

            ctx1.Response.Value.Should().BeNull();
            ctx1.Response.Value = ctx1.Command.Build(intParams);
            ctx1.Response.GetIntValues().Should().BeEquivalentTo(intParams);
            ctx1.Response.GetStrValues().Should().BeEquivalentTo("0B", "00DE", "00014D");

            var ctx2 = new CommContext("AA0A$10B$20C$3BB", "AA0A$10B$20C$3f", 1000);

            Assert.Throws(typeof(FormatException), () => ctx2.Response.GetStrValues(ctx2.Command.Build(intParams)));
            var values = ctx2.Response.GetStrValues(ctx2.Command.Build(intParams), false);

            values.Should().BeEquivalentTo("0B", "00DE", "00014D");
        }
        static void Main(string[] args)
        {
            CommContext cmt    = new CommContext();
            IntPtr      cmtPtr = Marshal.AllocHGlobal(Marshal.SizeOf(cmt));

            Marshal.StructureToPtr(cmt, cmtPtr, true);
            string host = "LocalHost";

            byte[] hostBytes = Encoding.UTF8.GetBytes(host + "\0");
            IntPtr hostPtr   = Marshal.AllocHGlobal(hostBytes.Length);

            Marshal.Copy(hostBytes, 0, hostPtr, hostBytes.Length);
            string username = "******";

            byte[] usernameBytes = Encoding.UTF8.GetBytes(username + "\0");
            IntPtr usernamePtr   = Marshal.AllocHGlobal(usernameBytes.Length);

            Marshal.Copy(usernameBytes, 0, usernamePtr, usernameBytes.Length);
            string password = "******";

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password + "\0");
            IntPtr passwordPtr   = Marshal.AllocHGlobal(passwordBytes.Length);

            Marshal.Copy(passwordBytes, 0, passwordPtr, passwordBytes.Length);
            string shell_cmd = "shell_cmd";

            byte[] shell_cmdBytes = Encoding.UTF8.GetBytes(shell_cmd + "\0");
            IntPtr shell_cmdPtr   = Marshal.AllocHGlobal(shell_cmdBytes.Length);

            Marshal.Copy(shell_cmdBytes, 0, shell_cmdPtr, shell_cmdBytes.Length);
            const int BUF_LEN   = 256;
            IntPtr    errmsgPtr = new IntPtr(BUF_LEN);
            int       bLen      = BUF_LEN;
            WSAData   data      = new WSAData();

            WSAStartup(0x201, out data);
            IntPtr sio     = socket(ADDRESS_FAMILIES_INT.AF_INET, SOCKET_TYPE_INT.SOCK_STREAM, PROTOCOL_INT.IPPROTO_TCP);
            IntPtr sErr    = socket(ADDRESS_FAMILIES_INT.AF_INET, SOCKET_TYPE_INT.SOCK_STREAM, PROTOCOL_INT.IPPROTO_TCP);
            int    results = WaitForLogon(cmtPtr, hostPtr, usernamePtr, passwordPtr, shell_cmdPtr, errmsgPtr, bLen, sio, sErr);
            string error   = Marshal.PtrToStringAuto(errmsgPtr);
        }
Exemple #12
0
        /// <summary>
        ///     Validates Request Id.
        /// </summary>
        /// <returns>True if valid, false otherwise.</returns>
        private bool ValidateRequestId()
        {
            var retValue = false;

            if (!HaveRequestId)
            {
                var err = PayflowUtility.PopulateCommError(PayflowConstants.EMissingRequestId, null,
                                                           PayflowConstants.SeverityFatal, IsXmlPayRequest,
                                                           null);
                if (!CommContext.IsCommunicationErrorContained(err))
                {
                    CommContext.AddError(err);
                }
            }
            else
            {
                retValue = true;
            }

            return(retValue);
        }
Exemple #13
0
        /// <summary>
        /// Validates Request Id.
        /// </summary>
        /// <returns>True if valid, false otherwise.</returns>
        private bool ValidateRequestId()
        {
            bool RetValue = false;

            if (!HaveRequestId)
            {
                ErrorObject Err = PayflowUtility.PopulateCommError(PayflowConstants.E_MISSING_REQUEST_ID, null,
                                                                   PayflowConstants.SEVERITY_FATAL, IsXmlPayRequest,
                                                                   null);
                if (!mContext.IsCommunicationErrorContained(Err))
                {
                    CommContext.AddError(Err);
                }
            }
            else
            {
                RetValue = true;
            }

            return(RetValue);
        }
Exemple #14
0
        /// <summary>
        /// Handles a message received event.
        /// </summary>
        private void MqttClient_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                string topic   = e.ApplicationMessage.Topic;
                string payload = e.ApplicationMessage.ConvertPayloadToString();

                dsLog.WriteAction("{0} {1} = {2}", CommPhrases.ReceiveNotation,
                                  topic, payload.GetPreview(MqttUtils.MessagePreviewLength));

                // parse and pass command
                if (topic == commandTopic)
                {
                    ReceivedCommand command = JsonSerializer.Deserialize <ReceivedCommand>(payload);
                    CommContext.SendCommand(new TeleCommand
                    {
                        CommandID    = ScadaUtils.GenerateUniqueID(),
                        CreationTime = DateTime.UtcNow,
                        DeviceNum    = command.DeviceNum,
                        CmdCode      = command.CmdCode,
                        CmdVal       = command.CmdVal,
                        CmdData      = ScadaUtils.HexToBytes(command.CmdData, false, true)
                    }, DriverUtils.DriverCode);
                }
            }
            catch (JsonException)
            {
                dsLog.WriteError(Locale.IsRussian ?
                                 "Ошибка при получении команды из JSON." :
                                 "Error parsing command from JSON.");
            }
            catch (Exception ex)
            {
                dsLog.WriteError(ex, Locale.IsRussian ?
                                 "Ошибка при обработке полученного сообщения. Топик: {0}" :
                                 "Error handling the received message. Topic: {0}", e?.ApplicationMessage?.Topic);
            }
        }
Exemple #15
0
        /// <summary>
        /// Receives telecontrol commands from the server.
        /// </summary>
        private void ReceiveCommands()
        {
            try
            {
                int cmdCnt = 0;

                while (scadaClient.GetCommand() is TeleCommand cmd)
                {
                    CommContext.SendCommand(cmd, Code);

                    if (++cmdCnt == MaxCommandCount)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                log.WriteError(ex, CommPhrases.DataSourceMessage, Code, Locale.IsRussian ?
                               "Ошибка при приёме команд ТУ" :
                               "Error receiving telecontrol commands");
            }
        }
Exemple #16
0
        public async Task <bool> SendAsync(CommContext context)
        {
            context.SendTime = DateTime.Now;
            _history.OnNext(context);
            _sendIndex++;

            if (_lostInterval > 0 && _sendIndex % _lostInterval == 0) //模拟失败
            {
                return(false);
            }

            await Task.Delay(_sendDelayMs);

            if (_fakeData)
            {
                _received.OnNext(context.Response.Template.SimulateResponse().HexToByte()); //根据响应模板生成
            }
            else
            {
                _received.OnNext(context.Command.Build().HexToByte()); //发什么回什么
            }
            return(true);
        }
Exemple #17
0
 public virtual Task <bool> SendAsync(CommContext context)
 {
     throw new NotImplementedException();
 }
Exemple #18
0
        /// <summary>
        ///     Execute function.
        /// </summary>
        public override async Task ExecuteAsync()
        {
            var isReceiveSuccess = false;

            Logger.Instance.Log("PayPal.Payments.Communication.ReceiveState.Execute(): Entered.",
                                PayflowConstants.SeverityDebug);
            if (!InProgress)
            {
                return;
            }
            try
            {
                //Begin Payflow Timeout Check Point 4
                long timeRemainingMsec;
                if (PayflowUtility.IsTimedOut(Connection.TimeOut, Connection.StartTime, out timeRemainingMsec))
                {
                    var addlMessage = "Input timeout value in millisec = " + Connection.TimeOut;
                    var err         = PayflowUtility.PopulateCommError(PayflowConstants.ETimeoutWaitResp, null,
                                                                       PayflowConstants.SeverityFatal, IsXmlPayRequest, addlMessage);
                    if (!CommContext.IsCommunicationErrorContained(err))
                    {
                        CommContext.AddError(err);
                    }
                }
                else
                {
                    Connection.TimeOut = timeRemainingMsec;
                }

                //End Payflow Timeout Check Point 4
                var responseValue = await Connection.ReceiveResponseAsync();

                isReceiveSuccess = SetReceiveResponse(responseValue);
            }
            catch (Exception ex)
            {
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.ReceiveState.Execute(): Error occurred While Receiving Response.",
                    PayflowConstants.SeverityError);
                Logger.Instance.Log("PayPal.Payments.Communication.ReceiveState.Execute(): Exception " + ex,
                                    PayflowConstants.SeverityError);
                isReceiveSuccess = false;
            }
            //catch
            //{
            //    IsReceiveSuccess = false;
            //}
            finally
            {
                if (isReceiveSuccess)
                {
                    Logger.Instance.Log(
                        "PayPal.Payments.Communication.ReceiveState.Execute(): Receive Response = Success ",
                        PayflowConstants.SeverityInfo);
                    SetStateSuccess();
                }
                else
                {
                    Logger.Instance.Log(
                        "PayPal.Payments.Communication.ReceiveState.Execute(): Receive Response = Failure ",
                        PayflowConstants.SeverityInfo);
                    SetStateFail();
                }
            }

            Logger.Instance.Log("PayPal.Payments.Communication.ReceiveState.Execute(): Exiting.",
                                PayflowConstants.SeverityDebug);
        }
Exemple #19
0
 public override Task <bool> SendAsync(CommContext cmd)
 {
     return(Task.FromResult(false));
 }
Exemple #20
0
 public LinkRepository(CommContext ctx)
 {
     this.db = ctx;
 }
        /// <summary>
        ///     Sets the appropriate server file path for the connection
        ///     and initializes the connection uri.
        /// </summary>
        public override Task ExecuteAsync()
        {
            var isConnected = false;

            Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Entered.",
                                PayflowConstants.SeverityDebug);
            if (!InProgress)
            {
                return(Task.CompletedTask);
            }
            try
            {
                Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Initializing Connection.",
                                    PayflowConstants.SeverityInfo);
                //Begin Payflow Timeout Check Point 2
                long timeRemainingMsec;
                var  timedOut =
                    PayflowUtility.IsTimedOut(Connection.TimeOut, Connection.StartTime, out timeRemainingMsec);
                if (timedOut)
                {
                    var addlMessage = "Input timeout value in millisec : " + Connection.TimeOut;
                    var err         = PayflowUtility.PopulateCommError(PayflowConstants.ETimeoutWaitResp, null,
                                                                       PayflowConstants.SeverityFatal, IsXmlPayRequest, addlMessage);
                    if (!CommContext.IsCommunicationErrorContained(err))
                    {
                        CommContext.AddError(err);
                    }
                }
                else
                {
                    Connection.TimeOut = timeRemainingMsec;
                }

                //End Payflow Timeout Check Point 2
                isConnected = Connection.ConnectToServer();
            }
            catch (Exception ex)
            {
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.InitState.Execute(): Error occurred While Initializing Connection.",
                    PayflowConstants.SeverityError);
                Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Exception " + ex,
                                    PayflowConstants.SeverityError);
                isConnected = false;
            }
            //catch
            //{
            //    IsConnected = false;
            //}
            finally
            {
                if (isConnected)
                {
                    Logger.Instance.Log(
                        "PayPal.Payments.Communication.InitState.Execute(): Connection Initialization =  Success",
                        PayflowConstants.SeverityInfo);
                    SetStateSuccess();
                }
                else
                {
                    Logger.Instance.Log(
                        "PayPal.Payments.Communication.InitState.Execute(): Initialized Connection = Failure",
                        PayflowConstants.SeverityInfo);
                    SetStateFail();
                }
            }

            Logger.Instance.Log("PayPal.Payments.Communication.InitState.Execute(): Exiting.",
                                PayflowConstants.SeverityDebug);
            return(Task.CompletedTask);
        }
Exemple #22
0
 public UnitOfWork(CommContext dbc)
 {
     this.db = dbc;
 }
 public UserRepository(CommContext ctx)
 {
     this.db = ctx;
 }
Exemple #24
0
 public virtual void Handle(CommContext context)
 {
 }
Exemple #25
0
 public ProjectRepository(CommContext ctx)
 {
     this.db = ctx;
 }
        /// <inheritdoc />
                #pragma warning disable CA1506 // TODO: Decomplexify
        public async Task <ISessionController> LaunchNew(DreamDaemonLaunchParameters launchParameters, IDmbProvider dmbProvider, IByondExecutableLock currentByondLock, bool primaryPort, bool primaryDirectory, bool apiValidate, CancellationToken cancellationToken)
        {
            var portToUse = primaryPort ? launchParameters.PrimaryPort : launchParameters.SecondaryPort;

            if (!portToUse.HasValue)
            {
                throw new InvalidOperationException("Given port is null!");
            }
            var accessIdentifier = cryptographySuite.GetSecureString();

            const string JsonPostfix = "tgs.json";

            var basePath = primaryDirectory ? dmbProvider.PrimaryDirectory : dmbProvider.SecondaryDirectory;

            // delete all previous tgs json files
            var files = await ioManager.GetFilesWithExtension(basePath, JsonPostfix, cancellationToken).ConfigureAwait(false);

            await Task.WhenAll(files.Select(x => ioManager.DeleteFile(x, cancellationToken))).ConfigureAwait(false);

            // i changed this back from guids, hopefully i don't regret that
            string JsonFile(string name) => String.Format(CultureInfo.InvariantCulture, "{0}.{1}", name, JsonPostfix);

            var securityLevelToUse = launchParameters.SecurityLevel.Value;

            switch (dmbProvider.CompileJob.MinimumSecurityLevel)
            {
            case DreamDaemonSecurity.Ultrasafe:
                break;

            case DreamDaemonSecurity.Safe:
                if (securityLevelToUse == DreamDaemonSecurity.Ultrasafe)
                {
                    securityLevelToUse = DreamDaemonSecurity.Safe;
                }
                break;

            case DreamDaemonSecurity.Trusted:
                securityLevelToUse = DreamDaemonSecurity.Trusted;
                break;

            default:
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid DreamDaemonSecurity value: {0}", dmbProvider.CompileJob.MinimumSecurityLevel));
            }

            // setup interop files
            var interopInfo = new JsonFile
            {
                AccessIdentifier   = accessIdentifier,
                ApiValidateOnly    = apiValidate,
                ChatChannelsJson   = JsonFile("chat_channels"),
                ChatCommandsJson   = JsonFile("chat_commands"),
                ServerCommandsJson = JsonFile("server_commands"),
                InstanceName       = instance.Name,
                SecurityLevel      = securityLevelToUse,
                Revision           = new Api.Models.Internal.RevisionInformation
                {
                    CommitSha       = dmbProvider.CompileJob.RevisionInformation.CommitSha,
                    OriginCommitSha = dmbProvider.CompileJob.RevisionInformation.OriginCommitSha
                }
            };

            interopInfo.TestMerges.AddRange(dmbProvider.CompileJob.RevisionInformation.ActiveTestMerges.Select(x => x.TestMerge).Select(x => new Interop.TestMerge(x, interopInfo.Revision)));

            var interopJsonFile = JsonFile("interop");

            var interopJson = JsonConvert.SerializeObject(interopInfo, new JsonSerializerSettings
            {
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });

            var chatJsonTrackingTask = chat.TrackJsons(basePath, interopInfo.ChatChannelsJson, interopInfo.ChatCommandsJson, cancellationToken);

            await ioManager.WriteAllBytes(ioManager.ConcatPath(basePath, interopJsonFile), Encoding.UTF8.GetBytes(interopJson), cancellationToken).ConfigureAwait(false);

            var chatJsonTrackingContext = await chatJsonTrackingTask.ConfigureAwait(false);

            try
            {
                // get the byond lock
                var byondLock = currentByondLock ?? await byond.UseExecutables(Version.Parse(dmbProvider.CompileJob.ByondVersion), cancellationToken).ConfigureAwait(false);

                try
                {
                    // create interop context
                    var context = new CommContext(ioManager, loggerFactory.CreateLogger <CommContext>(), basePath, interopInfo.ServerCommandsJson);
                    try
                    {
                        // set command line options
                        // more sanitization here cause it uses the same scheme
                        var parameters = String.Format(CultureInfo.InvariantCulture, "{2}={0}&{3}={1}", byondTopicSender.SanitizeString(application.Version.ToString()), byondTopicSender.SanitizeString(interopJsonFile), byondTopicSender.SanitizeString(Constants.DMParamHostVersion), byondTopicSender.SanitizeString(Constants.DMParamInfoJson));

                        var visibility = apiValidate ? "invisible" : "public";

                        // important to run on all ports to allow port changing
                        var arguments = String.Format(CultureInfo.InvariantCulture, "{0} -port {1} -ports 1-65535 {2}-close -{3} -{5} -public -params \"{4}\"",
                                                      dmbProvider.DmbName,
                                                      primaryPort ? launchParameters.PrimaryPort : launchParameters.SecondaryPort,
                                                      launchParameters.AllowWebClient.Value ? "-webclient " : String.Empty,
                                                      SecurityWord(securityLevelToUse),
                                                      parameters,
                                                      visibility);

                        // See https://github.com/tgstation/tgstation-server/issues/719
                        var noShellExecute = !platformIdentifier.IsWindows;

                        // launch dd
                        var process = processExecutor.LaunchProcess(byondLock.DreamDaemonPath, basePath, arguments, noShellExecute: noShellExecute);
                        try
                        {
                            networkPromptReaper.RegisterProcess(process);

                            // return the session controller for it
                            var result = new SessionController(new ReattachInformation
                            {
                                AccessIdentifier = accessIdentifier,
                                Dmb                = dmbProvider,
                                IsPrimary          = primaryDirectory,
                                Port               = portToUse.Value,
                                ProcessId          = process.Id,
                                ChatChannelsJson   = interopInfo.ChatChannelsJson,
                                ChatCommandsJson   = interopInfo.ChatCommandsJson,
                                ServerCommandsJson = interopInfo.ServerCommandsJson,
                            }, process, byondLock, byondTopicSender, chatJsonTrackingContext, context, chat, loggerFactory.CreateLogger <SessionController>(), launchParameters.SecurityLevel, launchParameters.StartupTimeout);

                            // writeback launch parameter's fixed security level
                            launchParameters.SecurityLevel = securityLevelToUse;

                            return(result);
                        }
                        catch
                        {
                            process.Dispose();
                            throw;
                        }
                    }
                    catch
                    {
                        context.Dispose();
                        throw;
                    }
                }
                catch
                {
                    if (currentByondLock == null)
                    {
                        byondLock.Dispose();
                    }
                    throw;
                }
            }
            catch
            {
                chatJsonTrackingContext.Dispose();
                throw;
            }
        }
 public RoleRepository(CommContext ctx)
 {
     this.db = ctx;
 }