Example #1
0
        /// <summary>
        /// Logs the information at the provided level.
        /// </summary>
        /// <param name="level">        The logging level.</param>
        /// <param name="exception">    The exception.</param>
        /// <param name="messageFormat">The message format.</param>
        /// <param name="args">         A variable-length parameters list containing arguments.</param>
        public void Log(Logging.LogLevel level, Exception exception, string messageFormat, params object[] args)
        {
            if (exception == null)
            {
                this.Log(level, messageFormat, args);
                return;
            }

            switch (level)
            {
                case Logging.LogLevel.Fatal:
                    this.logger.Fatal(exception, messageFormat, args);
                    break;
                case Logging.LogLevel.Error:
                    this.logger.Error(exception, messageFormat, args);
                    break;
                case Logging.LogLevel.Warning:
                    this.logger.Warn(exception, messageFormat, args);
                    break;
                case Logging.LogLevel.Info:
                    this.logger.Info(exception, messageFormat, args);
                    break;
                case Logging.LogLevel.Debug:
                    this.logger.Debug(exception, messageFormat, args);
                    break;
                case Logging.LogLevel.Trace:
                    this.logger.Trace(exception, messageFormat, args);
                    break;
                default:
                    this.logger.Trace(exception, messageFormat, args);
                    break;
            }
        }
Example #2
0
        public EmailerService(Logging.ILogger logger
			, Services.IConnectorService connectorService
			, Services.IAccountService accountService
			, Services.CryptoService cryptoService
			, Services.IScheduledTaskService taskService
			)
        {
            this.Logger = logger;
            this.ConnectorService = connectorService;
            this.CryptoService = cryptoService;
            this.AccountService = accountService;
            this.TaskService = taskService;

            var smtpSection = System.Configuration.ConfigurationManager.GetSection("system.net/mailSettings/smtp") as System.Net.Configuration.SmtpSection;
            if (!smtpSection.From.IsNullOrTrimmedEmpty())
            {
                m_MailFrom = new MailAddress(smtpSection.From);
            }
            else
            {
                m_MailFrom = new MailAddress(ERPStoreApplication.WebSiteSettings.Contact.EmailSender,
                               ERPStoreApplication.WebSiteSettings.Contact.EmailSenderName);
            }

            var bccEmail = ERPStoreApplication.WebSiteSettings.Contact.BCCEmail ?? ERPStoreApplication.WebSiteSettings.Contact.ContactEmail;
            m_Bcc = new MailAddressCollection();
            if (bccEmail != null)
            {
                var emailList = bccEmail.Split(';');
                foreach (var email in emailList)
                {
                    m_Bcc.Add(email.Trim());
                }
            }
        }
Example #3
0
        /// <summary>
        /// Indicates whether logging at the indicated level is enabled.
        /// </summary>
        /// <param name="level">The logging level.</param>
        /// <returns>
        /// <c>true</c> if enabled, <c>false</c> if not.
        /// </returns>
        public bool IsEnabled(Logging.LogLevel level)
        {
            if (this.logger.IsTraceEnabled)
            {
                return level <= Logging.LogLevel.Trace;
            }

            if (this.logger.IsDebugEnabled)
            {
                return level <= Logging.LogLevel.Debug;
            }

            if (this.logger.IsInfoEnabled)
            {
                return level <= Logging.LogLevel.Info;
            }

            if (this.logger.IsWarnEnabled)
            {
                return level <= Logging.LogLevel.Warning;
            }

            if (this.logger.IsErrorEnabled)
            {
                return level <= Logging.LogLevel.Error;
            }

            if (this.logger.IsFatalEnabled)
            {
                return level <= Logging.LogLevel.Fatal;
            }

            return false;
        }
        public ActionResult UpdateGrid(string hiddenSchoolFilter, string hiddenSchoolYearFilter)
        {
            try
            {
                dbTIREntities db = new dbTIREntities();
                SiteUser siteUser = ((SiteUser)Session["SiteUser"]);
                StudentService studentService = new StudentService(siteUser, db);
                SchoolService schoolService = new SchoolService(siteUser, db);
                ModelServices modelService = new ModelServices();
                ViewBag.DistrictDesc = siteUser.Districts[0].Name;
                int schoolYearId = modelService.GetSchoolYearId(Convert.ToInt32(hiddenSchoolYearFilter));
                ViewBag.SchoolId = modelService.DropDownDataSchool(hiddenSchoolFilter, siteUser.EdsUserId, schoolYearId, true);
                ViewBag.AllowEdit = HelperService.AllowUiEdits(siteUser.RoleDesc, "STUDENT");
                ViewBag.SchoolYearList = schoolService.DropDownDataSchoolYear(hiddenSchoolYearFilter);

                ViewBag.SchoolYear = hiddenSchoolYearFilter;

                return View("Index", new SiteModels()
                {
                    Students = studentService.GetViewData(hiddenSchoolYearFilter, hiddenSchoolFilter)
                });
            }
            catch (Exception ex)
            {
                Logging log = new Logging();
                log.LogException(ex);
                return View("GeneralError");
            }
        }
 public ViewMatchSessions(
     Logging.LoggingInterfaces.ITracer logger)
 {
     this.logger = logger;
     this.context = FSharpInterop.Interop.GetNewContext();
     InitializeComponent();
 }
 /// <summary>
 /// Logs the information at the provided level.
 /// </summary>
 /// <param name="level">The logging level.</param>
 /// <param name="message">The message.</param>
 /// <param name="exception">The exception.</param>
 public void Log(Logging.LogLevel level, object message, Exception exception = null)
 {
     switch (level)
     {
         case Logging.LogLevel.Fatal:
             this.LogWithException(message, exception, this.logger.Fatal, this.logger.Fatal);
             break;
         case Logging.LogLevel.Error:
             this.LogWithException(message, exception, this.logger.Error, this.logger.Error);
             break;
         case Logging.LogLevel.Warning:
             this.LogWithException(message, exception, this.logger.Warn, this.logger.Warn);
             break;
         case Logging.LogLevel.Info:
             this.LogWithException(message, exception, this.logger.Info, this.logger.Info);
             break;
         case Logging.LogLevel.Debug:
             this.LogWithException(message, exception, this.logger.Debug, this.logger.Debug);
             break;
         case Logging.LogLevel.Trace:
             this.LogWithException(message, exception, this.logger.Trace, this.logger.Trace);
             break;
         default:
             this.LogWithException(message, exception, this.logger.Trace, this.logger.Trace);
             break;
     }
 }
 public FetchMatchdataDialog(Logging.LoggingInterfaces.ITracer logger, string defaultLink)
 {
     this.logger = logger;
     Result = null;
     InitializeComponent();
     linkTextBox.Text = defaultLink;
 }
 /// <summary>
 /// Logs the information at the provided level.
 /// </summary>
 /// <param name="level">The logging level.</param>
 /// <param name="messageFormat">The message format.</param>
 /// <param name="args">The arguments.</param>
 public void Log(Logging.LogLevel level, string messageFormat, params object[] args)
 {
     switch (level)
     {
         case Logging.LogLevel.Fatal:
             this.logger.Fatal(messageFormat, args);
             break;
         case Logging.LogLevel.Error:
             this.logger.Error(messageFormat, args);
             break;
         case Logging.LogLevel.Warning:
             this.logger.Warn(messageFormat, args);
             break;
         case Logging.LogLevel.Info:
             this.logger.Info(messageFormat, args);
             break;
         case Logging.LogLevel.Debug:
             this.logger.Debug(messageFormat, args);
             break;
         case Logging.LogLevel.Trace:
             this.logger.Trace(messageFormat, args);
             break;
         default:
             this.logger.Trace(messageFormat, args);
             break;
     }
 }
        // GET: /Students/
        public ActionResult Index()
        {
            try
            {
                dbTIREntities db = new dbTIREntities();
                SiteUser siteUser = ((SiteUser)Session["SiteUser"]);
                StudentService studentService = new StudentService(siteUser, db);
                SchoolService schoolService = new SchoolService(siteUser, db);
                ModelServices modelService = new ModelServices();
                string currentSchoolYear = schoolService.GetCurrentSchoolYear();
                ViewBag.DistrictDesc = siteUser.Districts[0].Name;
                int schoolYearId = modelService.SchoolYearId();
                ViewBag.SchoolId = modelService.DropDownDataSchool("", siteUser.EdsUserId, schoolYearId, true);
                ViewBag.AllowEdit = HelperService.AllowUiEdits(siteUser.RoleDesc, "STUDENT");
                //ViewBag.SchoolYear = HelperService.SchoolYearDescription(db);
                ViewBag.SchoolYearList = schoolService.DropDownDataSchoolYear(currentSchoolYear);
                ViewBag.AllowEdit = HelperService.AllowUiEdits(siteUser.RoleDesc, "STUDENT");
                ViewBag.SchoolYear = currentSchoolYear;

                return View(new SiteModels()
                {
                    Students = studentService.GetViewData(currentSchoolYear, "", "")
                });
            }
            catch (Exception ex)
            {
                Logging log = new Logging();
                log.LogException(ex);
                return View("GeneralError");
            }
        }
Example #10
0
 public MetadataUtils(Config.Saml2Configuration configuration, Logging.IInternalLogger logger)
 {
     if (configuration == null) throw new ArgumentNullException("configuration");
     if (logger == null) throw new ArgumentNullException("logger");
     this.configuration = configuration;
     this.logger = logger;
 }
Example #11
0
        public Validation()
        {
            _tfsServer = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConfigurationManager.AppSettings["TfsServer"]));
            _vsoServer = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ConfigurationManager.AppSettings["VsoServer"]));
            _vsoStore = _vsoServer.GetService<WorkItemStore>();
            _tfsStore = _tfsServer.GetService<WorkItemStore>();

            var actionValue = ConfigurationManager.AppSettings["Action"];
            if (actionValue.Equals("validate", StringComparison.OrdinalIgnoreCase))
            {
                _action = Action.Validate;
            }
            else
            {
                _action = Action.Compare;
            }

            var runDateTime = DateTime.Now.ToString("yyyy-MM-dd-HHmmss");

            var dataFilePath = ConfigurationManager.AppSettings["DataFilePath"];
            var dataDir = string.IsNullOrWhiteSpace(dataFilePath) ? Directory.GetCurrentDirectory() : dataFilePath;
            var dirName = string.Format("{0}\\Log-{1}",dataDir,runDateTime);

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }

            _errorLog = new Logging(string.Format("{0}\\Error.txt", dirName));
            _statusLog = new Logging(string.Format("{0}\\Status.txt", dirName));
            _fullLog = new Logging(string.Format("{0}\\FullLog.txt", dirName));

            _taskList = new List<Task>();

            if (!_action.Equals(Action.Compare))
            {
                return;
            }

            _valFieldErrorLog = new Logging(string.Format("{0}\\FieldError.txt", dirName));
            _valTagErrorLog = new Logging(string.Format("{0}\\TagError.txt", dirName));
            _valPostMigrationUpdateLog = new Logging(string.Format("{0}\\PostMigrationUpdate.txt", dirName));

            _imageLog = new Logging(string.Format("{0}\\ItemsWithImage.txt", dirName));

            _commonFields = new List<string>();
            _itemTypesToValidate = new List<string>();

            var fields = ConfigurationManager.AppSettings["CommonFields"].Split(',');
            foreach (var field in fields)
            {
                _commonFields.Add(field);
            }

            var types = ConfigurationManager.AppSettings["WorkItemTypes"].Split(',');
            foreach (var type in types)
            {
                _itemTypesToValidate.Add(type);
            }
        }
Example #12
0
 static SharedObjects()
 {
     ProgramName = string.Empty;
     MainWin = (Form)null;
     ProgramExit = false;
     Log = new Logging();
 }
Example #13
0
        void Logging_LogMessage(object sender, Logging.LogMessageEventArgs e)
        {
            CWSRestart.Controls.LogFilter.MessageType t = Controls.LogFilter.MessageType.General;

            switch (e.type)
            {
                case Logging.MessageType.Error:
                    t = Controls.LogFilter.MessageType.Error;
                    break;

                case Logging.MessageType.Info:
                    t = Controls.LogFilter.MessageType.Info;
                    break;

                case Logging.MessageType.Server:
                    t = Controls.LogFilter.MessageType.Server;
                    break;

                case Logging.MessageType.Warning:
                    t = Controls.LogFilter.MessageType.Warning;
                    break;
            }

            Application.Current.Dispatcher.BeginInvoke(new Action<Controls.LogFilter.LogMessage>((m) => LogControl.Messages.Add(m)), new Controls.LogFilter.LogMessage(e.message, t)); 
        }
Example #14
0
        public SettingsService(ERPStore.Services.ICacheService cacheService
			, Logging.ILogger logger
			, Microsoft.Practices.Unity.IUnityContainer container)
        {
            this.CacheService = cacheService;
            this.Logger = logger;
            this.Container = container;
        }
        public ManagePlayers(Logging.LoggingInterfaces.ITracer logger)
        {
            this.logger = logger;

            // this is a copy.. this way we can discard everything at the end, if we need to
            wrapper = FSharpInterop.Interop.GetNewContext();
            InitializeComponent();
        }
        public HttpContextCartRepository(System.Web.HttpContext ctx
			, Services.ICacheService cacheService
			, Logging.ILogger logger)
        {
            HttpContext = ctx;
            CacheService = cacheService;
            this.Logger = logger;
        }
Example #17
0
 /// <summary>
 /// Constructor that takes all Employee attributes as parameters.
 /// </summary>
 /// <param name="firstName">Value for firstName. String.</param>
 /// <param name="lastName">Value for lastName. String.</param>
 /// <param name="date">Value for dateOfBirth. String.</param>
 /// <param name="socialInsNum">Value for socialinsuranceNumber. String.</param>
 public Employee(String firstName, String lastName, String date, String socialInsNum)
 {
     logfile = new Logging();
     SetFirstName(firstName);
     SetLastName(lastName);
     SetSocialNumber(socialInsNum);
     SetDateOfBirth(date);
 }
Example #18
0
 /// <summary>
 /// Constructor that takes in firstName and lastName as parameters.
 /// Intializes all other attributes to their default values.
 /// </summary>
 /// <param name="firstName">Value for firstName. String.</param>
 /// <param name="lastName">Value for lastName. String.</param>
 public Employee(String firstName, String lastName)
 {
     logfile = new Logging();
     SetFirstName("");
     SetLastName("");
     SetSocialNumber("000000000");
     SetDateOfBirth(new DateTime(0));
 }
 public void When_config_section_threshold_is_null_threshold_should_be_null()
 {
     var configSection = new Logging
     {
         Threshold = null
     };
     Assert.IsNull(SetLoggingLibrary.GetThresholdFromConfigSection(configSection));
 }
 public void When_config_section_threshold_is_validString_threshold_should_be_that_value()
 {
     var configSection = new Logging
     {
         Threshold = "High"
     };
     Assert.AreEqual("High", SetLoggingLibrary.GetThresholdFromConfigSection(configSection));
 }
Example #21
0
 public void logSentence()
 {
     if (_wholeSentence.Length > 0)
     {
         var logging = new Logging();
         logging.log("sentences", _wholeSentence);
     }
 }
Example #22
0
        /// <summary>
        /// Logs text to the textbox on the main form.
        /// </summary>
        /// <param name="Text">The text to log.</param>
        /// <param name="Type">A Logging.logType enum value, indicating the log's type.</param>
        public void logText(string Text, Logging.logType Type)
        {
            if (this.InvokeRequired)
                this.BeginInvoke(_Logger, Text, Type);
            else
            {
                try
                {
                    lock (this.txtLog)
                    {
                        switch (Type)
                        {
                            case Logging.logType.commonWarning:
                                {
                                    StringBuilder Data = new StringBuilder();
                                    Data.Append("Warning!" + Environment.NewLine);
                                    Data.Append("Time: " + DateTime.Now.ToShortTimeString() + Environment.NewLine);
                                    Data.Append("Description: " + Text + Environment.NewLine + Environment.NewLine);

                                    this.txtLog.SelectionColor = Color.Brown;
                                    this.txtLog.SelectedText = Data.ToString();
                                }
                                break;

                            case Logging.logType.reactorError:
                            case Logging.logType.commonError:
                                {
                                    StackFrame st = new StackTrace().GetFrame(2);
                                    StringBuilder Data = new StringBuilder();

                                    Data.Append("ERROR!" + Environment.NewLine);
                                    Data.Append("Time: " + DateTime.Now.ToShortTimeString() + Environment.NewLine);
                                    Data.Append("Object: " + st.GetMethod().ReflectedType.Name + Environment.NewLine);
                                    Data.Append("Method: " + st.GetMethod().Name + Environment.NewLine);
                                    Data.Append("Description: " + Text + Environment.NewLine + Environment.NewLine);

                                    this.txtLog.SelectionColor = Color.DarkRed;
                                    this.txtLog.SelectedText = Data.ToString();
                                }
                                break;

                            default:
                                {
                                    this.txtLog.AppendText("# ");
                                    this.txtLog.AppendText(Text);
                                    this.txtLog.AppendText(Environment.NewLine);
                                }
                                break;
                        }

                        this.txtLog.SelectionStart = this.txtLog.Text.Length;
                        this.txtLog.ScrollToCaret();
                        this.txtLog.Refresh();
                    }
                }
                catch (Exception) { }
            }
        }
Example #23
0
        // Constructor
        public PDBOperation()
        {
            _ConfigParam.LoadWebSVCConfigParam();
            _WebSVCConfig = _ConfigParam.WebSVCConfigStructures;
            Logger = new Logging(_WebSVCConfig.LogLevel, _WebSVCConfig.LogPath);

            _DbConnStr = string.Format("Provider=MSDAORA.1;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={2})));User Id={3};Password={4};",
                _WebSVCConfig.DBHostName, _WebSVCConfig.DBPort, _WebSVCConfig.DBServiceName, _WebSVCConfig.DBUserId, _WebSVCConfig.DBPassword);
        }
        public IncentiveService(Logging.ILogger logger,
			Repositories.ICouponRepository couponRepository,
			IAccountService accountService
			)
        {
            this.CouponRepository = couponRepository;
            this.Logger = logger;
            this.AccountService = accountService;
        }
Example #25
0
        public ServiceMain()
        {
            InitializeComponent();
            _logFile = new Logging();
            _logFile.logFileName = "EventLog";
            _logFile.WriteToLog("EventLog has been created.");

            string minuteDisplay;
            int timerIntervalMinutes = Properties.Settings.Default.TimerIntervalMinutes;
            minuteDisplay = timerIntervalMinutes == 1 ? " minute." : " minutes.";

            _timerIntervalMilliseconds = 1000 * 60 * timerIntervalMinutes;
            _logFile.WriteToLog("Timer interval set to " + timerIntervalMinutes.ToString() + minuteDisplay);

            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
            sc = Properties.Settings.Default.ScanDirectories;
            string[] scanDir = new string[sc.Count];

            //Copies all rows from string collection
            sc.CopyTo(scanDir, 0);

            string dirDisplay;
            dirDisplay = sc.Count == 1 ? "directory" : "directories";
            _logFile.WriteToLog("The following source " + dirDisplay + " will be scanned:");
            foreach (string dirName in scanDir)
            {
                _logFile.WriteToLog("--> " + dirName);
            }

            //jvc
            string failedDir = Properties.Settings.Default.FailedDirectory;
            _logFile.WriteToLog("FailedDirectory=" + failedDir);

            string outputDir = Properties.Settings.Default.OutputDirectory;
            string processedDir = Properties.Settings.Default.ProcessedDirectory;
            string validFileExt = Properties.Settings.Default.ValidFileExt;
            bool isDebugLogEnabled = Properties.Settings.Default.DebugLogEnabled;

            //_logFile.WriteToLog("OutputDirectory=" + outputDir);
            _logFile.WriteToLog("ProcessedDirectory=" + processedDir);
            _logFile.WriteToLog("ValidFileExt=" + validFileExt);
            _logFile.WriteToLog("DebugLogEnabled=" + isDebugLogEnabled);

            _logFile.WriteToLog("Creating DirectoryPoller...");
            _dirProcessor = new DirectoryProcessor(scanDir, validFileExt, outputDir, processedDir, failedDir, _logFile);
            _dirProcessor._isDebugLogEnabled = isDebugLogEnabled;
            _dirProcessor._EventLog = _logFile;
            _logFile.WriteToLog("DirectoryPoller was successfully created.");

            this.timerMain.Interval = _timerIntervalMilliseconds;
            //this.timerMain.Elapsed += new System.Timers.ElapsedEventHandler(timerMain_Elapsed);

            // If the timer is declared in a long-running method, use
            // KeepAlive to prevent garbage collection from occurring
            // before the method ends.
            GC.KeepAlive(timerMain);
        }
Example #26
0
        public EmailerService(Logging.ILogger logger
			, ERPStore.Services.IConnectorService connectorService
			, ERPStore.Services.IAccountService accountService
			, ERPStore.Services.CryptoService cryptoService
			, ERPStore.Services.IScheduledTaskService taskService
			)
            : base(logger, connectorService, accountService, cryptoService, taskService)
        {
        }
Example #27
0
        public Engine()
        {
            _unitActionDict = new ConcurrentDictionary<CharacterBase, ActionBase>();
            _scheduledActionsDict = new ConcurrentDictionary<long, ConcurrentQueue<CharacterBase>>();
            _timeKeeper = new TimeKeeper();
            _map = new Map();
            _characters = new List<CharacterBase>();

            Logging = new Logging();
        }
Example #28
0
        public Engine()
        {
            Scrn = new Bitmap(240, 160, PixelFormat.Format16bppRgb555);

            myCPU = new Armcpu(this);
            myMemory = new Memory(this);
            myLog = new Logging();
            myGfx = new Gfx(this);
            emulate=false;
        }
 public ManageWatchFolder(Logging.LoggingInterfaces.ITracer logger, LocalDatabaseWrapper context, WrapperDataTable.WrapperTable<WatchFolder> wrapperTable, Game game)
 {
     this.logger = logger;
     this.context = context;
     this.wrapperTable = wrapperTable;
     this.wrapperTableCopy = wrapperTable.Clone();
     wrapperTableCopy.UserAddedRow += wrapperTableCopy_UserAddedRow;
     wrapperTableCopy.DeletedRow += wrapperTableCopy_DeletedRow;
     this.game = game;
     InitializeComponent();
 }
Example #30
0
 private void Server_Log(object sender, Logging.LogEventArgs e)
 {
     if (InvokeRequired)
     {
         EventHandler<Logging.LogEventArgs> hnd = new EventHandler<Logging.LogEventArgs>(Server_Log);
         Invoke(hnd, new object[] { sender, e });
         return;
     }
     logText.AppendText(e.Text + Environment.NewLine);
     logText.SelectionStart = logText.TextLength;
     logText.ScrollToCaret();
 }
Example #31
0
        /// <summary>
        ///
        /// </summary>
        private void SyncBlockSettingsReceived(byte[] dataRcv)
        {
            try
            {
                var msgRcv = MyAPIGateway.Utilities.SerializeFromBinary <MsgBlockSettings>(dataRcv);

                NanobotBuildAndRepairSystemBlock system;
                if (BuildAndRepairSystems.TryGetValue(msgRcv.EntityId, out system))
                {
                    if (Mod.Log.ShouldLog(Logging.Level.Communication))
                    {
                        Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockSettingsReceived EntityId={0}/{1}", msgRcv.EntityId, Logging.BlockName(system.Entity, Logging.BlockNameOptions.None));
                    }
                    system.Settings.AssignReceived(msgRcv.Settings, system.BlockWeldPriority, system.BlockGrindPriority, system.ComponentCollectPriority);
                    if (MyAPIGateway.Session.IsServer)
                    {
                        SyncBlockSettingsSend(0, system);
                    }
                }
                else
                {
                    if (Mod.Log.ShouldLog(Logging.Level.Error))
                    {
                        Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockSettingsReceived for unknown system EntityId={0}", msgRcv.EntityId);
                    }
                }
            }
            catch (Exception ex)
            {
                Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockSettingsReceived Exception:{0}", ex);
            }
        }
Example #32
0
    public static async void Connect(HttpListenerContext ctx)
    {
        WebSocketContext wsc;
        WebSocket        ws;

        try {
            wsc = await ctx.AcceptWebSocketAsync(null);

            ws = wsc.WebSocket;
        } catch (WebSocketException ex) {
            ctx.Response.Close();
            Logging.Err(ex);
            return;
        }

        string sessionId = ctx.Request.Cookies["sessionid"]?.Value ?? null;

        if (sessionId is null)
        {
            ctx.Response.Close();
            return;
        }

        if (!Session.sessions.ContainsKey(sessionId))
        {
            ctx.Response.Close();
            return;
        }

        Session.SessionEntry sessionEntry = Session.sessions[sessionId];

        try {
            if (ws.State == WebSocketState.Open)
            {
                connections.Add(ws, new AliveEntry()
                {
                    ws       = ws,
                    session  = sessionId,
                    username = sessionEntry.username,
                    syncLock = new object()
                });
            }

            byte[] authorization = Encoding.UTF8.GetBytes(
                $"{{\"action\":\"authorization\",\"accesslist\":\"{sessionEntry.accessControl}\"}}"
                );
            await ws.SendAsync(new ArraySegment <byte>(authorization, 0, authorization.Length), WebSocketMessageType.Text, true, CancellationToken.None);

            byte[] version = Encoding.UTF8.GetBytes(
                $"{{\"action\":\"version\",\"userver\":\"{Database.usersVer}\",\"equipver\":\"{Database.equipVer}\"}}"
                );
            await ws.SendAsync(new ArraySegment <byte>(version, 0, version.Length), WebSocketMessageType.Text, true, CancellationToken.None);

            while (ws.State == WebSocketState.Open)
            {
                byte[] buff = new byte[1024];
                WebSocketReceiveResult receiveResult = await ws.ReceiveAsync(new ArraySegment <byte>(buff), CancellationToken.None);

                if (!Session.CheckAccess(sessionId))   //check session
                {
                    await ws.SendAsync(MSG_FORCE_RELOAD, WebSocketMessageType.Text, true, CancellationToken.None);

                    ctx.Response.Close();
                    return;
                }

                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                    break;
                }

                string[] action = Encoding.Default.GetString(buff, 0, receiveResult.Count).Split((char)127);
                if (action.Length > 1)
                {
                    switch (action[0])
                    {
                    case "updatesessiontimeout":
                        Session.UpdateSessionTimeout(sessionId, action?[1]);
                        if (!Session.CheckAccess(sessionId))       //check session
                        {
                            await ws.SendAsync(MSG_FORCE_RELOAD, WebSocketMessageType.Text, true, CancellationToken.None);

                            ctx.Response.Close();
                            return;
                        }
                        break;
                    }
                }
            }
        } catch { }

        //connections.Remove(ws);
    }
Example #33
0
        /// <summary>
        ///
        /// </summary>
        private void SyncBlockStateReceived(byte[] dataRcv)
        {
            try
            {
                var msgRcv = MyAPIGateway.Utilities.SerializeFromBinary <MsgBlockState>(dataRcv);

                NanobotBuildAndRepairSystemBlock system;
                if (BuildAndRepairSystems.TryGetValue(msgRcv.EntityId, out system))
                {
                    if (Mod.Log.ShouldLog(Logging.Level.Communication))
                    {
                        Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockStateReceived EntityId={0}/{1}, State={2}", system.Entity.EntityId, Logging.BlockName(system.Entity, Logging.BlockNameOptions.None), msgRcv.State.ToString());
                    }
                    system.State.AssignReceived(msgRcv.State);
                }
                else
                {
                    if (Mod.Log.ShouldLog(Logging.Level.Error))
                    {
                        Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockStateReceived for unknown system EntityId={0}", msgRcv.EntityId);
                    }
                }
            }
            catch (Exception ex)
            {
                Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockStateReceived Exception:{0}", ex);
            }
        }
Example #34
0
 private static void Log(string message)
 {
     message = "[Auto-Updater][" + ProjectName + "] " + message;
     Logging.Write(LogColor, message);
 }
 private void DownloadButton_Click(object sender, RoutedEventArgs e)
 {
     Logging.Debug("User clicked to download from the release notes window");
     ClientUpdater.Instance.DownloadNewClientVersion(null);
 }
Example #36
0
        internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
                               bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, this, ".ctor", "hostname=" + hostname + ", #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)) + ", encryptionPolicy=" + encryptionPolicy);
            }

            SslStreamPal.VerifyPackageInfo();

            _destination = hostname;

            GlobalLog.Assert(hostname != null, "SecureChannel#{0}::.ctor()|hostname == null", Logging.HashString(this));
            _hostName   = hostname;
            _serverMode = serverMode;

            _sslProtocols = sslProtocols;

            _serverCertificate       = serverCertificate;
            _clientCertificates      = clientCertificates;
            _remoteCertRequired      = remoteCertRequired;
            _securityContext         = null;
            _checkCertRevocation     = checkCertRevocationStatus;
            _checkCertName           = checkCertName;
            _certSelectionDelegate   = certSelectionDelegate;
            _refreshCredentialNeeded = true;
            _encryptionPolicy        = encryptionPolicy;
            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::.ctor");
        }
Example #37
0
        //
        // Acquire Server Side Certificate information and set it on the class.
        //
        private bool AcquireServerCredentials(ref byte[] thumbPrint)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials");

            X509Certificate localCertificate = null;
            bool            cachedCred       = false;

            if (_certSelectionDelegate != null)
            {
                X509CertificateCollection tempCollection = new X509CertificateCollection();
                tempCollection.Add(_serverCertificate);
                localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty <string>());
                GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert");
            }
            else
            {
                localCertificate = _serverCertificate;
            }

            if (localCertificate == null)
            {
                throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
            }

            // SECURITY: Accessing X509 cert Credential is disabled for semitrust.
            // We no longer need to demand for unmanaged code permissions.
            // EnsurePrivateKey should do the right demand for us.
            X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);

            if (selectedCert == null)
            {
                throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
            }

            GlobalLog.Assert(localCertificate.Equals(selectedCert), "AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");

            //
            // Note selectedCert is a safe ref possibly cloned from the user passed Cert object
            //
            byte[] guessedThumbPrint = selectedCert.GetCertHash();
            try
            {
                SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);

                if (cachedCredentialHandle != null)
                {
                    _credentialsHandle = cachedCredentialHandle;
                    _serverCertificate = localCertificate;
                    cachedCred         = true;
                }
                else
                {
                    _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);
                    thumbPrint         = guessedThumbPrint;
                    _serverCertificate = localCertificate;
                }
            }
            finally
            {
                // An extra cert could have been created, dispose it now.
                if ((object)localCertificate != (object)selectedCert)
                {
                    selectedCert.Dispose();
                }
            }

            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle));
            return(cachedCred);
        }
Example #38
0
        //
        // SECURITY: we open a private key container on behalf of the caller
        // and we require the caller to have permission associated with that operation.
        //
        private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
        {
            if (certificate == null)
            {
                return(null);
            }

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_locating_private_key_for_certificate, certificate.ToString(true)));
            }

            try
            {
                string certHash = null;

                // Protecting from X509Certificate2 derived classes.
                X509Certificate2 certEx = MakeEx(certificate);

                certHash = certEx.Thumbprint;

                if (certEx != null)
                {
                    if (certEx.HasPrivateKey)
                    {
                        if (Logging.On)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.net_log_cert_is_of_type_2);
                        }

                        return(certEx);
                    }

                    if ((object)certificate != (object)certEx)
                    {
                        certEx.Dispose();
                    }
                }

                X509Certificate2Collection collectionEx;

                // ELSE Try the MY user and machine stores for private key check.
                // For server side mode MY machine store takes priority.
                X509Store store = CertificateValidationPal.EnsureStoreOpened(_serverMode);
                if (store != null)
                {
                    collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
                    if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
                    {
                        if (Logging.On)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_found_cert_in_store, (_serverMode ? "LocalMachine" : "CurrentUser")));
                        }

                        return(collectionEx[0]);
                    }
                }

                store = CertificateValidationPal.EnsureStoreOpened(!_serverMode);
                if (store != null)
                {
                    collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
                    if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
                    {
                        if (Logging.On)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_found_cert_in_store, (_serverMode ? "CurrentUser" : "LocalMachine")));
                        }

                        return(collectionEx[0]);
                    }
                }
            }
            catch (CryptographicException)
            {
            }

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, this, SR.net_log_did_not_find_cert_in_store);
            }

            return(null);
        }
Example #39
0
        /*++
         *  AcquireCredentials - Attempts to find Client Credential
         *  Information, that can be sent to the server.  In our case,
         *  this is only Client Certificates, that we have Credential Info.
         *
         *  How it works:
         *      case 0: Cert Selection delegate is present
         *              Always use its result as the client cert answer.
         *              Try to use cached credential handle whenever feasible.
         *              Do not use cached anonymous creds if the delegate has returned null
         *              and the collection is not empty (allow responding with the cert later).
         *
         *      case 1: Certs collection is empty
         *              Always use the same statically acquired anonymous SSL Credential
         *
         *      case 2: Before our Connection with the Server
         *              If we have a cached credential handle keyed by first X509Certificate
         **content** in the passed collection, then we use that cached
         *              credential and hoping to restart a session.
         *
         *              Otherwise create a new anonymous (allow responding with the cert later).
         *
         *      case 3: After our Connection with the Server (i.e. during handshake or re-handshake)
         *              The server has requested that we send it a Certificate then
         *              we Enumerate a list of server sent Issuers trying to match against
         *              our list of Certificates, the first match is sent to the server.
         *
         *              Once we got a cert we again try to match cached credential handle if possible.
         *              This will not restart a session but helps minimizing the number of handles we create.
         *
         *      In the case of an error getting a Certificate or checking its private Key we fall back
         *      to the behavior of having no certs, case 1.
         *
         *  Returns: True if cached creds were used, false otherwise.
         *
         * --*/

        private bool AcquireClientCredentials(ref byte[] thumbPrint)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials");

            // Acquire possible Client Certificate information and set it on the handle.
            X509Certificate clientCertificate = null;            // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
            ArrayList       filteredCerts     = new ArrayList(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet.

            string[] issuers = null;                             // This is a list of issuers sent by the server, only valid is we do know what the server cert is.

            bool sessionRestartAttempt = false;                  // If true and no cached creds we will use anonymous creds.

            if (_certSelectionDelegate != null)
            {
                issuers = GetRequestCertificateAuthorities();

                GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback");

                X509Certificate2 remoteCert = null;
                try
                {
                    X509Certificate2Collection dummyCollection;
                    remoteCert        = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection);
                    clientCertificate = _certSelectionDelegate(_hostName, ClientCertificates, remoteCert, issuers);
                }
                finally
                {
                    if (remoteCert != null)
                    {
                        remoteCert.Dispose();
                    }
                }


                if (clientCertificate != null)
                {
                    if (_credentialsHandle == null)
                    {
                        sessionRestartAttempt = true;
                    }

                    filteredCerts.Add(clientCertificate);
                    if (Logging.On)
                    {
                        Logging.PrintInfo(Logging.Web, this, SR.net_log_got_certificate_from_delegate);
                    }
                }
                else
                {
                    if (ClientCertificates.Count == 0)
                    {
                        if (Logging.On)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.net_log_no_delegate_and_have_no_client_cert);
                        }

                        sessionRestartAttempt = true;
                    }
                    else
                    {
                        if (Logging.On)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.net_log_no_delegate_but_have_client_cert);
                        }
                    }
                }
            }
            else if (_credentialsHandle == null && _clientCertificates != null && _clientCertificates.Count > 0)
            {
                // This is where we attempt to restart a session by picking the FIRST cert from the collection.
                // Otherwise it is either server sending a client cert request or the session is renegotiated.
                clientCertificate     = ClientCertificates[0];
                sessionRestartAttempt = true;
                if (clientCertificate != null)
                {
                    filteredCerts.Add(clientCertificate);
                }

                if (Logging.On)
                {
                    Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_attempting_restart_using_cert, (clientCertificate == null ? "null" : clientCertificate.ToString(true))));
                }
            }
            else if (_clientCertificates != null && _clientCertificates.Count > 0)
            {
                //
                // This should be a server request for the client cert sent over currently anonymous sessions.
                //
                issuers = GetRequestCertificateAuthorities();

                if (Logging.On)
                {
                    if (issuers == null || issuers.Length == 0)
                    {
                        Logging.PrintInfo(Logging.Web, this, SR.net_log_no_issuers_try_all_certs);
                    }
                    else
                    {
                        Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_server_issuers_look_for_matching_certs, issuers.Length));
                    }
                }

                for (int i = 0; i < _clientCertificates.Count; ++i)
                {
                    //
                    // Make sure we add only if the cert matches one of the issuers.
                    // If no issuers were sent and then try all client certs starting with the first one.
                    //
                    if (issuers != null && issuers.Length != 0)
                    {
                        X509Certificate2 certificateEx = null;
                        X509Chain        chain         = null;
                        try
                        {
                            certificateEx = MakeEx(_clientCertificates[i]);
                            if (certificateEx == null)
                            {
                                continue;
                            }

                            GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer);
                            chain = new X509Chain();

                            chain.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName;
                            chain.Build(certificateEx);
                            bool found = false;

                            //
                            // We ignore any errors happened with chain.
                            //
                            if (chain.ChainElements.Count > 0)
                            {
                                for (int ii = 0; ii < chain.ChainElements.Count; ++ii)
                                {
                                    string issuer = chain.ChainElements[ii].Certificate.Issuer;
                                    found = Array.IndexOf(issuers, issuer) != -1;
                                    if (found)
                                    {
                                        GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() matched:" + issuer);
                                        break;
                                    }
                                    GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() no match:" + issuer);
                                }
                            }

                            if (!found)
                            {
                                continue;
                            }
                        }
                        finally
                        {
                            if (chain != null)
                            {
                                chain.Dispose();
                            }

                            if (certificateEx != null && (object)certificateEx != (object)_clientCertificates[i])
                            {
                                certificateEx.Dispose();
                            }
                        }
                    }

                    if (Logging.On)
                    {
                        Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_selected_cert, _clientCertificates[i].ToString(true)));
                    }

                    filteredCerts.Add(_clientCertificates[i]);
                }
            }

            bool             cachedCred   = false;     // This is a return result from this method.
            X509Certificate2 selectedCert = null;      // This is a final selected cert (ensured that it does have private key with it).

            clientCertificate = null;

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, this, SR.Format(SR.net_log_n_certs_after_filtering, filteredCerts.Count));
                if (filteredCerts.Count != 0)
                {
                    Logging.PrintInfo(Logging.Web, this, SR.net_log_finding_matching_certs);
                }
            }

            //
            // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key,
            //       THEN anonymous (no client cert) credential will be used.
            //
            // SECURITY: Accessing X509 cert Credential is disabled for semitrust.
            // We no longer need to demand for unmanaged code permissions.
            // EnsurePrivateKey should do the right demand for us.
            for (int i = 0; i < filteredCerts.Count; ++i)
            {
                clientCertificate = filteredCerts[i] as X509Certificate;
                if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null)
                {
                    break;
                }

                clientCertificate = null;
                selectedCert      = null;
            }

            GlobalLog.Assert(((object)clientCertificate == (object)selectedCert) || clientCertificate.Equals(selectedCert), "AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");

            GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null ? "null" : selectedCert.Subject));
            try
            {
                // Try to locate cached creds first.
                //
                // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type.
                //
                byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash();
                SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);

                // We can probably do some optimization here. If the selectedCert is returned by the delegate
                // we can always go ahead and use the certificate to create our credential
                // (instead of going anonymous as we do here).
                if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null)
                {
                    GlobalLog.Print("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session.");

                    // IIS does not renegotiate a restarted session if client cert is needed.
                    // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
                    // The following block happens if client did specify a certificate but no cached creds were found in the cache.
                    // Since we don't restart a session the server side can still challenge for a client cert.
                    if ((object)clientCertificate != (object)selectedCert)
                    {
                        selectedCert.Dispose();
                    }

                    guessedThumbPrint = null;
                    selectedCert      = null;
                    clientCertificate = null;
                }

                if (cachedCredentialHandle != null)
                {
                    if (Logging.On)
                    {
                        Logging.PrintInfo(Logging.Web, SR.net_log_using_cached_credential);
                    }

                    _credentialsHandle         = cachedCredentialHandle;
                    _selectedClientCertificate = clientCertificate;
                    cachedCred = true;
                }
                else
                {
                    _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);

                    thumbPrint = guessedThumbPrint; // Delay until here in case something above threw.
                    _selectedClientCertificate = clientCertificate;
                }
            }
            finally
            {
                // An extra cert could have been created, dispose it now.
                if (selectedCert != null && (object)clientCertificate != (object)selectedCert)
                {
                    selectedCert.Dispose();
                }
            }

            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), Logging.ObjectToString(_credentialsHandle));
            return(cachedCred);
        }
Example #40
0
        internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::GetChannelBindingToken", kind.ToString());

            ChannelBinding result = null;

            if (_securityContext != null)
            {
                result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
            }

            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::GetChannelBindingToken", Logging.HashString(result));
            return(result);
        }
Example #41
0
        /*++
         *  VerifyRemoteCertificate - Validates the content of a Remote Certificate
         *
         *  checkCRL if true, checks the certificate revocation list for validity.
         *  checkCertName, if true checks the CN field of the certificate
         * --*/

        //This method validates a remote certificate.
        //SECURITY: The scenario is allowed in semitrust StorePermission is asserted for Chain.Build
        //          A user callback has unique signature so it is safe to call it under permission assert.
        //
        internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback)
        {
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::VerifyRemoteCertificate");
            SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;

            // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
            bool             success             = false;
            X509Chain        chain               = null;
            X509Certificate2 remoteCertificateEx = null;

            try
            {
                X509Certificate2Collection remoteCertificateStore;
                remoteCertificateEx           = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore);
                _isRemoteCertificateAvailable = remoteCertificateEx != null;

                if (remoteCertificateEx == null)
                {
                    GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::VerifyRemoteCertificate (no remote cert)", (!_remoteCertRequired).ToString());
                    sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
                }
                else
                {
                    chain = new X509Chain();
                    chain.ChainPolicy.RevocationMode = _checkCertRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
                    chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
                    if (remoteCertificateStore != null)
                    {
                        chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore);
                    }

                    sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties(
                        chain,
                        remoteCertificateEx,
                        _checkCertName,
                        _serverMode,
                        _hostName);
                }

                if (remoteCertValidationCallback != null)
                {
                    success = remoteCertValidationCallback(_hostName, remoteCertificateEx, chain, sslPolicyErrors);
                }
                else
                {
                    if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_remoteCertRequired)
                    {
                        success = true;
                    }
                    else
                    {
                        success = (sslPolicyErrors == SslPolicyErrors.None);
                    }
                }

                if (Logging.On)
                {
                    if (sslPolicyErrors != SslPolicyErrors.None)
                    {
                        Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_has_errors);
                        if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
                        {
                            Logging.PrintInfo(Logging.Web, this, "\t" + SR.net_log_remote_cert_not_available);
                        }

                        if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
                        {
                            Logging.PrintInfo(Logging.Web, this, "\t" + SR.net_log_remote_cert_name_mismatch);
                        }

                        if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
                        {
                            foreach (X509ChainStatus chainStatus in chain.ChainStatus)
                            {
                                Logging.PrintInfo(Logging.Web, this, "\t" + chainStatus.StatusInformation);
                            }
                        }
                    }
                    if (success)
                    {
                        if (remoteCertValidationCallback != null)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_user_declared_valid);
                        }
                        else
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_has_no_errors);
                        }
                    }
                    else
                    {
                        if (remoteCertValidationCallback != null)
                        {
                            Logging.PrintInfo(Logging.Web, this, SR.net_log_remote_cert_user_declared_invalid);
                        }
                    }
                }
                GlobalLog.Print("Cert Validation, remote cert = " + (remoteCertificateEx == null ? "<null>" : remoteCertificateEx.ToString(true)));
            }
            finally
            {
                // At least on Win2k server the chain is found to have dependencies on the original cert context.
                // So it should be closed first.
                if (chain != null)
                {
                    chain.Dispose();
                }

                if (remoteCertificateEx != null)
                {
                    remoteCertificateEx.Dispose();
                }
            }
            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::VerifyRemoteCertificate", success.ToString());
            return(success);
        }
Example #42
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            string _cName = dgvDevices.CurrentRow.Cells["name"].Value.ToString();
            string _Abbr  = dgvDevices.CurrentRow.Cells["abbreviation"].Value.ToString();
            string _unit  = dgvDevices.CurrentRow.Cells["unit"].Value.ToString();
            int    zid    = Convert.ToInt32(dgvDevices.CurrentRow.Cells["id"].Value);

            if (Convert.ToBoolean(dgvDevices.CurrentRow.Cells["is_active"].Value))
            {
                //if (MessageBox.Show("Вы уверены, что хотите удалить запись?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                if (Convert.ToBoolean(dgvDevices.CurrentRow.Cells["used"].Value))// && MessageBox.Show("Удаляемая запись испольхуется и её невозможно удалить. Сделать запись неактивной?", "Ошибка", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes)
                {
                    if (MessageBox.Show("Выбранная для удаления запись\n    используется в программе.\nСделать запись недействующей?",
                                        "Удаление записи", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                        MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        Logging.StartFirstLevel(540);
                        Logging.Comment("Произведена смена статуса на неактивный у прибора");
                        Logging.Comment("ID: " + zid);
                        Logging.Comment("Наименование прибора: " + _cName);
                        Logging.Comment("Аббревиатура прибора: " + _Abbr);
                        Logging.Comment("Единицы измерения: " + _unit);

                        Logging.Comment("Операцию выполнил: ID:" + Nwuram.Framework.Settings.User.UserSettings.User.Id
                                        + " ; ФИО:" + Nwuram.Framework.Settings.User.UserSettings.User.FullUsername);
                        Logging.StopFirstLevel();

                        //proc.DeleteDevice(Convert.ToInt32(dgvDevices.CurrentRow.Cells["id"].Value), true);
                        proc.RestoreDevice(Convert.ToInt32(dgvDevices.CurrentRow.Cells["id"].Value), false, true);
                    }
                }
                else
                {
                    if (MessageBox.Show("Удалить выбранную запись?", "Удаление записи",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                        MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        Logging.StartFirstLevel(1393);
                        Logging.Comment("Удаление прибора");
                        Logging.Comment("ID: " + zid);
                        Logging.Comment("Наименование прибора: " + _cName);
                        Logging.Comment("Аббревиатура прибора: " + _Abbr);
                        Logging.Comment("Единицы измерения: " + _unit);

                        Logging.Comment("Операцию выполнил: ID:" + Nwuram.Framework.Settings.User.UserSettings.User.Id
                                        + " ; ФИО:" + Nwuram.Framework.Settings.User.UserSettings.User.FullUsername);
                        Logging.StopFirstLevel();

                        //proc.DeleteDevice(Convert.ToInt32(dgvDevices.CurrentRow.Cells["id"].Value), false);
                        proc.RestoreDevice(Convert.ToInt32(dgvDevices.CurrentRow.Cells["id"].Value), false, false);
                    }
                }
                dgvDevices_Load();
            }
            else
            {
                //if (MessageBox.Show("Сделать запись снова активной?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                if (MessageBox.Show("Сделать выбранную запись действующей?",
                                    "Восстановление записи", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    Logging.StartFirstLevel(540);
                    Logging.Comment("Произведена смена статуса на активный  у прибора");
                    Logging.Comment("ID: " + zid);
                    Logging.Comment("Наименование прибора: " + _cName);
                    Logging.Comment("Аббревиатура прибора: " + _Abbr);
                    Logging.Comment("Единицы измерения: " + _unit);

                    Logging.Comment("Операцию выполнил: ID:" + Nwuram.Framework.Settings.User.UserSettings.User.Id
                                    + " ; ФИО:" + Nwuram.Framework.Settings.User.UserSettings.User.FullUsername);
                    Logging.StopFirstLevel();

                    proc.RestoreDevice(Convert.ToInt32(dgvDevices.CurrentRow.Cells["id"].Value), true, false);
                    dgvDevices_Load();
                }
            }
        }
Example #43
0
 public static void ConnectionClosed(IPEndPoint endpoint, string data)
 {
     Logging.Log("[RECEIVED] Connection closing.");
     CloseConnection(endpoint);
 }
Example #44
0
        /*++
         *  GenerateToken - Called after each successive state
         *  in the Client - Server handshake.  This function
         *  generates a set of bytes that will be sent next to
         *  the server.  The server responds, each response,
         *  is pass then into this function, again, and the cycle
         *  repeats until successful connection, or failure.
         *
         *  Input:
         *      input  - bytes from the wire
         *      output - ref to byte [], what we will send to the
         *          server in response
         *  Return:
         *      errorCode - an SSPI error code
         * --*/
        private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output)
        {
#if TRACE_VERBOSE
            GlobalLog.Enter("SecureChannel#" + Logging.HashString(this) + "::GenerateToken, _refreshCredentialNeeded = " + _refreshCredentialNeeded);
#endif

            if (offset < 0 || offset > (input == null ? 0 : input.Length))
            {
                GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::GenerateToken", "Argument 'offset' out of range.");
                throw new ArgumentOutOfRangeException("offset");
            }

            if (count < 0 || count > (input == null ? 0 : input.Length - offset))
            {
                GlobalLog.Assert(false, "SecureChannel#" + Logging.HashString(this) + "::GenerateToken", "Argument 'count' out of range.");
                throw new ArgumentOutOfRangeException("count");
            }

            SecurityBuffer   incomingSecurity        = null;
            SecurityBuffer[] incomingSecurityBuffers = null;

            if (input != null)
            {
                incomingSecurity        = new SecurityBuffer(input, offset, count, SecurityBufferType.Token);
                incomingSecurityBuffers = new SecurityBuffer[]
                {
                    incomingSecurity,
                    new SecurityBuffer(null, 0, 0, SecurityBufferType.Empty)
                };
            }

            SecurityBuffer outgoingSecurity = new SecurityBuffer(null, SecurityBufferType.Token);

            SecurityStatusPal errorCode = 0;

            bool   cachedCreds = false;
            byte[] thumbPrint  = null;

            //
            // Looping through ASC or ISC with potentially cached credential that could have been
            // already disposed from a different thread before ISC or ASC dir increment a cred ref count.
            //
            try
            {
                do
                {
                    thumbPrint = null;
                    if (_refreshCredentialNeeded)
                    {
                        cachedCreds = _serverMode
                                        ? AcquireServerCredentials(ref thumbPrint)
                                        : AcquireClientCredentials(ref thumbPrint);
                    }

                    if (_serverMode)
                    {
                        errorCode = SslStreamPal.AcceptSecurityContext(
                            ref _credentialsHandle,
                            ref _securityContext,
                            incomingSecurity,
                            outgoingSecurity,
                            _remoteCertRequired);
                    }
                    else
                    {
                        if (incomingSecurity == null)
                        {
                            errorCode = SslStreamPal.InitializeSecurityContext(
                                ref _credentialsHandle,
                                ref _securityContext,
                                _destination,
                                incomingSecurity,
                                outgoingSecurity);
                        }
                        else
                        {
                            errorCode = SslStreamPal.InitializeSecurityContext(
                                _credentialsHandle,
                                ref _securityContext,
                                _destination,
                                incomingSecurityBuffers,
                                outgoingSecurity);
                        }
                    }
                } while (cachedCreds && _credentialsHandle == null);
            }
            finally
            {
                if (_refreshCredentialNeeded)
                {
                    _refreshCredentialNeeded = false;

                    //
                    // Assuming the ISC or ASC has referenced the credential,
                    // we want to call dispose so to decrement the effective ref count.
                    //
                    if (_credentialsHandle != null)
                    {
                        _credentialsHandle.Dispose();
                    }

                    //
                    // This call may bump up the credential reference count further.
                    // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert.
                    //
                    if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid)
                    {
                        SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
                    }
                }
            }

            output = outgoingSecurity.token;

#if TRACE_VERBOSE
            GlobalLog.Leave("SecureChannel#" + Logging.HashString(this) + "::GenerateToken()", Interop.MapSecurityStatus((uint)errorCode));
#endif
            return((SecurityStatusPal)errorCode);
        }
Example #45
0
 public void Start()
 {
     try
     {
         /*Stopwatch timer = Stopwatch.StartNew();
          * var hbProfile = XmlSerializer.Deserialize<HBProfile>(Application.StartupPath + @"\[A - Quest] EK 12-58 [Kick].xml");
          * if (hbProfile.Items == null || !hbProfile.Items.Any())
          * {
          *  return;
          * }
          * int count = hbProfile.Items.Length;
          * if (count > hbProfile.ItemsElementName.Length)
          *  count = hbProfile.ItemsElementName.Length;
          * for (int i = 0; i < count; i++)
          * {
          *  ItemsChoiceType2 name = hbProfile.ItemsElementName[i];
          *  object value = hbProfile.Items[i];
          *  Logging.Write(name + ": " + value);
          *  if (value.ToString().Contains("Profiles_Converters.Converters"))
          *  {
          *      if (value is Vendors)
          *      {
          *          var vendors = value as Vendors;
          *          foreach (VendorType vendor in vendors.Items)
          *          {
          *              Logging.Write(vendor.Entry + ";" + vendor.Name + ";" + vendor.Nav + ";" + vendor.Type + ";" + vendor.X + ";" + vendor.Y + ";" + vendor.Z);
          *          }
          *      }
          *      else if (value is Mailboxes)
          *      {
          *          var mailboxes = value as Mailboxes;
          *          foreach (MailboxType mailbox in mailboxes.Items)
          *          {
          *              Logging.Write(mailbox.Nav + ";" + mailbox.X + ";" + mailbox.Y + ";" + mailbox.Z);
          *          }
          *      }
          *      else if (value is Blackspots)
          *      {
          *          var blackspots = value as Blackspots;
          *          foreach (BlackspotType blackspot in blackspots.Blackspot)
          *          {
          *              _tnbProfile.Blackspots.Add(new QuesterBlacklistRadius
          *              {
          *                  Position = new Point {X = blackspot.X, Y = blackspot.Y, Z = blackspot.Z, Type = ""},
          *                  Radius = blackspot.Radius
          *              });
          *              //Logging.Write(blackspot.X + ";" + blackspot.Y + ";" + blackspot.Z + ";" + blackspot.Radius + ";" + blackspot.Height);
          *          }
          *      }
          *          // avoidmob dosn't gather a valid Entry yet.
          *      else if (value is AvoidMobs)
          *      {
          *          var avoidMobs = value as AvoidMobs;
          *          foreach (MobType avoidMob in avoidMobs.Items)
          *          {
          *              _tnbProfile.AvoidMobs.Add(new Npc
          *              {
          *                  Entry = (int) avoidMob.Id,
          *                  Name = avoidMob.Name
          *              });
          *              //Logging.Write(avoidMob.Entry + ";" + avoidMob.Name);
          *          }
          *      }
          *      else if (value is Quest && (value as Quest).Id != null) // if id = null, then we are parsing the QuestOrder.
          *      {
          *          var quest = value as Quest;
          *          var tmpQuest = new Quester.Profile.Quest();
          *          tmpQuest.Id = quest.Id != null ? Others.ToInt32(quest.Id) : 0;
          *          tmpQuest.Name = quest.Name;
          *          Logging.Write(quest.Id + ";" + quest.Name);
          *          if (quest.Items.Length <= 0)
          *              return;
          *          foreach (object qContent in quest.Items)
          *          {
          *              if (qContent is ObjectiveMetaType)
          *              {
          *                  tmpQuest.Objectives.Add(getValidObjective(qContent as ObjectiveMetaType));
          *              }
          *          }
          *          bool found = false;
          *          foreach (Quester.Profile.Quest tmpQ in _tnbProfile.Quests)
          *          {
          *              if (tmpQ.Id == tmpQuest.Id)
          *              {
          *                  found = true;
          *                  break;
          *              }
          *          }
          *          if (!found)
          *              _tnbProfile.Quests.Add(tmpQuest);
          *      }
          *      else
          *      {
          *          if (value is QuestOrderType)
          *          {
          *              var questOrder = value as QuestOrderType;
          *              AnalyzeDeeper(questOrder);
          *          }
          *      }
          *  }
          * }
          * if (_pickUpList.Count > 0)
          * {
          *  foreach (Quester.Profile.Quest tnbQuest in _tnbProfile.Quests)
          *  {
          *      foreach (var keyValuePair in _pickUpList)
          *      {
          *          if (keyValuePair.Key == tnbQuest.Id && tnbQuest.PickUp == 0)
          *          {
          *              tnbQuest.PickUp = (int) keyValuePair.Value;
          *          }
          *      }
          *  }
          * }
          * if (_itemPickUpList.Count > 0)
          * {
          *  foreach (Quester.Profile.Quest tnbQuest in _tnbProfile.Quests)
          *  {
          *      foreach (var keyValuePair in _itemPickUpList)
          *      {
          *          if (keyValuePair.Key == tnbQuest.Id && tnbQuest.ItemPickUp == 0)
          *          {
          *              tnbQuest.ItemPickUp = (int) keyValuePair.Value;
          *          }
          *      }
          *  }
          * }
          * if (_turnInList.Count > 0)
          * {
          *  foreach (Quester.Profile.Quest tnbQuest in _tnbProfile.Quests)
          *  {
          *      foreach (var keyValuePair in _turnInList)
          *      {
          *          if (keyValuePair.Key == tnbQuest.Id && tnbQuest.TurnIn == 0)
          *          {
          *              tnbQuest.TurnIn = (int) keyValuePair.Value;
          *          }
          *      }
          *  }
          * }
          * if (_tnbTmpNpcList.Count > 0)
          * {
          *  foreach (Npc tmpNPC in _tnbTmpNpcList)
          *  {
          *      bool found = false;
          *      foreach (Npc npc in _tnbProfile.Questers)
          *      {
          *          if (npc.Entry == tmpNPC.Entry && npc.Position.X == tmpNPC.Position.X)
          *              found = true;
          *      }
          *      if (!found)
          *          _tnbProfile.Questers.Add(tmpNPC);
          *  }
          * }
          * var questsToRemove = new List<Quester.Profile.Quest>();
          * foreach (Quester.Profile.Quest q in _tnbProfile.Quests)
          * {
          *  if (q.MinLevel == 0 || q.MaxLevel == 0 || q.QuestLevel == 0)
          *  {
          *      WowHead.QuestInfo qInfo = WowHead.GetQuestObject(q.Id);
          *      if (!qInfo.IsValid)
          *      {
          *          questsToRemove.Add(q);
          *          continue;
          *      }
          *      q.MinLevel = qInfo.ReqMinLevel;
          *      q.MaxLevel = qInfo.ReqMaxLevel;
          *      q.QuestLevel = qInfo.Level;
          *      if (q.TurnIn == 0)
          *          q.TurnIn = qInfo.TurnIn;
          *      if (q.PickUp == 0)
          *          q.PickUp = qInfo.PickUp;
          *      if (qInfo.Race != 0)
          *          q.RaceMask = qInfo.Race;
          *      else if (qInfo.Side != 0 && q.RaceMask == 0)
          *      {
          *          if (qInfo.Side == 1)
          *          {
          *              q.RaceMask = 16778317;
          *          }
          *          else if (qInfo.Side == 2)
          *          {
          *              q.RaceMask = 33555378;
          *          }
          *          else if (qInfo.Side == 3)
          *          {
          *              q.RaceMask = 50333695; // or not set
          *          }
          *      }
          *      if (qInfo.Classs != 0)
          *          q.ClassMask = qInfo.Classs;
          *      Logging.Write("Update quest: " + q.Name + "(" + q.Id + "), questLevel = " + q.QuestLevel + ", minLevel = " + q.MinLevel + ", maxLevel = " + q.MaxLevel + ", raceMask = " + q.RaceMask +
          *                    ", classMask = " + q.ClassMask);
          *  }
          *  bool turnInfound = false;
          *  bool pickUpfound = false;
          *  foreach (Npc npc in _tnbProfile.Questers)
          *  {
          *      if (q.TurnIn != 0 && npc.Entry == q.TurnIn)
          *      {
          *          turnInfound = true;
          *          if (pickUpfound)
          *              break;
          *      }
          *      if (q.PickUp != 0 && npc.Entry == q.PickUp)
          *      {
          *          pickUpfound = true;
          *          if (turnInfound)
          *              break;
          *      }
          *  }
          *  if (!turnInfound && q.TurnIn != 0)
          *  {
          *      Npc npw = QuestersDB.GetNpcByEntry(q.TurnIn);
          *      if (npw.Entry > 0)
          *      {
          *          _tnbProfile.Questers.Add(npw);
          *          Logging.Write("Add Quester entry " + q.TurnIn + " for Quest " + q.Name + " from QuestersDB.");
          *      }
          *      else
          *          Logging.WriteError("Quester id: " + q.TurnIn + " not found in QuestersDB.");
          *  }
          *  if (!pickUpfound && q.PickUp != 0 && q.TurnIn != q.PickUp)
          *  {
          *      Npc npw = QuestersDB.GetNpcByEntry(q.PickUp);
          *      if (npw.Entry > 0)
          *      {
          *          _tnbProfile.Questers.Add(npw);
          *          Logging.Write("Add Quester entry " + q.TurnIn + " for Quest " + q.Name + " from QuestersDB.");
          *      }
          *      else
          *      {
          *          Logging.WriteError("Quester id: " + q.PickUp + " not found in QuestersDB.");
          *      }
          *  }
          * }
          * XmlSerializer.Serialize(Application.StartupPath + @"\test_TNB_Extract.xml", _tnbProfile);
          * XmlSerializer.Serialize(Application.StartupPath + @"\test_HB_ReExtract.xml", hbProfile);
          * MessageBox.Show(timer.ElapsedMilliseconds.ToString());*/
         formMain = new MainForm();
         formMain.Show();
         _isStarted = true;
         Others.ProductStatusLog(Products.ProductName, 4);
     }
     catch (Exception e)
     {
         Logging.WriteError("Profiles Converters > Main > Start(): " + e);
     }
 }
Example #46
0
 public App(IPlatformInitializer initializer = null) : base(initializer)
 {
     Logging.ReleaseTag = false;
     Logging.Debug("Start app.", Logging.Level.DATABASE);
     VBook.Database = Database;
 }
Example #47
0
        private void btAdd_Click(object sender, EventArgs e)
        {
            string  num = "";
            decimal?AreaS;

            if (tbAreaNew.Text == Area)
            {
                AreaS = null;
            }
            else
            {
                AreaS = decimal.Parse(tbAreaNew.Text);
            }

            if (tbNumber.Text == "")
            {
                num = null;
            }
            else
            {
                num = tbNumber.Text;
            }

            if (cbTypeDoc.Text == "")
            {
                MessageBox.Show("Не выбран тип доп. документа.\nСохранение невозможно", "Сохранение доп.документа",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if ((tbAreaNew.Visible == true) && (tbAreaNew.Text == Area))
            {
                MessageBox.Show("Не заполнено поле \"Общ. площадь\".\nСохранение невозможно", "Сохранение доп.документа",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (CheckDate())
            {
                return;
            }

            DateTime?prolong;

            if (dateren.Visible == true)
            {
                prolong = dateren.Value;
            }
            else
            {
                prolong = null;
            }

            DateTime?departureDate;

            if (dtpDeparture.Visible == true)
            {
                departureDate = dtpDeparture.Value;
            }
            else
            {
                departureDate = null;
            }

            if (dtpOutDate.Visible)
            {
                departureDate = dtpOutDate.Value.Date;
            }

            string comment = null;

            if (tbComment.Visible)
            {
                comment = tbComment.Text;
            }



            _proc.AddeditTD(1, _id, Convert.ToDateTime(dateadddoc.Text), _id_type_doc, num, prolong, AreaS, departureDate, comment, id_PetitionLeave);

            Logging.StartFirstLevel(1402);
            //Logging.Comment("ID: " + id_DopDoc);
            Logging.Comment("№ документа: " + num);
            Logging.Comment("Тип документа ID: " + _id_type_doc + " ; Наименование: " + cbTypeDoc.Text);
            Logging.Comment("Дата документа: " + dateadddoc.Value.ToShortDateString());

            Logging.Comment("Данные арендатора, к которому добавляется доп.документ");
            Logging.Comment("Дата заключения договора: " + oldDoc.ToShortDateString());
            Logging.Comment("Номер договора: " + num_doc);
            Logging.Comment("Арендатор ID: " + _old_id_ten + "; Наименование: " + oldTen);
            Logging.Comment("Арендодатель ID: " + _old_id_lord + "; Наименование: " + oldLord);


            if (dateren.Visible)
            {
                Logging.Comment($"{label4.Text}: {dateren.Value.ToShortDateString()}");
            }
            if (dtpDeparture.Visible)
            {
                Logging.Comment($"{lblDeparture.Text}: {dtpDeparture.Value.ToShortDateString()}");
            }
            if (dtpOutDate.Visible)
            {
                Logging.Comment($"{label3.Text}: {dtpOutDate.Value.ToShortDateString()}");
            }
            if (tbAreaNew.Visible)
            {
                Logging.Comment($"{lblAreaNew.Text}: {tbAreaNew.Text}");
            }
            if (tbComment.Visible)
            {
                Logging.Comment($"{label4.Text}: {tbComment.Text}");
            }



            Logging.Comment("Операцию выполнил: ID:" + Nwuram.Framework.Settings.User.UserSettings.User.Id
                            + " ; ФИО:" + Nwuram.Framework.Settings.User.UserSettings.User.FullUsername);
            Logging.StopFirstLevel();

            MessageBox.Show("Данные сохранены.", "Сохранение доп.документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
            DialogResult = DialogResult.Cancel;
        }
        //
        // Builds up stats about Jira usage
        //
        public static JiraStatistics GetJiraStatistics(SvnLogs.Log[] revisionLogs, Simple credentials, Logging logger, StatisticGenerated statsGenerated)
        {
            // Track our updates
            Object writeLock     = new object();
            int    revisionCount = 0;

            int commitsWithoutJira = 0;

            ConcurrentDictionary <string, UInt64> validJiras   = new ConcurrentDictionary <string, ulong>();
            ConcurrentDictionary <string, UInt64> invalidJiras = new ConcurrentDictionary <string, ulong>();

            // We need to spin through every review and pull out the information about each one
            logger.Log("Starting to pull out the Jira stats from the given revision list");
            ParallelLoopResult result = Parallel.ForEach(revisionLogs, new ParallelOptions {
                MaxDegreeOfParallelism = 1
            }, (thisRevision, loopState) =>
            {
                // Assume no Jira until we have one
                bool noJira = true;

                // Get the Jira line
                string jiraLine = thisRevision.Message.FirstOrDefault(line =>
                {
                    return(line.Contains(@"[Jira Issue(s):"));
                });

                // Do we have one?
                if (string.IsNullOrEmpty(jiraLine) == false && jiraLine.Contains(@"N/A") == false)
                {
                    // Pull out the Jira information
                    string[] splitIssuesLine = jiraLine.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);

                    // We need two, the description and the Jira
                    if (splitIssuesLine.Length == 2)
                    {
                        // Ok, this is something we should be able to use...
                        // Get rid of the [] which might exist at the moment
                        string jirasOnly         = splitIssuesLine[1].Replace("[", "").Replace("]", "").Replace(" ", "");
                        string[] individualJiras = jirasOnly.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                        // Check the Jira is valid
                        foreach (string thisJira in individualJiras)
                        {
                            // Note we have a Jira now
                            noJira = false;

                            // Check if we track this as valid or invalid
                            bool isJiraValid = false;
                            try
                            {
                                isJiraValid = RB_Tools.Shared.Targets.Jira.ValidateJiraTicker(credentials, thisJira);
                            }
                            catch (Exception)
                            {
                                // It's not valid
                            }

                            // Get the dictionary and update it
                            ConcurrentDictionary <string, UInt64> dictionaryToUpdate = isJiraValid == true ? validJiras : invalidJiras;
                            dictionaryToUpdate.AddOrUpdate(thisJira, 1, (jira, count) =>
                            {
                                return(++count);
                            });
                        }
                    }
                }

                // Continue?
                if (loopState.IsStopped == false)
                {
                    // Update
                    lock (writeLock)
                    {
                        logger.Log("Updating Jira properties");

                        // Update our stats
                        if (noJira)
                        {
                            ++commitsWithoutJira;
                        }

                        // Update
                        statsGenerated(++revisionCount);
                    }
                }
            });

            return(new JiraStatistics(commitsWithoutJira, revisionLogs.Length - commitsWithoutJira, validJiras, invalidJiras));
        }
Example #49
0
 private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
 {
     Logging.Log("Application_ThreadException", e.Exception.ToString());
     Application.Exit();
 }
Example #50
0
        public void OnCommand(EnsoCommand ensoCommand, string postfix, IntPtr foregroundWindowForGrab)
        {
            Logging.AddDebugLog("OnCommand:" + ensoCommand.Name + " postfix:" + postfix + "------------------------------------------------------------------------------------------------");
            try
            {
                //SelectionListener.Listener.Current.IfOpenedPause();

                MergedCommand mergedCommand = this.mergedCommands[ensoCommand.Name];

                //if none of potentially chosen commands use selection skip expensive operations:
                //  this.service.GetFileSelection() and/or this.service.GetUnicodeSelection();
                bool skipGetUnicodeSelection = true;
                bool skipGetFileSelection    = true;
                foreach (var sourceCommand in mergedCommand.sourceCommands)
                {
                    if (sourceCommand.canUseTextSelectionForParameter)
                    {
                        skipGetUnicodeSelection = false;
                    }

                    if (sourceCommand.canUseFileSelectionForParameter)
                    {
                        skipGetFileSelection = false;
                    }

                    if (!skipGetUnicodeSelection && !skipGetFileSelection)
                    {
                        break;
                    }
                }
                Logging.AddDebugLog("OnCommand: skipGetUnicodeSelection=" + skipGetUnicodeSelection + " skipGetFilesSelection=" + skipGetFileSelection);

                //do we need file selection?
                if ((ensoCommand.Name == "topen" || ensoCommand.Name == "rtopen" || ensoCommand.Name == "empty"))
                {
                    try
                    {
                        if (CraftSynth.BuildingBlocks.WindowsNT.Misc.GetForegroundWindowCaption().Contains("Total Commander"))
                        {
                            skipGetFileSelection = true;
                        }
                    }
                    catch
                    {
                    }
                }

                //read selection
                ClipboardData selectedData = null;
                if (!skipGetUnicodeSelection || !skipGetFileSelection)
                {
                    selectedData = HandlerForSelection.Get(foregroundWindowForGrab);
                }
                Logging.AddDebugLog("OnCommand: first 100 chars of HandlerForSelection.Get=" + (selectedData == null?"null":selectedData.AsUnicodeText).FirstXChars(100, "..."));

                //Get text selection if needed
                string selectedText = null;
                if (!skipGetUnicodeSelection && selectedData != null)
                {
                    selectedText = selectedData.AsUnicodeText;
                }
                Logging.AddDebugLog("OnCommand: first 100 chars of selectedText=" + (selectedText ?? "null").FirstXChars(100, "..."));

                //Get file selection if needed
                string[] fileSelectionArray = null;
                if (!skipGetFileSelection &&
                    !skipGetUnicodeSelection && string.IsNullOrEmpty(selectedText) && selectedData != null)
                {
                    var ffl = selectedData.AsFileFolderList;
                    if (ffl == null)
                    {
                        fileSelectionArray = null;
                    }
                    else
                    {
                        fileSelectionArray = ffl.ToArray();
                    }
                    ;     //ex: this.service.GetFileSelection();
                }
                else
                {
                    fileSelectionArray = new string[] { };
                }
                Logging.AddDebugLog("OnCommand: first 100 chars of fileSelectionArray=" + (fileSelectionArray == null? "null": Syntax.FileSelectionArrayToString(fileSelectionArray)).FirstXChars(100, "..."));

                if (fileSelectionArray != null && fileSelectionArray.Length > 0 && string.IsNullOrEmpty(selectedText))
                {
                    selectedText = Syntax.FileSelectionArrayToString(fileSelectionArray);
                }

                Command bestCandidateForUsedCommand = null;
                bool    bestCandidateForUsedCommandRequiresParameterInput = false;
                foreach (Command sourceCommand in mergedCommand.sourceCommands)
                {
                    Logging.AddDebugLog("OnCommand: Syntax.ExtractParameterValues...");
                    int           parameterCountInSyntax      = 0;
                    List <string> parametersFromInlineCommand = Syntax.ExtractParameterValues(sourceCommand.Postfix, postfix, (GetSelectionForCommand(selectedText, sourceCommand)), mergedCommand.sourceCommands.Count == 1, out parameterCountInSyntax);

                    Logging.AddDebugLog("OnCommand: parametersFromInlineCommand=" + (parametersFromInlineCommand == null?"null":parametersFromInlineCommand.ToCSV()));
                    if (parametersFromInlineCommand == null)
                    {
                        continue;
                    }

                    //replace jockers - should be refactored
                    Logging.AddDebugLog("OnCommand: replace jockers...");
                    int i = parametersFromInlineCommand.Count - 1;
                    while (i >= 0)
                    {
                        if (parametersFromInlineCommand[i] == Syntax.lastMessageInPostfix)
                        {
                            parametersFromInlineCommand[i] = MessagesHandler.GetLastFromHistory().Text;
                        }
                        else if (parametersFromInlineCommand[i] == Syntax.selectionInPostfix1 || parametersFromInlineCommand[i] == Syntax.selectionInPostfix2)
                        {
                            parametersFromInlineCommand.RemoveAt(i);
                        }
                        i--;
                    }
                    Logging.AddDebugLog("OnCommand: Determine best candidate...");

                    if ((GetSelectionForCommand(selectedText, sourceCommand) == string.Empty && parametersFromInlineCommand.Count == parameterCountInSyntax) ||
                        (parameterCountInSyntax == 0 && sourceCommand.Postfix == " ") ||
                        (GetSelectionForCommand(selectedText, sourceCommand) != string.Empty && parametersFromInlineCommand.Count == parameterCountInSyntax && GetSelectionForCommand(selectedText, sourceCommand).CompareTo(parametersFromInlineCommand[parametersFromInlineCommand.Count - 1]) == 0))
                    {
                        bestCandidateForUsedCommand = sourceCommand.GetClone();
                        bestCandidateForUsedCommand.parametersOnExecute   = StringWorkItem.CreateInstances(parametersFromInlineCommand);
                        bestCandidateForUsedCommandRequiresParameterInput = false;
                        Logging.AddDebugLog("OnCommand: bc=a");
                        break;
                    }
                    else if (GetSelectionForCommand(selectedText, sourceCommand) != string.Empty && parametersFromInlineCommand.Count == parameterCountInSyntax && GetSelectionForCommand(selectedText, sourceCommand).CompareTo(parametersFromInlineCommand[parametersFromInlineCommand.Count - 1]) != 0)
                    {
                        bestCandidateForUsedCommand = sourceCommand.GetClone();
                        bestCandidateForUsedCommand.parametersOnExecute   = StringWorkItem.CreateInstances(parametersFromInlineCommand);
                        bestCandidateForUsedCommandRequiresParameterInput = false;
                        Logging.AddDebugLog("OnCommand: bc=b");
                    }
                    else if (parametersFromInlineCommand.Count == (parameterCountInSyntax - 1))
                    {
                        bestCandidateForUsedCommand = sourceCommand.GetClone();
                        bestCandidateForUsedCommand.parametersOnExecute   = StringWorkItem.CreateInstances(parametersFromInlineCommand);
                        bestCandidateForUsedCommandRequiresParameterInput = true;
                        Logging.AddDebugLog("OnCommand: bc=c");
                    }
                }



                if (bestCandidateForUsedCommand == null)
                {
                    Logging.AddDebugLog("OnCommand: postfix Invalid!");
                    MessagesHandler.Display("Postfix invalid!", ensoCommand.Name + " " + ensoCommand.Postfix);
                }
                else
                {
                    Logging.AddDebugLog("OnCommand: bestCandidateForUsedCommand=" + bestCandidateForUsedCommand.Name);
                    Logging.AddDebugLog("OnCommand: replace 'last' parameter with last used parameter/WorkItem");
                    //replace 'last' parameter with last used parameter/WorkItem
                    int j = 0;
                    while (j < bestCandidateForUsedCommand.parametersOnExecute.Count)
                    {
                        Logging.AddDebugLog("OnCommand: first 100 chars of paramsOnExecute[" + j + "]=" + (bestCandidateForUsedCommand.parametersOnExecute[j].GetValueAsText().FirstXChars(100, "...")));
                        if (bestCandidateForUsedCommand.parametersOnExecute[j].GetValueAsText() == Syntax.lastParameterInPostfix)
                        {
                            bestCandidateForUsedCommand.parametersOnExecute[j] = WorkItemsProviders.CommandsHistory.CommandsHistory.GetLastWorkItem();
                            Logging.AddDebugLog("OnCommand: first 100 chars of paramsOnExecute[" + j + "]=" + bestCandidateForUsedCommand.parametersOnExecute[j].GetValueAsText().FirstXChars(100, "..."));
                        }

                        j++;
                    }

                    if (bestCandidateForUsedCommand.parameterInputArguments.acceptOnlySuggested && !bestCandidateForUsedCommandRequiresParameterInput && bestCandidateForUsedCommand.parametersOnExecute.Count > 0)
                    {//user entered all parameters and command uses cloased parameter group
                        Logging.AddDebugLog("OnCommand: user entered all parameters and command uses cloased parameter group");
                        Dictionary <string, IWorkItem> suggestions = GetAvailableSuggestions(bestCandidateForUsedCommand);
                        IWorkItem selectedSuggestion = null;
                        if (suggestions.TryGetValue(bestCandidateForUsedCommand.parametersOnExecute[bestCandidateForUsedCommand.parametersOnExecute.Count - 1].GetCaption(), out selectedSuggestion))
                        {//user-entered parameter does not exist in group - add it to list
                            Logging.AddDebugLog("OnCommand: user-entered parameter does not exist in group - add it to list");
                            IWorkItem postProcessedSuggestion = PostProcessSelectedSuggestion(selectedSuggestion);
                            if (postProcessedSuggestion == null)
                            {//user probably canceled command - abort command
                                Logging.AddDebugLog("OnCommand: user probably canceled command - abort command");
                                return;
                            }
                            bestCandidateForUsedCommand.parametersOnExecute[bestCandidateForUsedCommand.parametersOnExecute.Count - 1] = postProcessedSuggestion;
                        }
                        else
                        {//user-entered parameter does not exist in group - plan input parameter box
                            Logging.AddDebugLog("OnCommand: user-entered parameter does not exist in group - plan input parameter box");
                            if (bestCandidateForUsedCommand.parameterInputArguments.acceptOnlySuggested)
                            {
                                bestCandidateForUsedCommand.parameterInputArguments.predefinedValue = string.Empty;
                            }
                            else
                            {
                                bestCandidateForUsedCommand.parameterInputArguments.predefinedValue = bestCandidateForUsedCommand.parametersOnExecute[bestCandidateForUsedCommand.parametersOnExecute.Count - 1].GetCaption();
                            }
                            bestCandidateForUsedCommand.parametersOnExecute.RemoveAt(bestCandidateForUsedCommand.parametersOnExecute.Count - 1);
                            bestCandidateForUsedCommandRequiresParameterInput = true;
                        }
                    }

                    if (!bestCandidateForUsedCommandRequiresParameterInput)
                    {
                        Logging.AddDebugLog("OnCommand: bestCandidateForUsedCommandRequiresParameterInput==false");
                        Logging.AddDebugLog("OnCommand: ExecuteCommandCandidate...");
                        ExecuteCommandCandidate(bestCandidateForUsedCommand);
                    }
                    else
                    {
                        Logging.AddDebugLog("OnCommand: ProcessingBeforeParameterInput...");
                        bool cancel = false;
                        bestCandidateForUsedCommand.provider.ProcessingBeforeParameterInput(bestCandidateForUsedCommand, ref cancel);
                        Logging.AddDebugLog("OnCommand: ProcessingBeforeParameterInput done. cancel=" + cancel);
                        if (cancel)
                        {
                            return;
                        }

                        Logging.AddDebugLog("OnCommand: GetAvailableSuggestions...");
                        Dictionary <string, IWorkItem> suggestions = GetAvailableSuggestions(bestCandidateForUsedCommand);

                        //prepare parameters to suggestions
                        bestCandidateForUsedCommand.parameterInputArguments.suggestions = new List <string>();
                        foreach (var suggestion in suggestions)
                        {
                            bestCandidateForUsedCommand.parameterInputArguments.suggestions.Add(suggestion.Key);
                        }

                        //execute dropbox
                        Logging.AddDebugLog("OnCommand: execute dropbox...");
                        try
                        {
                            PostParameterInputArguments contextData = new PostParameterInputArguments();
                            contextData.suggestions = suggestions;
                            contextData.bestCandidateForUsedCommand = bestCandidateForUsedCommand;
                            contextData.bestCandidateForUsedCommandRequiresParameterInput = bestCandidateForUsedCommandRequiresParameterInput;

                            ParameterInput.Display(bestCandidateForUsedCommand.parameterInputArguments, ParameterInput_OnClose, contextData, Screen.FromPoint(Cursor.Position));
                        }
                        catch (Exception exception)
                        {
                            MessagesHandler.Display("Error", exception.Message);
                            Logging.AddErrorLog("Parameter input failed: " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                            Common.Logging.AddExceptionLog(exception);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logging.AddErrorLog("Command execution failed: " + exception.Message + ((exception.InnerException != null) ? ":" + exception.InnerException.Message : ""));
                Logging.AddExceptionLog(exception);
                throw exception;
            }
            //SelectionListener.Listener.Current.IfOpenedContinue();
        }
        private void OnDrawingEndScene(EventArgs args)
        {
            try
            {
                if (Drawing.Direct3DDevice == null || Drawing.Direct3DDevice.IsDisposed ||
                    !this.Menu.Item("LastPosition.Enabled").IsActive())
                {
                    return;
                }

                var map             = this.Menu.Item("LastPosition.Map").IsActive();
                var minimap         = this.Menu.Item("LastPosition.Minimap").IsActive();
                var ssCircle        = this.Menu.Item("LastPosition.SSCircle").IsActive();
                var circleThickness = this.Menu.Item("LastPosition.CircleThickness").GetValue <Slider>().Value;
                var circleColor     = this.Menu.Item("LastPosition.CircleColor").GetValue <Circle>();
                var totalSeconds    = this.Menu.Item("LastPosition.TimeFormat").GetValue <StringList>().SelectedIndex == 1;
                var timerOffset     = this.Menu.Item("LastPosition.SSTimerOffset").GetValue <Slider>().Value;
                var timer           = this.Menu.Item("LastPosition.SSTimer").IsActive();


                this.sprite.Begin(SpriteFlags.AlphaBlend);
                foreach (var lp in this.lastPositions)
                {
                    if (!lp.Hero.IsDead && !lp.LastPosition.Equals(Vector3.Zero) &&
                        lp.LastPosition.Distance(lp.Hero.Position) > 500)
                    {
                        lp.Teleported = false;
                        lp.LastSeen   = Game.Time;
                    }
                    lp.LastPosition = lp.Hero.Position;
                    if (lp.Hero.IsVisible)
                    {
                        lp.Teleported = false;
                        if (!lp.Hero.IsDead)
                        {
                            lp.LastSeen = Game.Time;
                        }
                    }
                    if (!lp.Hero.IsVisible && !lp.Hero.IsDead)
                    {
                        var pos   = lp.Teleported ? this.spawnPoint : lp.LastPosition;
                        var mpPos = Drawing.WorldToMinimap(pos);
                        var mPos  = Drawing.WorldToScreen(pos);

                        if (ssCircle && !lp.LastSeen.Equals(0f) && Game.Time - lp.LastSeen > 3f)
                        {
                            var radius = Math.Abs((Game.Time - lp.LastSeen - 1) * lp.Hero.MoveSpeed * 0.9f);
                            if (radius <= 8000)
                            {
                                if (map && pos.IsOnScreen(50))
                                {
                                    Render.Circle.DrawCircle(
                                        pos,
                                        radius,
                                        circleColor.Color,
                                        circleThickness,
                                        true);
                                }
                                if (minimap)
                                {
                                    this.DrawCircleMinimap(pos, radius, circleColor.Color, circleThickness);
                                }
                            }
                        }

                        if (map && pos.IsOnScreen(50))
                        {
                            this.sprite.DrawCentered(this.heroTextures[lp.Hero.NetworkId], mPos);
                        }
                        if (minimap)
                        {
                            this.sprite.DrawCentered(this.heroTextures[lp.Hero.NetworkId], mpPos);
                        }

                        if (lp.IsTeleporting)
                        {
                            if (map && pos.IsOnScreen(50))
                            {
                                this.sprite.DrawCentered(this.teleportTexture, mPos);
                            }
                            if (minimap)
                            {
                                this.sprite.DrawCentered(this.teleportTexture, mpPos);
                            }
                        }

                        if (timer && !lp.LastSeen.Equals(0f) && Game.Time - lp.LastSeen > 3f)
                        {
                            var time = (Game.Time - lp.LastSeen).FormatTime(totalSeconds);
                            if (map && pos.IsOnScreen(50))
                            {
                                this.text.DrawTextCentered(
                                    time,
                                    new Vector2(mPos.X, mPos.Y + 15 + timerOffset),
                                    Color.White);
                            }
                            if (minimap)
                            {
                                this.text.DrawTextCentered(
                                    time,
                                    new Vector2(mpPos.X, mpPos.Y + 15 + timerOffset),
                                    Color.White);
                            }
                        }
                    }
                }
                this.sprite.End();
            }
            catch (Exception e)
            {
                Logging.AddEntry(LoggingEntryType.Error, "@LastPositionTracker.cs: An error occurred: {0}", e);
            }
        }
Example #52
0
 // 日志文件清理
 public void logFileClear()
 {
     Logging.Clear();
 }
Example #53
0
        /// <summary>
        ///
        /// </summary>
        public static void SyncBlockStateSend(ulong steamId, NanobotBuildAndRepairSystemBlock system)
        {
            if (!MyAPIGateway.Session.IsServer)
            {
                return;
            }
            if (!MyAPIGateway.Multiplayer.MultiplayerActive)
            {
                return;
            }


            var msgSnd = new MsgBlockState();

            msgSnd.EntityId = system.Entity.EntityId;
            msgSnd.State    = system.State.GetTransmit();

            var res = false;

            if (steamId == 0)
            {
                if (Mod.Log.ShouldLog(Logging.Level.Communication))
                {
                    Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockStateSend to others EntityId={0}/{1}, State={2}", system.Entity.EntityId, Logging.BlockName(system.Entity, Logging.BlockNameOptions.None), msgSnd.State.ToString());
                }
                res = MyAPIGateway.Multiplayer.SendMessageToOthers(MSGID_BLOCK_STATE_FROM_SERVER, MyAPIGateway.Utilities.SerializeToBinary(msgSnd), true);
            }
            else
            {
                if (Mod.Log.ShouldLog(Logging.Level.Communication))
                {
                    Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockStateSend to SteamId={0} EntityId={1}/{2}, State={3}", steamId, system.Entity.EntityId, Logging.BlockName(system.Entity, Logging.BlockNameOptions.None), msgSnd.State.ToString());
                }
                res = MyAPIGateway.Multiplayer.SendMessageTo(MSGID_BLOCK_STATE_FROM_SERVER, MyAPIGateway.Utilities.SerializeToBinary(msgSnd), steamId, true);
            }
            system.State.GetTransmit();

            if (!res && Mod.Log.ShouldLog(Logging.Level.Error))
            {
                Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockStateSend Failed");
            }
        }
Example #54
0
 private void LogBuffer(int size)
 {
     GlobalLog.Assert(Logging.On, "OverlappedAsyncResult#{0}::LogBuffer()|Logging is off!", Logging.HashString(this));
     if (size > -1)
     {
         if (_wsaBuffers != null)
         {
             foreach (WSABuffer wsaBuffer in _wsaBuffers)
             {
                 Logging.Dump(Logging.Sockets, AsyncObject, "PostCompletion", wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
                 if ((size -= wsaBuffer.Length) <= 0)
                 {
                     break;
                 }
             }
         }
         else
         {
             Logging.Dump(Logging.Sockets, AsyncObject, "PostCompletion", _singleBuffer.Pointer, Math.Min(_singleBuffer.Length, size));
         }
     }
 }
Example #55
0
        /// <summary>
        ///
        /// </summary>
        public static void SyncBlockSettingsSend(ulong steamId, NanobotBuildAndRepairSystemBlock block)
        {
            var msgSnd = new MsgBlockSettings();

            msgSnd.EntityId = block.Entity.EntityId;
            msgSnd.Settings = block.Settings.GetTransmit();

            var res = false;

            if (MyAPIGateway.Session.IsServer)
            {
                if (steamId == 0)
                {
                    if (Mod.Log.ShouldLog(Logging.Level.Communication))
                    {
                        Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockSettingsSend To Others EntityId={0}/{1}", block.Entity.EntityId, Logging.BlockName(block.Entity, Logging.BlockNameOptions.None));
                    }
                    res = MyAPIGateway.Multiplayer.SendMessageToOthers(MSGID_BLOCK_SETTINGS_FROM_SERVER, MyAPIGateway.Utilities.SerializeToBinary(msgSnd), true);
                }
                else
                {
                    if (Mod.Log.ShouldLog(Logging.Level.Communication))
                    {
                        Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockSettingsSend To SteamId={2} EntityId={0}/{1}", block.Entity.EntityId, Logging.BlockName(block.Entity, Logging.BlockNameOptions.None), steamId);
                    }
                    res = MyAPIGateway.Multiplayer.SendMessageTo(MSGID_BLOCK_SETTINGS_FROM_SERVER, MyAPIGateway.Utilities.SerializeToBinary(msgSnd), steamId, true);
                }
            }
            else
            {
                if (Mod.Log.ShouldLog(Logging.Level.Communication))
                {
                    Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockSettingsSend To Server EntityId={0}/{1} to Server", block.Entity.EntityId, Logging.BlockName(block.Entity, Logging.BlockNameOptions.None));
                }
                res = MyAPIGateway.Multiplayer.SendMessageToServer(MSGID_BLOCK_SETTINGS_FROM_CLIENT, MyAPIGateway.Utilities.SerializeToBinary(msgSnd), true);
            }
            if (!res && Mod.Log.ShouldLog(Logging.Level.Error))
            {
                Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockSettingsSend failed", Logging.BlockName(block.Entity, Logging.BlockNameOptions.None));
            }
        }
Example #56
0
        public override bool Start(Server server, Mode mode)
        {
            if (!Ready)
            {
                return(false);
            }
            File.WriteAllText("data\\last.json", JsonConvert.SerializeObject(new VMess.Config
            {
                inbounds = new List <VMess.Inbounds>
                {
                    new VMess.Inbounds
                    {
                        settings = new VMess.InboundSettings(),
                        port     = Global.Settings.Socks5LocalPort,
                        listen   = Global.Settings.LocalAddress
                    }
                },
                outbounds = new List <VMess.Outbounds>
                {
                    new VMess.Outbounds
                    {
                        settings = new VMess.OutboundSettings
                        {
                            vnext = new List <VMess.VNext>
                            {
                                new VMess.VNext
                                {
                                    address = server.Hostname,
                                    port    = server.Port,
                                    users   = new List <VMess.User>
                                    {
                                        new VMess.User
                                        {
                                            id       = server.UserID,
                                            alterId  = server.AlterID,
                                            security = server.EncryptMethod
                                        }
                                    }
                                }
                            }
                        },
                        streamSettings = new VMess.StreamSettings
                        {
                            network    = server.TransferProtocol,
                            security   = server.TLSSecure ? "tls" : "",
                            wsSettings = server.TransferProtocol == "ws"
                                ? new VMess.WebSocketSettings
                            {
                                path    = server.Path == "" ? "/" : server.Path,
                                headers = new VMess.WSHeaders
                                {
                                    Host = server.Host == "" ? server.Hostname : server.Host
                                }
                            }
                                : null,
                            tcpSettings = server.FakeType == "http"
                                ? new VMess.TCPSettings
                            {
                                header = new VMess.TCPHeaders
                                {
                                    type    = server.FakeType,
                                    request = new VMess.TCPRequest
                                    {
                                        path    = server.Path == "" ? "/" : server.Path,
                                        headers = new VMess.TCPRequestHeaders
                                        {
                                            Host = server.Host == "" ? server.Hostname : server.Host
                                        }
                                    }
                                }
                            }
                                : null,
                            kcpSettings = server.TransferProtocol == "kcp"
                                ? new VMess.KCPSettings
                            {
                                header = new VMess.TCPHeaders
                                {
                                    type = server.FakeType
                                }
                            }
                                : null,
                            quicSettings = server.TransferProtocol == "quic"
                                ? new VMess.QUICSettings
                            {
                                security = server.QUICSecure,
                                key      = server.QUICSecret,
                                header   = new VMess.TCPHeaders
                                {
                                    type = server.FakeType
                                }
                            }
                                : null,
                            httpSettings = server.TransferProtocol == "h2"
                                ? new VMess.HTTPSettings
                            {
                                host = server.Host == "" ? server.Hostname : server.Host,
                                path = server.Path == "" ? "/" : server.Path
                            }
                                : null,
                            tlsSettings = new VMess.TLSSettings
                            {
                                allowInsecure = true,
                                serverName    = server.Host == "" ? server.Hostname : server.Host
                            }
                        },
                        mux = new VMess.OutboundMux
                        {
                            enabled = server.UseMux
                        }
                    },
                    mode.Type == 0 || mode.Type == 1 || mode.Type == 2
                        ? new VMess.Outbounds
                    {
                        tag      = "TUNTAP",
                        protocol = "freedom"
                    }
                        : new VMess.Outbounds
                    {
                        tag      = "direct",
                        protocol = "freedom"
                    }
                },
                routing = new VMess.Routing
                {
                    rules = new List <VMess.RoutingRules>
                    {
                        mode.BypassChina
                            ? new VMess.RoutingRules
                        {
                            type = "field",
                            ip   = new List <string>
                            {
                                "geoip:cn",
                                "geoip:private"
                            },
                            domain = new List <string>
                            {
                                "geosite:cn"
                            },
                            outboundTag = "direct"
                        }
                            : new VMess.RoutingRules
                        {
                            type = "field",
                            ip   = new List <string>
                            {
                                "geoip:private"
                            },
                            outboundTag = "direct"
                        }
                    }
                }
            }));

            Instance = GetProcess("bin\\v2ray.exe");
            Instance.StartInfo.Arguments = "-config ..\\data\\last.json";

            Instance.OutputDataReceived += OnOutputDataReceived;
            Instance.ErrorDataReceived  += OnOutputDataReceived;

            State = State.Starting;
            Instance.Start();
            Instance.BeginOutputReadLine();
            Instance.BeginErrorReadLine();
            for (var i = 0; i < 1000; i++)
            {
                Thread.Sleep(10);

                if (State == State.Started)
                {
                    if (File.Exists("data\\last.json"))
                    {
                        File.Delete("data\\last.json");
                    }

                    return(true);
                }

                if (State == State.Stopped)
                {
                    Logging.Error("V2Ray 进程启动失败");

                    Stop();
                    return(false);
                }
            }

            Logging.Error("V2Ray 进程启动超时");
            Stop();
            return(false);
        }
Example #57
0
        /// <summary>
        ///
        /// </summary>
        private void SyncBlockDataRequestReceived(byte[] dataRcv)
        {
            var msgRcv = MyAPIGateway.Utilities.SerializeFromBinary <MsgBlockDataRequest>(dataRcv);

            NanobotBuildAndRepairSystemBlock system;

            if (BuildAndRepairSystems.TryGetValue(msgRcv.EntityId, out system))
            {
                if (Mod.Log.ShouldLog(Logging.Level.Communication))
                {
                    Mod.Log.Write(Logging.Level.Communication, "BuildAndRepairSystemMod: SyncBlockDataRequestReceived SteamId={0} EntityId={1}/{2}", msgRcv.SteamId, msgRcv.EntityId, Logging.BlockName(system.Entity, Logging.BlockNameOptions.None));
                }
                SyncBlockSettingsSend(msgRcv.SteamId, system);
                SyncBlockStateSend(msgRcv.SteamId, system);
            }
            else
            {
                if (Mod.Log.ShouldLog(Logging.Level.Error))
                {
                    Mod.Log.Write(Logging.Level.Error, "BuildAndRepairSystemMod: SyncBlockDataRequestReceived for unknown system SteamId{0} EntityId={1}", msgRcv.SteamId, msgRcv.EntityId);
                }
            }
        }
Example #58
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            int count = 0;

            if (!int.TryParse(txtQuantity.Text, out count))
            {
                MessageBox.Show("Количество имеет неверный формат!");
                return;
            }

            if (device.Id != Convert.ToInt32(cmbDevices.SelectedValue))
            {
                proc.RemoveDeviceFromSection(section.Id, device.Id);
            }

            DataTable dtGetSecInfo = new DataTable();

            dtGetSecInfo = proc.GetSecInfo(section.Id);

            DataTable dtResult = proc.AddDeviceToSection(section.Id, Convert.ToInt32(cmbDevices.SelectedValue), Convert.ToInt32(txtQuantity.Text));


            if (device.Id == 0)
            {
                Logging.StartFirstLevel(1395);
                Logging.Comment("Информация о секции:");

                Logging.Comment("id = " + section.Id.ToString()
                                + ", Наименование секции: \"" + dtGetSecInfo.Rows[0]["Sec"].ToString() + "\"");

                Logging.Comment("id объекта  = " + dtGetSecInfo.Rows[0]["id_ObjectLease"].ToString()
                                + ", Наименование объекта : \"" + dtGetSecInfo.Rows[0]["Obj"].ToString() + "\"");

                Logging.Comment("id здания = " + dtGetSecInfo.Rows[0]["id_Build"].ToString()
                                + ", Наименование здания: \"" + dtGetSecInfo.Rows[0]["Build"].ToString() + "\"");

                Logging.Comment("id этажа = " + dtGetSecInfo.Rows[0]["id_Floo"].ToString()
                                + ", Наименование этажа: \"" + dtGetSecInfo.Rows[0]["Floo"].ToString() + "\"");
                Logging.Comment("Количество телефонных линий: " + dtGetSecInfo.Rows[0]["Telephone_lines"].ToString());
                Logging.Comment("Количество светильников: " + dtGetSecInfo.Rows[0]["Lamps"].ToString());
                Logging.Comment("Номер телефона: " + dtGetSecInfo.Rows[0]["Phone_number"].ToString());
                Logging.Comment("Общая площадь: " + dtGetSecInfo.Rows[0]["Total_Area"].ToString());
                Logging.Comment("Площадь торгового зала: " + dtGetSecInfo.Rows[0]["Area_of_Trading_Hall"].ToString());
                Logging.Comment("Признак АППЗ: " + ((bool.Parse(dtGetSecInfo.Rows[0]["isAPPZ"].ToString())) ? "ДА" : "НЕТ"));

                Logging.Comment("Информация о добавленном приборе:");

                if (dtResult != null && dtResult.Rows.Count > 0 && dtResult.Columns.Contains("id"))
                {
                    Logging.Comment($"ID:{dtResult.Rows[0]["id"]}");
                }

                Logging.Comment("Тип прибора ID: " + cmbDevices.SelectedValue + " ;Наименование: " + cmbDevices.Text);
                Logging.Comment("Количество: " + txtQuantity.Text.Trim());

                Logging.Comment("Операцию выполнил: ID:" + Nwuram.Framework.Settings.User.UserSettings.User.Id
                                + " ; ФИО:" + Nwuram.Framework.Settings.User.UserSettings.User.FullUsername);
                Logging.StopFirstLevel();
            }
            else
            {
                Logging.StartFirstLevel(1396);
                Logging.Comment("Информация о секции:");

                Logging.Comment("id = " + section.Id.ToString()
                                + ", Наименование секции: \"" + dtGetSecInfo.Rows[0]["Sec"].ToString() + "\"");

                Logging.Comment("id объекта  = " + dtGetSecInfo.Rows[0]["id_ObjectLease"].ToString()
                                + ", Наименование объекта : \"" + dtGetSecInfo.Rows[0]["Obj"].ToString() + "\"");

                Logging.Comment("id здания = " + dtGetSecInfo.Rows[0]["id_Build"].ToString()
                                + ", Наименование здания: \"" + dtGetSecInfo.Rows[0]["Build"].ToString() + "\"");

                Logging.Comment("id этажа = " + dtGetSecInfo.Rows[0]["id_Floo"].ToString()
                                + ", Наименование этажа: \"" + dtGetSecInfo.Rows[0]["Floo"].ToString() + "\"");
                Logging.Comment("Количество телефонных линий: " + dtGetSecInfo.Rows[0]["Telephone_lines"].ToString());
                Logging.Comment("Количество светильников: " + dtGetSecInfo.Rows[0]["Lamps"].ToString());
                Logging.Comment("Номер телефона: " + dtGetSecInfo.Rows[0]["Phone_number"].ToString());
                Logging.Comment("Общая площадь: " + dtGetSecInfo.Rows[0]["Total_Area"].ToString());
                Logging.Comment("Площадь торгового зала: " + dtGetSecInfo.Rows[0]["Area_of_Trading_Hall"].ToString());
                Logging.Comment("Признак АППЗ: " + ((bool.Parse(dtGetSecInfo.Rows[0]["isAPPZ"].ToString())) ? "ДА" : "НЕТ"));

                Logging.Comment("Информация о редактируемом приборе:");

                if (dtResult != null && dtResult.Rows.Count > 0 && dtResult.Columns.Contains("id"))
                {
                    Logging.Comment($"ID:{dtResult.Rows[0]["id"]}");
                }

                //Logging.VariableChange("Тип прибора ID: " , cmbDevices.SelectedValue ,device.Id);
                //Logging.VariableChange("Тип прибора Наименование: ", cmbDevices.Text,device.Name);
                Logging.Comment("Тип прибора ID: " + cmbDevices.SelectedValue + " ;Наименование: " + cmbDevices.Text);
                Logging.VariableChange("Количество: ", txtQuantity.Text.Trim(), device.Quantity);

                Logging.Comment("Операцию выполнил: ID:" + Nwuram.Framework.Settings.User.UserSettings.User.Id
                                + " ; ФИО:" + Nwuram.Framework.Settings.User.UserSettings.User.FullUsername);
                Logging.StopFirstLevel();
            }

            this.DialogResult = DialogResult.OK;
        }
Example #59
0
            public void doRequest(Socket connection, Logging Log)
            {
                string line = null;
                string name;
                string location;
                string lineMerge = null;

                String        Host = ((IPEndPoint)connection.RemoteEndPoint).Address.ToString();
                NetworkStream socketStream;

                socketStream = new NetworkStream(connection);
                Console.WriteLine("Connection Recieved");

                String Status = "OK";

                try
                {
                    StreamWriter sw = new StreamWriter(socketStream);
                    StreamReader sr = new StreamReader(socketStream);


                    line = sr.ReadLine();


                    string[] split = line.Split(' ');


                    if (line.EndsWith("HTTP/1.0"))
                    {
                        if (split[0] == "GET" || (split[0] == "GET" && split[1].StartsWith("/")))               //this is the lookup for the HTTP/1.0 protocol
                        {
                            name = split[1].Substring(2);
                            if (dictionary.ContainsKey(name))
                            {
                                sw.WriteLine("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n" + dictionary[name] + "\r\n");
                                sw.Flush();
                                lineMerge = "GET " + name + " is " + dictionary[name];
                                Status    = "OK";
                                if (debug == true)
                                {
                                    Console.WriteLine("This is look-up for protocol HTTP/1.0 and the username is: " + name + " and the location is: " + dictionary[name]);
                                }
                            }
                            else if (!dictionary.ContainsKey(name))
                            {
                                sw.WriteLine("HTTP/1.0 404 Not Found\r\nContent-Type: text/plain\r\n\r\n");
                                sw.Flush();
                                Status = "UNKNOWN";
                            }
                        }
                        else if (split[0] == "POST")                    //this is the update for the HTTP/1.0 protocol
                        {
                            name = split[1].Substring(1);
                            string line2 = sr.ReadLine();
                            string line1;
                            do
                            {
                                line1 = sr.ReadLine();
                            } while (line1.Length == 0);


                            dictionary[name] = line1;

                            sw.WriteLine("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n");
                            sw.Flush();
                            lineMerge = "POST " + name + " location changed to be " + line1;
                            Status    = "OK";
                            if (debug == true)
                            {
                                Console.WriteLine("This is an update location for protocol HTTP/1.0 and the username is: " + name + " and the location is: " + line1);
                            }
                        }
                    }
                    else if (line.EndsWith("HTTP/1.1"))
                    {
                        if (split[0] == "GET")                   //this is lookup for the HTTP/1.1 protocol
                        {
                            name = split[1].Substring(7);
                            if (dictionary.ContainsKey(name))
                            {
                                sw.WriteLine("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n" + dictionary[name]);
                                sw.Flush();
                                lineMerge = "GET " + name + " is " + dictionary[name];
                                Status    = "OK";
                            }
                            else
                            {
                                sw.WriteLine("HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\n");
                                sw.Flush();
                                Status = "UNKNOWN";
                            }
                        }
                        else if (split[0] == "POST")             //this is the update for the HTTP/1.1 protocol
                        {
                            string line2 = sr.ReadLine();
                            string line3 = sr.ReadLine();
                            string line1;
                            do
                            {
                                line1 = sr.ReadLine();
                            } while (line1.Length == 0);

                            string[] split1 = line1.Split('=', '&');
                            location         = split1.Last();
                            name             = split1[1];
                            dictionary[name] = location;

                            sw.WriteLine("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
                            sw.Flush();
                            lineMerge = "POST " + name + " location changed to be " + line1;
                            Status    = "OK";
                        }
                    }

                    else                                                                   //The following are for either HTTP/0.9 or whois
                    {
                        if ((split[0] == "GET" || split[0] == "PUT") && split.Length == 1) // if the name is GET or PUT for protocol whois
                        {
                            name = split[0];
                            if (dictionary.ContainsKey(name))
                            {
                                sw.WriteLine(dictionary[name]);
                                sw.Flush();
                                lineMerge = "GET " + name + " is " + dictionary[name];
                                Status    = "OK";
                            }
                            else
                            {
                                sw.WriteLine("ERROR: no entries found");
                                sw.Flush();
                                Status = "UNKNOWN";
                            }
                        }
                        else if (split[0] == "GET" && split[1].StartsWith("/"))     // this is lookup for the HTTP/0.9 protocol
                        {
                            name = split[1].Substring(1);

                            if (dictionary.ContainsKey(name))
                            {
                                sw.WriteLine("HTTP/0.9 200 OK\r\nContent-Type: text/plain\r\n\r\n" + dictionary[name]);
                                sw.Flush();
                                lineMerge = "GET " + name + " is " + dictionary[name];
                                Status    = "OK";
                            }
                            else if (!dictionary.ContainsKey(name))
                            {
                                sw.WriteLine("HTTP/0.9 404 Not Found\r\nContent-Type: text/plain\r\n\r\n");
                                sw.Flush();
                                Status = "UNKNOWN";
                            }
                        }



                        else if (split[0] == "PUT" && split[1].StartsWith("/"))  //  //this is for the update for the HTTP/0.9 protocol
                                                                                 // however hits this if its a whois where the name is PUT and location starts with a /
                        {
                            name = split[1].Substring(1);
                            string line1;
                            do
                            {
                                line1 = sr.ReadLine();
                            } while (line1.Length == 0);

                            dictionary[name] = line1;
                            lineMerge        = "PUT " + line + " location changed to be " + line1;

                            sw.WriteLine("HTTP/0.9 200 OK\r\nContent-Type: text/plain\r\n\r\n");
                            sw.Flush();
                            Status = "OK";
                        }

                        else if (split.Length == 1)         //this is lookup for the whois protocol
                        {
                            name = split[0];
                            if (debug == true)
                            {
                                Console.WriteLine("This is look-up for protocol whois and the username is: " + name);
                            }
                            if (dictionary.ContainsKey(name))
                            {
                                sw.WriteLine(dictionary[name]);
                                sw.Flush();
                                lineMerge = name + " is " + dictionary[name];
                                Status    = "OK";
                            }
                            else
                            {
                                sw.WriteLine("ERROR: no entries found");
                                sw.Flush();
                                Status = "UNKNOWN";
                            }
                        }

                        else  //this is for the update of whois protocol
                        {
                            name             = split[0];
                            location         = string.Join(" ", split.Skip(1).ToArray());
                            dictionary[name] = location;
                            sw.WriteLine("OK");
                            sw.Flush();
                            lineMerge = name + " location changed to be " + location;
                            Status    = "OK";
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Something went wrong: " + e.ToString());
                    Status = "EXCEPTION";
                }

                finally
                {
                    socketStream.Close();
                    connection.Close();
                    Log.WriteToLog(Host, lineMerge, Status);
                }
            }
Example #60
0
 public static void KeepAlive(IPEndPoint endpoint, string data)
 {
     Logging.Log("Keep alive request.");
 }