public override void OnException(HttpActionExecutedContext context)
 {
     var loggingHelper = new LoggingHelper();
     loggingHelper.TraceError(context.Exception);
     ErrorLog.GetDefault(HttpContext.Current).Log(new Error(context.Exception));
     context.Response = context.Request.CreateResponse(
         HttpStatusCode.InternalServerError,
         new ErrorDto
         {
             Code = 0,
             Error = "Oops, something went wrong!"
         }
         );
 }
        public TasaCambioResponse OperacionArticulo(TasaCambioRequest request)
        {
            var response = new TasaCambioResponse()
            {
                EjecucionValida    = false,
                MensajeError       = string.Empty,
                IdUsuarioEjecucion = request.IdUsuarioEjecucion
            };

            try
            {
                response.Item            = iTasaCambioDominio.GetListTasaCambio(request.Item);
                response.EjecucionValida = true;
            }
            catch (Exception ex)
            {
                response.MensajeError = ex.Message;
                using (LoggingHelper helper = new LoggingHelper(TipoRepositorio.Xml))
                {
                    helper.Registrar(ex);
                }
            }
            return(response);
        }
示例#3
0
        public static List <ThisEntity> GetAll(Guid parentUid, ref List <ContactPoint> orphanContacts)
        {
            ThisEntity        entity = new ThisEntity();
            List <ThisEntity> list   = new List <ThisEntity>();

            try
            {
                using (var context = new EntityContext())
                {
                    List <EM.Entity_Address> results = context.Entity_Address
                                                       .Where(s => s.Entity.EntityUid == parentUid)
                                                       .OrderByDescending(s => s.IsPrimaryAddress)
                                                       .ThenBy(s => s.Id)
                                                       .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (EM.Entity_Address item in results)
                        {
                            entity = new ThisEntity();
                            MapFromDB(item, entity);
                            if (entity.HasAddress() == false && entity.HasContactPoints())
                            {
                                orphanContacts.AddRange(entity.ContactPoint);
                            }
                            list.Add(entity);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + string.Format(".GetAll. Guid parentUid: {0}", parentUid));
            }
            return(list);
        }        //
示例#4
0
 public static void ExecuteNonQuery(string sp, List <SqlParameter> parameters)
 {
     try
     {
         using (SqlConnection conn = GetConnection())
         {
             conn.Open();
             // Create a command and prepare it for execution
             using (SqlCommand cmd = GetCommand(conn, sp))
             {
                 if (parameters != null && parameters.Count > 0)
                 {
                     cmd.Parameters.AddRange(parameters.ToArray());
                 }
                 int retval = cmd.ExecuteNonQuery();
             }
         }
     }
     catch (Exception e)
     {
         LoggingHelper.Instance.AgregarLog(new LogSqlEntity("ExecuteNonQuery", sp, parameters, e));
         LoggingHelper.HandleException(e);
     }
 }
 static int Main()
 {
     LoggingHelper.InitLogging();
     try
     {
         return((int)HostFactory.Run(x =>
         {
             x.UseLog4Net();
             x.UseNinject(new HostModule());
             x.Service <EndpointsControl>(s =>
             {
                 s.ConstructUsingNinject();
                 s.WhenStarted((i, hostControl) => i.Start(hostControl));
                 s.WhenStopped((i, hostControl) => i.Stop(hostControl));
             });
             x.SetServiceName("MultiHostNinject");
             x.OnException(ex => LogManager.GetLogger("Host").Fatal("OnException", ex));
         }));
     }
     finally
     {
         LogManager.Shutdown();
     }
 }
        /// <summary>
        /// Adapts Akka.NET configuration to use the correct hostname and cluster seed node (actor system name,
        /// hostname and port).
        /// </summary>
        /// <param name="workerHostName">
        /// The worker host name.
        /// </param>
        /// <param name="clusterSeed">
        /// Hostname of cluster seed node.
        /// </param>
        /// <param name="seedPort">
        /// Port of cluster seed node.
        /// </param>
        /// <param name="logOnDebugLevel">
        /// Whether logging should be done on debug level.
        /// </param>
        /// <returns>
        /// The adapted Akka.NET configuration.
        /// </returns>
        private static Config CustomizeAkkaConfiguration(
            string workerHostName,
            string clusterSeed,
            int seedPort,
            bool logOnDebugLevel)
        {
            Config commonBaseConfig =
                ConfigurationFactory.FromResource(AkkaNames.CommonAkkaConfigFileName, Assembly.GetCallingAssembly());

            if (string.IsNullOrWhiteSpace(workerHostName))
            {
                workerHostName = NetworkUtils.GetFullyQualifiedDomainName();
            }

            LoggingHelper.WriteLine(VerbosityLevel.Debug, $"Worker's own HostName: {workerHostName}");

            var logClusterEvents = logOnDebugLevel ? "on" : "off";

            var config = ConfigurationFactory.ParseString(
                $@"
                akka
                {{
                    log-config-on-start = on
                    remote.dot-netty.tcp {{
                        hostname={workerHostName}
                        port = 0 #let os pick random port
                        batching.enabled = false
                    }}
                    cluster.seed-nodes = [""akka.tcp://{AkkaNames.ActorSystemName}@{clusterSeed}:{seedPort}""]
                    cluster.log-info = {logClusterEvents}
               }}").WithFallback(commonBaseConfig);

            return(logOnDebugLevel
                       ? config.WithFallback(ConfigurationFactory.FromResource(AkkaNames.ExtensiveAkkaLoggingFileName, Assembly.GetCallingAssembly()))
                       : config);
        }
        // POST: api/HotelBooking
        public IHttpActionResult Post([FromBody] CheckOutData value)
        {
            LoggingHelper.WriteToFile("SaveBookingController/Request/", "SaveController" + "INController" + value.Sid, "RequestObject", JsonConvert.SerializeObject(value));

            try
            {
                if (ModelState.IsValid)
                {
                    var BookingNum = BookingManager.GetBookingNumberAndManageBooking(value);
                    if (BookingNum != null)
                    {
                        // var myAnonymousType = new { bookingNum= BookingNum};
                        return(Ok(new { bookingNum = BookingNum }));
                    }
                    return(Ok("Booking Number not Created"));
                }
                return(BadRequest(ModelState));
            }catch (Exception ex)
            {
                LoggingHelper.WriteToFile("SaveBookingController/Errors/", "SaveController" + "INController" + value.Sid, ex.InnerException?.Message, ex.Message + ex.StackTrace);

                return(BadRequest(ex.Message));
            }
        }
示例#8
0
        public ArticuloDocumentoResponse SubirDocumentoArticulo(ArticuloDocumentoRequest request)
        {
            var response = new ArticuloDocumentoResponse()
            {
                EjecucionValida    = false,
                MensajeError       = string.Empty,
                IdUsuarioEjecucion = request.IdUsuarioEjecucion
            };

            try
            {
                response.Item            = iArticuloDominio.SubeDocumentoArticulo(request.Item);
                response.EjecucionValida = true;
            }
            catch (Exception ex)
            {
                response.MensajeError = ex.Message;
                using (LoggingHelper helper = new LoggingHelper(TipoRepositorio.Xml))
                {
                    helper.Registrar(ex);
                }
            }
            return(response);
        }
示例#9
0
        public string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
        {
            var condition = new Func <string, bool>(p => true);

            if (!string.IsNullOrEmpty(searchPattern))
            {
                var regex = RegexHelper.GetRegex(searchPattern.Replace("*", ".*"), true);
                condition = new Func <string, bool>(p => regex.IsMatch(Path.GetFileName(p)));
            }

            var flat = searchOption == SearchOption.TopDirectoryOnly;

            var files = Get(path).GetBlobs(flat)
                        .Select(d => AzurePathHelper.GetFileSystemPath(d.Path))
                        .Where(condition)
                        .ToArray();

            if (LoggingHelper.LogsEnabled)
            {
                LoggingHelper.Log($"GetFiles {path}", $"Base path: {path}, condition: {condition}, files: {string.Join(",", files)}");
            }

            return(files);
        }
        /// <summary>
        /// Changes to the correct <see cref="IPopulationUpdateStrategy{TInstance,TResult}"/> based on the current
        /// strategy.
        /// </summary>
        /// <param name="initializationInstances">
        /// Instances to use for potential evaluations on strategy initialization.
        /// </param>
        /// <param name="currentIncumbent">Most recent incumbent genome. Might be <c>null</c>.</param>
        /// <returns>The chosen <see cref="IPopulationUpdateStrategy{TInstance,TResult}"/>.</returns>
        public IPopulationUpdateStrategy <TInstance, TResult> ChangePopulationUpdateStrategy(
            ICollection <TInstance> initializationInstances,
            IncumbentGenomeWrapper <TResult> currentIncumbent)
        {
            var currentStrategy = this.CurrentStrategy;

            while (currentStrategy.HasTerminated())
            {
                this.FinishPhase();

                this.CurrentUpdateStrategyIndex = currentStrategy.NextStrategy(this._populationUpdateStrategies);

                var newStrategy = this.CurrentStrategy;
                newStrategy.Initialize(this.BasePopulation, currentIncumbent, initializationInstances);

                LoggingHelper.WriteLine(
                    VerbosityLevel.Info,
                    $"Changing strategy from {currentStrategy.GetType().Name} to {newStrategy.GetType().Name}.");

                currentStrategy = newStrategy;
            }

            return(currentStrategy);
        }
示例#11
0
        private void CreateReport(ReportInformation reportInformation)
        {
            string filePath = null;

            try
            {
                if (!_fileProcessor.DirectoryExists(ReportFolderPath))
                {
                    _fileProcessor.DirectoryCreate(ReportFolderPath);
                }

                filePath = GeneratorHelper.GetFilePathFormatted(
                    ReportFolderPath,
                    ReportFileNameFormat,
                    reportInformation.FeedId.ToString(),
                    reportInformation.FeedRunId.HasValue ? reportInformation.FeedRunId.Value.ToString() : "0",
                    reportInformation.ExecutionStartTime.ToString("yyyy-MM-dd_hh-mm-ss-fff"));

                using (var fileStream = _fileProcessor.FileCreate(filePath))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        {
                            var serializer = new JsonSerializer();
                            serializer.NullValueHandling = NullValueHandling.Ignore;
                            serializer.Serialize(jsonWriter, reportInformation);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Error(ex, string.Format("Failed to create a report for {0}", filePath));
            }
        }
示例#12
0
 public ProxyLogin()
 {
     InitializeComponent();
     try
     {
         ProxyAuthentication proxy = dbInteraction.RetrieveProxyInfo();
         if (proxy != null)
         {
             textBoxUserID.Text = proxy.UserName;
             textBoxPassword.Focus();
             textBoxPort.Text     = proxy.Port;
             textBoxProxy.Text    = proxy.ProxyAddress;
             textBoxPassword.Text = Helper.DecryptPass(proxy.PassWord);
         }
         else
         {
             string domain   = Environment.UserDomainName;
             string username = Environment.UserName;
             textBoxUserID.Text = domain + CONST_BACKSLASH + username;
             if (((WebProxy)GlobalProxySelection.Select).Address != null)
             {
                 int    colonIndex = ((WebProxy)GlobalProxySelection.Select).Address.ToString().LastIndexOf(':');
                 string proxystr   = ((WebProxy)GlobalProxySelection.Select).Address.ToString().Substring(0, colonIndex);
                 string port       = ((WebProxy)GlobalProxySelection.Select).Address.ToString().Substring(colonIndex + 1, ((WebProxy)GlobalProxySelection.Select).Address.ToString().Length - colonIndex - 1);
                 port.TrimEnd('/');
                 textBoxPassword.Text = string.Empty;
                 textBoxProxy.Text    = proxystr;
                 textBoxPort.Text     = port.Substring(0, 4);
             }
         }
     }
     catch (Exception e)
     {
         LoggingHelper.ShowMessage(e);
     }
 }
 internal ConnectionDetails GetConnectionDetails()
 {
     try
     {
         IObjectContainer container = Db4oClient.OMNConnection;
         IQuery           qry       = container.Query();
         qry.Constrain(typeof(ConnectionDetails));
         IObjectSet objSet;
         if (currConnParams.Host == null)
         {
             qry.Descend("m_connParam").Descend("m_connection").Constrain(currConnParams.Connection);
             objSet = qry.Execute();
         }
         else
         {
             qry.Descend("m_connParam").Descend("m_host").Constrain(currConnParams.Host);
             qry.Descend("m_connParam").Descend("m_port").Constrain(currConnParams.Port);
             qry.Descend("m_connParam").Descend("m_userName").Constrain(currConnParams.UserName);
             qry.Descend("m_connParam").Descend("m_passWord").Constrain(currConnParams.PassWord);
             objSet = qry.Execute();
         }
         if (objSet.Count > 0)
         {
             return((ConnectionDetails)objSet.Next());
         }
     }
     catch (Exception oEx)
     {
         LoggingHelper.HandleException(oEx);
     }
     finally
     {
         Db4oClient.CloseRecentConnectionFile();
     }
     return(null);
 }
示例#14
0
        public async Task <string> GetPetDetails()
        {
            try
            {
                var people = await _repository.GetPeople();

                if (people == null)
                {
                    return(LoggingHelper.LogErrorAndReturnMessage("No people found"));
                }

                var catsByOwnersGender = _processor.GroupPetNamesByOwnersGenderForSpecifiedPetType(people, PetType.Cat);
                if (catsByOwnersGender == null || catsByOwnersGender.Count() == 0)
                {
                    return(LoggingHelper.LogErrorAndReturnMessage("No cats found"));
                }

                return(_outputFormatter.FormatAsHeaderAndSubPoints(catsByOwnersGender));
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GrayBoxSimulation{TTargetAlgorithm, TInstance, TResult}" /> class.
        /// </summary>
        /// <param name="configuration">The <see cref="AlgorithmTunerConfiguration"/>.</param>
        /// <param name="targetAlgorithmFactory">The <see cref="ITargetAlgorithmFactory{TTargetAlgorithm, TInstance, TResult}"/>.</param>
        /// <param name="customGrayBoxMethods">The <see cref="ICustomGrayBoxMethods{TResult}"/>.</param>
        /// <param name="runEvaluator">The <see cref="IRunEvaluator{TInstance, TResult}"/>.</param>
        /// <param name="parameterTree">The <see cref="ParameterTree"/>.</param>
        public GrayBoxSimulation(
            AlgorithmTunerConfiguration configuration,
            ITargetAlgorithmFactory <TTargetAlgorithm, TInstance, TResult> targetAlgorithmFactory,
            ICustomGrayBoxMethods <TResult> customGrayBoxMethods,
            IRunEvaluator <TInstance, TResult> runEvaluator,
            ParameterTree parameterTree)
        {
            ProcessUtils.SetDefaultCultureInfo(CultureInfo.InvariantCulture);

            this._configuration          = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this._customGrayBoxMethods   = customGrayBoxMethods ?? throw new ArgumentNullException(nameof(customGrayBoxMethods));
            this._runEvaluator           = runEvaluator ?? throw new ArgumentNullException(nameof(runEvaluator));
            this._targetAlgorithmFactory = targetAlgorithmFactory ?? throw new ArgumentNullException(nameof(targetAlgorithmFactory));
            this._parameterTree          = parameterTree ?? throw new ArgumentNullException(nameof(parameterTree));

            this._logFileDirectory = new DirectoryInfo(Path.Combine(this._configuration.DataRecordDirectoryPath, "GrayBoxSimulationLogFiles"));
            Directory.CreateDirectory(this._logFileDirectory.FullName);

            LoggingHelper.Configure(
                Path.Combine(this._logFileDirectory.FullName, $"consoleOutput_GrayBoxSimulation_{ProcessUtils.GetCurrentProcessId()}.log"));
            LoggingHelper.ChangeConsoleLoggingLevel(configuration.Verbosity);
            LoggingHelper.WriteLine(VerbosityLevel.Info, "Reading in and preprocessing data for gray box simulation.");

            if (!GrayBoxUtils.TryToReadDataRecordsFromDirectory(
                    targetAlgorithmFactory,
                    configuration.DataRecordDirectoryPath,
                    0,
                    configuration.Generations - 1,
                    out this._allDataRecords))
            {
                throw new ArgumentException($"Cannot read data records from {configuration.DataRecordDirectoryPath}!");
            }

            this.ReadGenerationCompositionFiles();
            this.CreatePredictionDictionaryAndDataDictionary();
        }
示例#16
0
        /// <summary>
        /// Get all assessments for the provided entity
        /// The returned entities are just the base
        /// </summary>
        /// <param name="parentUid"></param>
        /// <returns></returnsThisEntity
        public static List <ThisEntity> GetAll(Guid parentUid, int identityValueTypeId)
        {
            List <ThisEntity> list   = new List <ThisEntity>();
            ThisEntity        entity = new ThisEntity();

            Entity parent = EntityManager.GetEntity(parentUid);

            LoggingHelper.DoTrace(7, string.Format(thisClassName + ".GetAll: parentUid:{0} entityId:{1}, e.EntityTypeId:{2}", parentUid, parent.Id, parent.EntityTypeId));

            try
            {
                using (var context = new EntityContext())
                {
                    List <DBEntity> results = context.Entity_IdentifierValue
                                              .Where(s => s.EntityId == parent.Id && s.IdentityValueTypeId == identityValueTypeId)
                                              .OrderBy(s => s.Name)
                                              .ToList();

                    if (results != null && results.Count > 0)
                    {
                        foreach (DBEntity item in results)
                        {
                            entity = new ThisEntity();
                            MapFromDB(item, entity);
                            list.Add(entity);
                        }
                    }
                    return(list);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".GetAll");
            }
            return(list);
        }
示例#17
0
        public static object EditObjects(object obj, string attribute, string value)
        {
            try
            {
                string fieldName  = attribute;
                int    intIndexof = fieldName.IndexOf('.') + 1;
                fieldName = fieldName.Substring(intIndexof, fieldName.Length - intIndexof);

                string[] splitstring      = fieldName.Split('.');
                object   holdParentObject = obj;

                foreach (string str in splitstring)
                {
                    holdParentObject = SetField(str, holdParentObject, fieldName, value);
                }

                return(obj);
            }
            catch (Exception oEx)
            {
                LoggingHelper.HandleException(oEx);
                return(null);
            }
        }
示例#18
0
        public void UpdateHoliday(long holidayID, DateTime date, string name, long ptoCycle)
        {
            try
            {
                using (var context = new PTOMEntities())
                {
                    var holiday = context.HOLIDAY.FirstOrDefault(h => h.HOLIDAY_ID == holidayID);
                    if (holiday != null)
                    {
                        holiday.HOLIDAY_DATE = date;
                        holiday.NAME         = name;
                        holiday.PTO_CYCLE    = ptoCycle;

                        context.SaveChanges();
                    }
                    ;
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.LogServiceMessage(LoggingHelper.MessageType.Error, string.Empty, ex);
                throw;
            }
        }
示例#19
0
        internal List <string> ReturnStringList()
        {
            List <string> stringList = null;

            try
            {
                GroupofSearchStrings groupSearchList = FetchAllSearchStringsForAConnection();
                if (groupSearchList != null)
                {
                    List <SeachString> searchStringList = groupSearchList.m_SearchStringList;
                    stringList = new List <string>();
                    foreach (SeachString str in searchStringList)
                    {
                        stringList.Add(str.SearchString);
                    }
                }
            }
            catch (Exception oEx)
            {
                LoggingHelper.HandleException(oEx);
            }

            return(stringList);
        }
示例#20
0
        /// <summary>
        /// Computes and updates the <see cref="IsCancelledByRacing"/>.
        /// Moves all <see cref="RunningInstances"/> and <see cref="OpenInstances"/> to <see cref="CancelledByRacingInstances"/>.
        /// </summary>
        /// <returns><c>true</c>, if <see cref="IsCancelledByRacing"/> was set from <c>false</c> to <c>true</c>.</returns>
        public bool UpdateCancelledByRacing()
        {
            lock (this._lock)
            {
                if (this.IsCancelledByRacing || !this.HasOpenOrRunningInstances)
                {
                    return(false);
                }

                foreach (var unfinishedInstance in this._openInstances.Concat(this._runningInstances))
                {
                    this._cancelledByRacingInstances.Add(unfinishedInstance);
                }

                LoggingHelper.WriteLine(
                    VerbosityLevel.Info,
                    $"The evaluation of {this._cancelledByRacingInstances.Count} instances (Open: {this._openInstances.Count}, Running: {this._runningInstances.Count}) of the following genome is stopped by racing.{Environment.NewLine}{this.Genome}");

                this._openInstances.Clear();
                this._runningInstances.Clear();

                return(true);
            }
        }
        public void OnException(ExceptionContext context)
        {
            string errorId = (Convert.ToBase64String(Guid.NewGuid().ToByteArray())).Replace("=", "");
            string message = $"Đã xảy ra lỗi trong quá trình xử lý ({errorId}).";

            LoggingHelper.SetProperty("ErrorId:", errorId);
            string errorMessage = context.Exception.ToString();

            // TODO
            if (context.Exception.GetType() == typeof(CustomValidationException))
            {
                var validationException = (CustomValidationException)context.Exception;
                message = string.Join(" | ", validationException.Errors.SelectMany(x => x.Value));
            }
            var response = ResultObject.Error(message, errorMessage, code: ResultCode.ErrorException);

            context.Result = new ContentResult()
            {
                Content     = JsonConvert.SerializeObject(response),
                ContentType = "application/json; charset=utf-8",
                StatusCode  = (int)HttpStatusCode.OK
            };
            context.ExceptionHandled = true;
        }
示例#22
0
        static void Main(string[] args)
        {
            var lh = new LoggingHelper();

            lh.ClearLogFile();
            Log.Info("=====================================================================");
            var       g0     = ExampleWeightedGraph.GenerateExampleWeightedTwinGraph2();
            TwinGraph g0Star = GenerateG0StarFrom(g0);

            _mAugmentingPath = new LinkedList <Arc>();
            var i = 0;
            var mAugmentingPaths = new LinkedList <LinkedList <Arc> >();

            while (true)
            {
                i++;
                Log.Info("ITERATION " + i + " =============================================");
                var k     = new ABVertexStack();
                var l     = new LinkedList <ABVertex>();
                var mdfsw = new MDFSW(g0Star, k, l);
                MDFSW._step = 0;

                _mAugmentingPath = mdfsw.Run();
                if (_mAugmentingPath == null)
                {
                    //Extension step instead of breaking
                    break;
                }
                mAugmentingPaths.AddLast(_mAugmentingPath);
                g0Star.SymmetricDifferenceWith(_mAugmentingPath);

                g0Star.LogArcsWeighted();
                g0Star.LogVerticesWeighted();
            }
            LogPaths(mAugmentingPaths);
        }
示例#23
0
        /// <summary>
        /// Tries to get the generation id from the data log file name.
        /// </summary>
        /// <param name="fileName">The file name.</param>
        /// <param name="generation">The generation id.</param>
        /// <returns>True, if successful.</returns>
        public static bool TryToGetGenerationIdFromDataLogFileName(string fileName, out int generation)
        {
            generation = 0;

            if (!GrayBoxUtils.DataLogFileNameRegex.IsMatch(fileName))
            {
                LoggingHelper.WriteLine(
                    VerbosityLevel.Warn,
                    $"The name of the file {fileName} does not match the regex {GrayBoxUtils.DataLogFileNameRegex}.");
                return(false);
            }

            var generationString = GrayBoxUtils.DataLogFileNameRegex.Match(fileName).Result("$1");

            if (!int.TryParse(generationString, out generation))
            {
                LoggingHelper.WriteLine(
                    VerbosityLevel.Warn,
                    $"The name of the file {fileName} matches the regex {GrayBoxUtils.DataLogFileNameRegex}, but does not contain the generation id as integer.");
                return(false);
            }

            return(true);
        }
示例#24
0
        private bool Action(Grid grid, bool mark)
        {
            try
            {
                var abc  = grid.Children.OfType <Grid>();
                var temp = abc.Select(x => x.Children.OfType <Button>().First()).ToList();
                foreach (var btn in temp)
                {
                    var brush = new ImageBrush
                    {
                        ImageSource = new BitmapImage(new Uri("Assets/Images/checkbox.png", UriKind.Relative))
                    };
                    btn.Background = mark ? brush : null;
                    btn.Content    = mark ? "checked" : "unchecked";
                }

                return(true);
            }
            catch (Exception ex)
            {
                LoggingHelper.Save(ex);
                return(false);
            }
        }
示例#25
0
        public static void TryToMoveFile(FileInfo sourceFile, FileInfo targetFile)
        {
            if (!File.Exists(sourceFile.FullName))
            {
                return;
            }

            Directory.CreateDirectory(targetFile.DirectoryName !);

            try
            {
                if (File.Exists(targetFile.FullName))
                {
                    File.Delete(targetFile.FullName);
                }

                File.Move(sourceFile.FullName, targetFile.FullName);
                LoggingHelper.WriteLine(VerbosityLevel.Warn, $"Moved existing {sourceFile.FullName} to {targetFile.FullName}.");
            }
            catch
            {
                LoggingHelper.WriteLine(VerbosityLevel.Warn, $"Cannot move existing {sourceFile.FullName} to {targetFile.FullName}.");
            }
        }
示例#26
0
        /// <summary>
        /// Actor is ignorant about which instances to evaluate genomes on.
        /// </summary>
        private void WaitForInstances()
        {
            // If a poll comes in, decline and ask for configuration first.
            this.Receive <Poll>(
                poll =>
            {
                this.Sender.Tell(new Decline());
                this.Sender.Tell(new InstancesRequest());
            });

            // Timeout can be updated.
            this.Receive <UpdateTimeout>(update => this.HandleTimeoutUpdate(update));

            // Timeout can be reset.
            this.Receive <ResetTimeout>(reset => this._totalEvaluationTimeout = TimeSpan.MaxValue);

            // Instances can be updated.
            this.Receive <ClearInstances>(update => this._instancesForEvaluation = new List <TInstance>());
            this.Receive <AddInstances <TInstance> >(update => this._instancesForEvaluation.AddRange(update.Instances));

            // If an instance update finishes successfully, change to ready state.
            this.Receive <InstanceUpdateFinished>(
                update => this.Become(this.Ready),
                update => this._instancesForEvaluation.Count == update.ExpectedInstanceCount);

            // Else request a new instance specification.
            this.Receive <InstanceUpdateFinished>(
                update =>
            {
                this.Sender.Tell(new InstancesRequest());
                LoggingHelper.WriteLine(
                    VerbosityLevel.Warn,
                    $"Request instances again because we received {this._instancesForEvaluation.Count} instead of {update.ExpectedInstanceCount} instances from {this.Sender}.");
            },
                update => this._instancesForEvaluation.Count != update.ExpectedInstanceCount);
        }
示例#27
0
		private void buttonSaveIndex_Click(object sender, EventArgs e)
		{
			try
			{
				if (ListofModifiedObjects.Instance.Count > 0)
				{
					DialogResult dialogRes = MessageBox.Show("This will close all the Query result windows. Do you want to continue?", Helper.GetResourceString(Constants.PRODUCT_CAPTION), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
					if (dialogRes == DialogResult.Yes)
					{
						SaveIndex();

					}
				}
				else
				{
					SaveIndex();
				}

			}
			catch (Exception e1)
			{
				LoggingHelper.ShowMessage(e1);
			}
		}
示例#28
0
 private void btnSignIn_Click(object sender, EventArgs e)
 {
     try
     {
         var login = txtLogin.Text;
         var pass  = txtPass.Text;
         var val   = SearchUser(login, pass);
         if (val == true)
         {
             Form1 form = new Form1();
             this.Hide();
             form.ShowDialog();
             this.Close();
         }
         else if (val == false)
         {
             MessageBox.Show("Login or password is incorrect!");
         }
     }catch (Exception ex)
     {
         MessageBox.Show($"Internal error!{ex.Message}");
         LoggingHelper.LogEntry(SystemCategories.GeneralError, $"{ex.Message} {ex.StackTrace}");
     }
 }
示例#29
0
        public static void AddGoneEntryByNodeId(int nodeId)
        {
            if (UmbracoContext.Current == null) // NiceUrl will throw an exception if UmbracoContext is null, and we'll be unable to retrieve the URL of the node
            {
                return;
            }

            string url = umbraco.library.NiceUrl(nodeId);

            if (url == "#")
            {
                return;
            }

            if (url.StartsWith("http://") || url.StartsWith("https://"))
            {
                Uri uri = new Uri(url);
                url = uri.AbsolutePath;
            }
            url = UrlTrackerHelper.ResolveShortestUrl(url);

            string query  = "SELECT 1 FROM icUrlTracker WHERE RedirectNodeId = @redirectNodeId AND OldUrl = @oldUrl AND RedirectHttpCode = 410";
            int    exists = _sqlHelper.ExecuteScalar <int>(query, _sqlHelper.CreateParameter("redirectNodeId", nodeId), _sqlHelper.CreateStringParameter("oldUrl", url));

            if (exists != 1)
            {
                LoggingHelper.LogInformation("UrlTracker Repository | Inserting 410 Gone mapping for node with id: {0}", nodeId);

                query = "INSERT INTO icUrlTracker (RedirectNodeId, OldUrl, RedirectHttpCode, Notes) VALUES (@redirectNodeId, @oldUrl, 410, @notes)";
                _sqlHelper.ExecuteNonQuery(query, _sqlHelper.CreateParameter("redirectNodeId", nodeId), _sqlHelper.CreateStringParameter("oldUrl", url), _sqlHelper.CreateStringParameter("notes", "Node removed"));
            }
            else
            {
                LoggingHelper.LogInformation("UrlTracker Repository | Skipping 410 Gone mapping for node with id: {0} (already exists)", nodeId);
            }
        }
示例#30
0
        public static void SetFieldToNull(object obj, string fieldName)
        {
            try
            {
                IReflectClass klass = DataLayerCommon.ReflectClassFor(obj);
                if (klass != null)
                {
                    IReflectField field = DataLayerCommon.GetDeclaredFieldInHeirarchy(klass, fieldName);
                    if (field == null)
                    {
                        return;
                    }

                    field.Set(obj, null);
                    Db4oClient.Client.Store(obj);

                    Db4oClient.Client.Commit();
                }
            }
            catch (Exception oEx)
            {
                LoggingHelper.HandleException(oEx);
            }
        }
        public static void SendEmail_OnUnConfirmedEmail(string userEmail)
        {
            //should have a valid email at this point
            AppUser user    = GetUserByEmail(userEmail);
            string  subject = "Forgot password attempt with unconfirmed email";

            string toEmail = UtilityManager.GetAppKeyValue("systemAdminEmail", "*****@*****.**");

            string fromEmail = UtilityManager.GetAppKeyValue("contactUsMailFrom", "*****@*****.**");
            //string subject = "Forgot Password";
            string email    = "User: {0} attempted Forgot Password, and email has not been confirmed.<br/>Email: {1}<br/>Created: {2}";
            string eMessage = "";

            try
            {
                eMessage = string.Format(email, user.FullName(), user.Email, user.Created);

                EmailManager.SendEmail(toEmail, fromEmail, subject, eMessage, "", "");
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".SendEmail_OnUnConfirmedEmail()");
            }
        }