Esempio n. 1
0
            /// <summary>
            /// Create enumerator for given exception and all inner exception
            /// </summary>
            /// <param name="exception">last exception in stack</param>
            /// <returns>enumerator to iterate the errors</returns>
            internal static IEnumerable<ErrorDescription> CreateList(Exception exception)
            {
                List<ErrorDescription> list = new List<ErrorDescription>();

                while (null != exception)
                {
                    ErrorDescription error = new ErrorDescription(exception);
                    list.Add(error);
                    exception = exception.InnerException;
                }

                return list;
            }
Esempio n. 2
0
        private void ThrowCommunicationException(ServiceResponse serviceReponse)
        {
            ErrorDescription response = new ErrorDescription();

            if (!string.IsNullOrEmpty(serviceReponse.Response))
            {
                try
                {
                    response = _modelConvertor.ConvertToModel <ErrorDescription>(serviceReponse.Response);
                }
                catch { }
            }

            throw new ServiceCommunicationException()
                  {
                      StatusCode  = serviceReponse.StatusCode,
                      Code        = response.Code,
                      Description = string.IsNullOrEmpty(response.Message) ? serviceReponse.Response : response.Message
                  };
        }
        public override OneOf <ParseSuccess, (ErrorDescription description, dynamic bestParseAttempt)> Parse(
            Type type, string value, string path)
        {
            if (type != typeof(int) && type != typeof(int?))
            {
                throw new InvalidOperationException(
                          $"Fields tagged with {typeof(StronglyApiedIntAttribute).FullName} "
                          + $"must be a {typeof(int).FullName}, "
                          + $"but the given type was {type.FullName}");
            }

            if (string.IsNullOrEmpty(value))
            {
                if (optional)
                {
                    return(ParseSuccess.From(null));
                }
                else
                {
                    return(ErrorDescription.InvalidInt32(value, path), default);
Esempio n. 4
0
        private void dataGridViewErrors_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (dataGridViewErrors.SelectedCells.Count == 0)
                {
                    return;
                }

                ErrorDescription selectedItem = dataGridViewErrors.Rows[dataGridViewErrors.SelectedCells[0].RowIndex].DataBoundItem as ErrorDescription;
                if (null != selectedItem)
                {
                    ShowSingleException(selectedItem);
                }
            }
            catch (Exception exception)
            {
                ShowSingleException(exception);
            }
        }
        /// <summary>
        /// Writes a log message to the logger destination.
        /// </summary>
        /// <param name="level">a log level.</param>
        /// <param name="correlationId">(optional) transaction id to trace execution through call chain.</param>
        /// <param name="error">an error object associated with this message.</param>
        /// <param name="message">a human-readable message to log.</param>
        protected override void Write(LogLevel level, string correlationId, Exception error, string message)
        {
            ErrorDescription errorDescription = error != null?ErrorDescriptionFactory.Create(error, correlationId) : null;

            LogMessage logMessage = new LogMessage()
            {
                Time          = DateTime.UtcNow,
                Level         = LogLevelConverter.ToString(level),
                Source        = _source,
                Error         = errorDescription,
                Message       = message,
                CorrelationId = correlationId
            };

            lock (_lock)
            {
                _cache.Add(logMessage);
            }

            Update();
        }
Esempio n. 6
0
        /// <summary>
        /// Process the <see cref="ConfigurationSetStableRequest"/>
        /// </summary>
        /// <param name="request">The request</param>
        private void OnConfigurationSetStable(ConfigurationSetStableRequest request)
        {
            try
            {
                using (var ds = this.GetContext())
                {
                    var configuration = ds.Configurations.FirstOrDefault(r => r.Id == request.Id);
                    if (configuration == null)
                    {
                        this.Sender.Tell(CrudActionResponse <Configuration> .Error(new EntityNotFoundException(), null));
                        return;
                    }

                    if (configuration.State != EnConfigurationState.Active)
                    {
                        this.Sender.Tell(
                            CrudActionResponse <Configuration> .Error(
                                new Exception("Only active configurations can be marked as stable"),
                                null));
                        return;
                    }

                    if (configuration.IsStable != request.IsStable)
                    {
                        var error             = new ErrorDescription("isStable", "The value is not changed");
                        var mutationException = new MutationException(error);
                        this.Sender.Tell(CrudActionResponse <Configuration> .Error(mutationException, null));
                        return;
                    }

                    configuration.IsStable = request.IsStable;
                    ds.SaveChanges();
                    this.Sender.Tell(CrudActionResponse <Configuration> .Success(configuration, null));
                }
            }
            catch (Exception exception)
            {
                this.Sender.Tell(CrudActionResponse <Configuration> .Error(exception, null));
            }
        }
        public string GetErrors()
        {
            if (!HasErrors)
            {
                return(string.Empty);
            }

            var builder = new StringBuilder();

            if (Error.IsNotEmpty())
            {
                builder.Append($"Error: {Error};");
            }
            if (ErrorDescription.IsNotEmpty())
            {
                builder.Append($"ErrorDescription: {ErrorDescription};");
            }
            if (ValidationErrors.IsNotEmpty())
            {
                builder.Append($"ValidationErrors: {string.Join(" - ", ValidationErrors.ToArray())};");
            }
            return(builder.ToString());
        }
        public override OneOf <ParseSuccess, (ErrorDescription description, dynamic bestParseAttempt)> Parse(
            Type type, string value, string path)
        {
            if (!type.IsEnum)
            {
                throw new InvalidOperationException(
                          $"Fields tagged with {typeof(StronglyApiedOptionAttribute).FullName} "
                          + $"must be an enum, "
                          + $"but the given type was {type.FullName}");
            }

            string trimmedValue = value.Trim();

            List <string> enumValues = type.GetFields()
                                       .Select((FieldInfo fieldInfo) => fieldInfo.Name.ToString())
                                       .Where((string value) => value != "value__")   //junk data which appears when you use Type.GetFields() to get enum values.
                                       .Where((string value) => value != "Undefined") //TODO: Think of a good way to exclude "Undefined" for me but not for other people.
                                                                                      //I use the enum-value of Undefined to signify that the enum is in Identity-state, but that's specific to me.
                                       .ToList();

            if (!enumValues.Contains(trimmedValue))
            {
                return(ErrorDescription.InvalidOption(value, enumValues, path), default);
        public void OpenDevice()
        {
            HekkaDevice device = HekkaDevice.Zero;

            uint err = ITCMM.ITC_OpenDevice(ITCMM.USB18_ID, 0, ITCMM.SMART_MODE, out device);

            try
            {
                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                err,
                                ErrorDescription.ErrorString(err)
                                );

                Assert.NotNull(device);
            }
            finally
            {
                err = ITCMM.ITC_CloseDevice(device);
                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                err,
                                ErrorDescription.ErrorString(err)
                                );
            }
        }
Esempio n. 10
0
        public bool debugValidateChild(RenderObject child)
        {
            D.assert(() =>
            {
                if (!(child is RenderSliver))
                {
                    string result = "";
                    result       += new ErrorDescription(
                        $"A {GetType()} expected a child of type $ChildType but received a " +
                        $"child of type {child.GetType()}.");
                    result += new ErrorDescription(
                        "RenderObjects expect specific types of children because they " +
                        "coordinate with their children during layout and paint. For " +
                        "example, a RenderSliver cannot be the child of a RenderBox because " +
                        "a RenderSliver does not understand the RenderBox layout protocol."
                        );
                    result += new ErrorSpacer();
                    result += new DiagnosticsProperty <dynamic>(
                        $"The {GetType()} that expected a $ChildType child was created by",
                        debugCreator,
                        style: DiagnosticsTreeStyle.errorProperty
                        );
                    result += new ErrorSpacer();
                    result += new DiagnosticsProperty <dynamic>(
                        $"The {child.GetType()} that did not match the expected child type " +
                        "was created by",
                        child.debugCreator,
                        style: DiagnosticsTreeStyle.errorProperty
                        );
                    throw new UIWidgetsError(result);
                }

                return(true);
            });
            return(true);
        }
Esempio n. 11
0
        private async Task <HttpResponseMessage> ExecuteRequestAsync(
            string correlationId, HttpMethod method, Uri uri, HttpContent content = null)
        {
            if (_client == null)
            {
                throw new InvalidOperationException("REST client is not configured");
            }

            // Set headers
            foreach (var key in _headers.Keys)
            {
                if (!_client.DefaultRequestHeaders.Contains(key))
                {
                    _client.DefaultRequestHeaders.Add(key, _headers[key]);
                }
            }

            HttpResponseMessage result = null;

            var retries = Math.Min(1, Math.Max(5, _retries));

            while (retries > 0)
            {
                try
                {
                    if (method == HttpMethod.Get)
                    {
                        result = await _client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
                    }
                    else if (method == HttpMethod.Post)
                    {
                        result = await _client.PostAsync(uri, content);
                    }
                    else if (method == HttpMethod.Put)
                    {
                        result = await _client.PutAsync(uri, content);
                    }
                    else if (method == HttpMethod.Delete)
                    {
                        result = await _client.DeleteAsync(uri);
                    }
#if !NETSTANDARD2_0
                    else if (method == HttpMethod.Patch)
                    {
                        result = await _client.PatchAsync(uri, content);
                    }
#endif
                    else
                    {
                        throw new InvalidOperationException("Invalid request type");
                    }

                    retries = 0;
                }
                catch (HttpRequestException ex)
                {
                    retries--;
                    if (retries > 0)
                    {
                        throw new ConnectionException(correlationId, null, "Unknown communication problem on REST client", ex);
                    }
                    else
                    {
                        _logger.Trace(correlationId, $"Connection failed to uri '{uri}'. Retrying...");
                    }
                }
            }

            if (result == null)
            {
                throw ApplicationExceptionFactory.Create(ErrorDescriptionFactory.Create(
                                                             new UnknownException(correlationId, $"Unable to get a result from uri '{uri}' with method '{method}'")));
            }

            if ((int)result.StatusCode >= 400)
            {
                var responseContent = await result.Content.ReadAsStringAsync();

                ErrorDescription errorObject = null;
                try
                {
                    errorObject = JsonConverter.FromJson <ErrorDescription>(responseContent);
                }
                finally
                {
                    if (errorObject == null)
                    {
                        errorObject = ErrorDescriptionFactory.Create(new UnknownException(correlationId, $"UNKNOWN_ERROR with result status: '{result.StatusCode}'", responseContent));
                    }
                }

                throw ApplicationExceptionFactory.Create(errorObject);
            }

            return(result);
        }
Esempio n. 12
0
        protected void IsInvalidEmail(string s, ErrorDescription error)
        {
            const string pattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";

            Fail(!Regex.IsMatch(s, pattern), error);
        }
 /// <summary>HTTP 404 Error: Not found.</summary>
 /// <param name="errorDescription">The error description.</param>
 public ActionResult Http404(ErrorDescription errorDescription)
 {
     return(this.View("Http404"));
 }
        private static void ExploreTopologyErrors(Topology topology)
        {
            // Get all the errors and exceptions currently associated with the topology.

            Console.WriteLine("***************************************************************************");
            IReadOnlyList <TopologyError> allErrorsAndExceptions = topology.GetErrors(new ErrorDescription(topology.GetExtent()));

            Console.WriteLine($"There are {allErrorsAndExceptions.Count} errors and exceptions associated with the topology.");

            Console.WriteLine("OriginClassName \t OriginObjectID \t DestinationClassName \t DestinationObjectID \t RuleType \t IsException \t Shape type \t Shape width & height \t  Rule ID \t");

            foreach (TopologyError error in allErrorsAndExceptions)
            {
                Console.WriteLine($"'{error.OriginClassName}' \t {error.OriginObjectID} \t '{error.DestinationClassName}' \t " +
                                  $"{error.DestinationObjectID} \t {error.RuleType} \t {error.IsException} \t {error.Shape.GeometryType} \t " +
                                  $"{error.Shape.Extent.Width},{error.Shape.Extent.Height} \t {error.RuleID}");
            }

            // Get all the errors due to features violating the "PointProperlyInsideArea" topology rule.

            TopologyDefinition definition = topology.GetDefinition();
            TopologyRule       pointProperlyInsideAreaRule = definition.GetRules().First(rule => rule.RuleType == TopologyRuleType.PointProperlyInsideArea);

            ErrorDescription errorDescription = new ErrorDescription(topology.GetExtent())
            {
                TopologyRule = pointProperlyInsideAreaRule
            };

            IReadOnlyList <TopologyError> errorsDueToViolatingPointProperlyInsideAreaRule = topology.GetErrors(errorDescription);

            Console.WriteLine($"There are {errorsDueToViolatingPointProperlyInsideAreaRule.Count} feature violating the 'PointProperlyInsideArea' topology rule.");

            // Mark all errors from features violating the 'PointProperlyInsideArea' topology rule as exceptions.

            foreach (TopologyError error in errorsDueToViolatingPointProperlyInsideAreaRule)
            {
                topology.MarkAsException(error);
            }

            // Now verify all the errors from features violating the 'PointProperlyInsideArea' topology rule have indeed been
            // marked as exceptions.
            //
            // By default, ErrorDescription is initialized to ErrorType.ErrorAndException.  Here we want ErrorType.ErrorOnly.

            errorDescription = new ErrorDescription(topology.GetExtent())
            {
                ErrorType    = ErrorType.ErrorOnly,
                TopologyRule = pointProperlyInsideAreaRule
            };

            IReadOnlyList <TopologyError> errorsAfterMarkedAsExceptions = topology.GetErrors(errorDescription);

            Console.WriteLine($"There are {errorsAfterMarkedAsExceptions.Count} feature violating the 'PointProperlyInsideArea' topology rule after all the errors have been marked as exceptions.");

            // Finally, reset all the exceptions as errors by unmarking them as exceptions.

            foreach (TopologyError error in errorsDueToViolatingPointProperlyInsideAreaRule)
            {
                topology.UnmarkAsException(error);
            }

            IReadOnlyList <TopologyError> errorsAfterUnmarkedAsExceptions = topology.GetErrors(errorDescription);

            Console.WriteLine($"There are {errorsAfterUnmarkedAsExceptions.Count} feature violating the 'PointProperlyInsideArea' topology rule after all the exceptions have been reset as errors.");
        }
 /// <summary>HTTP 404 Error: Not found.</summary>
 /// <param name="errorDescription">The error description.</param>
 public ActionResult Http404(ErrorDescription errorDescription)
 {
     return this.View();
 }
Esempio n. 16
0
 protected void IsInvalidEmail(Email s, ErrorDescription error)
 {
     Fail(Email.Notification.HasErrors, error);
 }
Esempio n. 17
0
 ///<summary>
 /// Сохранить цепочку ошибок
 ///</summary>
 ///<param name="errorDescription"></param>
 ///<returns></returns>
 public static long WriteError(this ErrorDescription errorDescription)
 {
     return(errorDescription.Exception.WriteError(errorDescription.HttpCode, errorDescription.Request));
 }
 partial void UpdateErrorDescription(ErrorDescription instance);
 internal NotAuthorizedException(string reasonPhrase, ErrorDescription error)
     : base(HttpStatusCode.Unauthorized, reasonPhrase, error)
 {
 }
Esempio n. 20
0
 /// <summary>
 /// Notifica se o e-mail for inválido.
 /// </summary>
 /// <param name="email">
 /// O email a ser notifcado.
 /// </param>
 /// <param name="error">
 /// O error a ser disparado.
 /// </param>
 protected void IsInvalidEmail(Email email, ErrorDescription error)
 {
     this.Fail(email.Notification.HasErrors, error);
 }
        public void ReadAvailableSamples()
        {
            HekkaDevice device = HekkaDevice.Zero;

            uint err = ITCMM.ITC_OpenDevice(ITCMM.USB18_ID, 0, ITCMM.SMART_MODE, out device);

            if (err != ITCMM.ACQ_SUCCESS)
            {
                Assert.Fail(ErrorDescription.ErrorString(err));
            }

            try
            {
                //ITCMM.HWFunction hwf = new ITCMM.HWFunction();

                err = ITCMM.ITC_InitDevice(device, IntPtr.Zero); // ref hwf);

                ITCMM.ITCPublicConfig config = new ITCMM.ITCPublicConfig();
                config.OutputEnable = 1;

                err = ITCMM.ITC_ConfigDevice(device, ref config);
                if (err != ITCMM.ACQ_SUCCESS)
                {
                    Assert.Fail(ErrorDescription.ErrorString(err));
                }


                Assert.NotNull(device);

                ITCMM.ITCChannelInfo channelInfo = new ITCMM.ITCChannelInfo();
                channelInfo.ChannelType   = ITCMM.H2D;
                channelInfo.ChannelNumber = 0;
                channelInfo.SamplingRate  = 1000.0;
                Assert.AreEqual(System.IntPtr.Zero, channelInfo.FIFOPointer);

                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                ITCMM.ITC_SetChannels(device, 1, new ITCMM.ITCChannelInfo[] { channelInfo })
                                );

                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                (int)ITCMM.ITC_UpdateChannels(device)
                                );

                ITCMM.ITCChannelDataEx info = new ITCMM.ITCChannelDataEx();

                info.ChannelType   = ITCMM.H2D;
                info.ChannelNumber = 0;

                ITCMM.ITCChannelDataEx[] arr = new ITCMM.ITCChannelDataEx[] { info };
                err = ITCMM.ITC_GetDataAvailable(device, 1, arr);
                if (err != ITCMM.ACQ_SUCCESS)
                {
                    Assert.Fail(ErrorDescription.ErrorString(err));
                }

                info = arr[0];

                Assert.That(info.Value, Is.GreaterThanOrEqualTo(0));
            }
            finally
            {
                err = ITCMM.ITC_CloseDevice(device);
                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                err,
                                ErrorDescription.ErrorString(err)
                                );
            }
        }
        public void AsyncIORoundTrip()
        {
            HekkaDevice device = HekkaDevice.Zero;

            uint err = ITCMM.ITC_OpenDevice(ITCMM.USB18_ID, 0, ITCMM.SMART_MODE, out device);

            Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                            err,
                            ErrorDescription.ErrorString(err)
                            );

            try
            {
                err = ITCMM.ITC_InitDevice(device, IntPtr.Zero); //ref sHWFunction);
                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                err,
                                ErrorDescription.ErrorString(err)
                                );


                uint expectedValue = 8000;

                var channelData = new ITCMM.ITCChannelDataEx[] {
                    new ITCMM.ITCChannelDataEx {
                        ChannelNumber = 0,
                        ChannelType   = ITCMM.OUTPUT_GROUP,
                        Value         = (short)expectedValue
                    }
                };

                err = ITCMM.ITC_AsyncIO(device, 1, channelData);
                if (err != ITCMM.ACQ_SUCCESS)
                {
                    throw new HekaDAQException("Unable to write AsyncIO", err);
                }

                channelData = new ITCMM.ITCChannelDataEx[] {
                    new ITCMM.ITCChannelDataEx {
                        ChannelNumber = 0,
                        ChannelType   = ITCMM.INPUT_GROUP,
                        Value         = (short)expectedValue
                    }
                };

                err = ITCMM.ITC_AsyncIO(device, 1, channelData);
                if (err != ITCMM.ACQ_SUCCESS)
                {
                    throw new HekaDAQException("Unable to write AsyncIO", err);
                }

                var actualValue = channelData[0].Value;

                Assert.That(actualValue, Is.InRange(expectedValue - 50, expectedValue + 50));
            }
            finally
            {
                err = ITCMM.ITC_CloseDevice(device);
                Assert.AreEqual(ITCMM.ACQ_SUCCESS,
                                err,
                                ErrorDescription.ErrorString(err)
                                );
            }
        }
Esempio n. 23
0
 private void ShowSingleException(ErrorDescription error)
 {
     MessageBox.Show(this, error.ToString(), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);        
 }
 /// <summary>Default action.</summary>
 /// <param name="errorDescription">The error description.</param>
 public override ActionResult Default(ErrorDescription errorDescription)
 {
     return this.View("Default");
 }
Esempio n. 25
0
 protected void IsInvalidGuid(Guid guid, ErrorDescription error)
 {
     this.Fail(guid == Guid.Empty, error);
 }
 /// <summary>Called before the action method is invoked. Use it for error logging etc</summary>
 /// <param name="errorDescription">The error description.</param>
 protected override void HandleError(ErrorDescription errorDescription)
 {
     // TODO: Add a logging code here (just a reminder).
 }
Esempio n. 27
0
 private void ShowSingleException(ErrorDescription error)
 {
     MessageBox.Show(this, error.ToString(), Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
Esempio n. 28
0
 /// <summary>
 /// 获取错误说明
 /// </summary>
 /// <param name="errcode"></param>
 /// <returns></returns>
 protected string GetErrorCodeDescription(int errcode) => ErrorDescription.Where(d => d.Key == errcode).Select(d => d.Value).FirstOrDefault();
Esempio n. 29
0
        /// <summary>
        /// Updates the UI with details from the job
        /// </summary>
        /// <param name="job">The job must always be non-null</param>
        public void SetJob(BITS.IBackgroundCopyJob job)
        {
            Job = job ?? throw new ArgumentNullException("job");

            // Update the details
            BITS.BG_JOB_STATE currState;
            Job.GetState(out currState);

            // time details (Create/Modified/Completed)
            // The DateTime.ToString("F") makes a date + time string in the user's locale.
            BITS._BG_JOB_TIMES times;
            Job.GetTimes(out times);

            var time = MakeDateTime(times.CreationTime);

            _uiJobCreationTime.Text = time > DateTime.MinValue
                ? time.ToString("F")
                : Properties.Resources.JobTimeNotSet;

            time = MakeDateTime(times.ModificationTime);
            _uiJobModificationTime.Text = time > DateTime.MinValue
                ? time.ToString("F")
                : Properties.Resources.JobTimeNotSet;

            time = MakeDateTime(times.TransferCompletionTime);
            _uiJobTransferCompletionTime.Text = time > DateTime.MinValue
                ? time.ToString("F")
                : Properties.Resources.JobTimeNotSet;

            // Progress details (Bytes/Files)
            BITS._BG_JOB_PROGRESS progress;
            Job.GetProgress(out progress);
            var files = String.Format(
                Properties.Resources.JobProgressFileCount,
                progress.FilesTransferred,
                progress.FilesTotal);
            var bytes = progress.BytesTotal == ulong.MaxValue
                ? String.Format(
                Properties.Resources.JobProgressByteCountUnknown,
                progress.BytesTransferred)
                : String.Format(
                Properties.Resources.JobProgressByteCount,
                progress.BytesTransferred, progress.BytesTotal);

            _uiJobProgressFiles.Text = files;
            _uiJobProgressBytes.Text = bytes;

            // Error details (HRESULT, Context, Description)
            uint NError = 0;

            BITS.IBackgroundCopyError Error;
            BITS.BG_ERROR_CONTEXT     ErrorContext;
            int    ErrorHRESULT;
            string ErrorContextDescription;
            string ErrorDescription;
            int    langid = System.Globalization.CultureInfo.CurrentUICulture.LCID;

            langid = (langid & 0xFFFF); // Equivilent of LANGIDFROMLCID(GetThreadLocale()). BITS takes in the LANGID

            Job.GetErrorCount(out NError);
            if (NError == 0)
            {
                _uiJobErrorCount.Text = Properties.Resources.JobErrorNoErrors;
                _uiJobError.Text      = "";
            }
            else // (NError > 0)
            {
                _uiJobErrorCount.Text = NError.ToString("N0"); // Locale-specific numeric with no decimal places

                if (currState != BITS.BG_JOB_STATE.BG_JOB_STATE_ERROR &&
                    currState != BITS.BG_JOB_STATE.BG_JOB_STATE_TRANSIENT_ERROR)
                {
                    _uiJobError.Text = Properties.Resources.JobErrorWhenError;
                }
                else
                {
                    try
                    {
                        Job.GetError(out Error);
                        Error.GetError(out ErrorContext, out ErrorHRESULT);
                        Error.GetErrorDescription((uint)langid, out ErrorDescription);
                        Error.GetErrorContextDescription((uint)langid, out ErrorContextDescription);

                        var errorText = String.Format("\t{0} \t0x{1:X08}\n\t{2} \t{3}{4}\t{5} \t{6}",
                                                      Properties.Resources.JobErrorHRESULT,
                                                      ErrorHRESULT,
                                                      Properties.Resources.JobErrorDescription,
                                                      ErrorDescription,
                                                      ErrorDescription.EndsWith("\n") ? "" : "\n",
                                                      Properties.Resources.JobErrorContext,
                                                      ErrorContextDescription
                                                      );
                        _uiJobError.Text = errorText;
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        _uiJobError.Text = Properties.Resources.JobErrorException;
                    }
                }
            }

            string jobOwner;

            Job.GetOwner(out jobOwner);

            // convert the user sid to a domain\name
            var identifier = new System.Security.Principal.SecurityIdentifier(jobOwner);

            if (identifier.IsValidTargetType(typeof(System.Security.Principal.NTAccount)))
            {
                string account = identifier.Translate(typeof(System.Security.Principal.NTAccount)).ToString();
                _uiJobOwner.Text = account;
            }
            else
            {
                _uiJobOwner.Text = jobOwner;
            }

            // Job priority details
            BITS.BG_JOB_PRIORITY jobPriority;
            Job.GetPriority(out jobPriority);
            _uiJobPriority.Text = BitsConversions.ConvertJobPriorityToString(jobPriority);

            // Job Type details
            BITS.BG_JOB_TYPE jobType;
            Job.GetType(out jobType);
            _uiJobType.Text = BitsConversions.ConvertJobTypeToString(jobType);

            // Job State details
            BITS.BG_JOB_STATE jobState;
            Job.GetState(out jobState);
            _uiJobState.Text = BitsConversions.ConvertJobStateToString(jobState);

            // Values from IBackgroundCopyJob5 Property interface
            // COST_FLAGS, DYNAMIC_CONTENT, HIGH_PERFORMANCE, ON_DEMAND_MODE
            BITS5.IBackgroundCopyJob5 job5 = job as BITS5.IBackgroundCopyJob5;
            if (job5 == null)
            {
                _uiJobCost.Text  = Properties.Resources.JobCostNotAvailable;
                _uiJobFlags.Text = Properties.Resources.JobFlagsNotAvailable;
            }
            else
            {
                BITS5.BITS_JOB_PROPERTY_VALUE cost;
                job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_ID_COST_FLAGS, out cost);
                var costString = BitsConversions.ConvertCostToString((BitsCosts)cost.Dword);
                _uiJobCost.Text = costString;

                var flagBuilder = new StringBuilder();
                BITS5.BITS_JOB_PROPERTY_VALUE flagValue;
                job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_DYNAMIC_CONTENT, out flagValue);
                if (flagValue.Enable != 0)
                {
                    if (flagBuilder.Length > 0)
                    {
                        flagBuilder.Append(", ");
                    }
                    flagBuilder.Append(Properties.Resources.JobFlagsDynamic);
                }

                job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_HIGH_PERFORMANCE, out flagValue);
                if (flagValue.Enable != 0)
                {
                    if (flagBuilder.Length > 0)
                    {
                        flagBuilder.Append(", ");
                    }
                    flagBuilder.Append(Properties.Resources.JobFlagsHighPerformance);
                }

                job5.GetProperty(BITS5.BITS_JOB_PROPERTY_ID.BITS_JOB_PROPERTY_ON_DEMAND_MODE, out flagValue);
                if (flagValue.Enable != 0)
                {
                    if (flagBuilder.Length > 0)
                    {
                        flagBuilder.Append(", ");
                    }
                    flagBuilder.Append(Properties.Resources.JobFlagsOnDemandMode);
                }

                if (flagBuilder.Length == 0)
                {
                    flagBuilder.Append(Properties.Resources.JobFlagsNoneSet);
                }
                _uiJobFlags.Text = flagBuilder.ToString();
            }

            // Get the JobHttpOptions custom method
            var httpOptions2 = Job as BITS10_2.IBackgroundCopyJobHttpOptions2;

            if (httpOptions2 == null)
            {
                _uiJobHttpMethod.Text = Properties.Resources.JobHttpMethodNotAvailable;
            }
            else
            {
                string httpMethod;
                try
                {
                    httpOptions2.GetHttpMethod(out httpMethod);
                    _uiJobHttpMethod.Text = httpMethod ?? Properties.Resources.JobHttpMethodNotSet;
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    _uiJobHttpMethod.Text = String.Format(Properties.Resources.JobHttpMethodException, ex.Message);
                }
            }

            // Get the HttpJobOptions
            var httpOptions = Job as BITS4.IBackgroundCopyJobHttpOptions;

            if (httpOptions == null)
            {
                _uiJobCustomHeaders.Text = Properties.Resources.JobCustomHeadersNotAvailable;
            }
            else
            {
                string customHeaders;
                try
                {
                    httpOptions.GetCustomHeaders(out customHeaders);
                    var headers = customHeaders == null
                        ? Properties.Resources.JobCustomHeadersNotSet
                        : TabifyHttpHeaders.AddTabs(TabifyHttpHeaders.PrependCRLF(customHeaders))
                    ;
                    _uiJobCustomHeaders.Text = headers;
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    _uiJobCustomHeaders.Text = String.Format(
                        Properties.Resources.JobCustomHeadersException,
                        ex.Message);
                }
                catch (System.UnauthorizedAccessException ex)
                {
                    _uiJobCustomHeaders.Text = String.Format(
                        Properties.Resources.JobCustomHeadersException,
                        ex.Message);
                }
            }

            // Update the list of files associated with the job.
            ListBITSJobFiles(Job);
        }
 /// <summary>Default action.</summary>
 /// <param name="errorDescription">The error description.</param>
 public override ActionResult Default(ErrorDescription errorDescription)
 {
     return(this.View("Default"));
 }
 partial void InsertErrorDescription(ErrorDescription instance);
 /// <summary>Called before the action method is invoked. Use it for error logging etc</summary>
 /// <param name="errorDescription">The error description.</param>
 protected override void HandleError(ErrorDescription errorDescription)
 {
     // TODO: Add a logging code here (just a reminder).
 }
 partial void DeleteErrorDescription(ErrorDescription instance);
Esempio n. 34
0
 protected void IsInvalidName(string s, ErrorDescription error)
 {
     this.Fail(string.IsNullOrWhiteSpace(s), error);
 }
Esempio n. 35
0
        public static string GenericValidation(string strControlText, string strControlCaption, bool bMandatory,
                                               string strValidationType, string strValidationErrorCode, string ControlType)
        {
            string strErrorMessage = string.Empty;

            if (bMandatory)
            {
                //code for mandatory check
                switch (ControlType)
                {
                case "ctlTextBox":
                    if (strControlText.Trim() == string.Empty)
                    {
                        strErrorMessage = ErrorDescription.Empty + "<br/>";
                    }
                    break;

                case "ctlTextArea":
                    if (strControlText.Trim() == string.Empty)
                    {
                        strErrorMessage = ErrorDescription.Empty + "<br/>";
                    }
                    break;

                case "ctlDropDownList":
                    if (strControlText.Trim() == "0")
                    {
                        strErrorMessage = ErrorDescription.InvalidSelect + "<br/>";
                    }
                    break;

                case "ctlCheckBoxList":
                    if (strControlText.Trim() == string.Empty)
                    {
                        strErrorMessage = ErrorDescription.InvalidSelect + "<br/>";
                    }
                    break;

                case "ctlRadioButton":
                    if (strControlText.Trim().ToLower() == "false")
                    {
                        strErrorMessage = ErrorDescription.InvalidSelect + "<br/>";
                    }
                    break;
                }
            }

            if ((strValidationType != "0") && (strValidationErrorCode != "0"))
            {
                if ((strErrorMessage == string.Empty) && (strControlText.Trim() != string.Empty))
                {
                    //code for regex validations
                    var       objRegexConstants = new RegexConstants();
                    Type      objRegexType      = objRegexConstants.GetType();
                    FieldInfo objFieldInfo      = objRegexType.GetField(strValidationType);
                    string    strRegex          = objFieldInfo.GetValue(objRegexConstants).ToString();

                    //code for regex match and error generation
                    var objRegex = new Regex(strRegex);
                    if (!objRegex.IsMatch(strControlText.Trim()))
                    {
                        //code for generating error message for validation failure
                        var       objErrorMessageConstants = new ErrorDescription();
                        Type      objErrorType             = objErrorMessageConstants.GetType();
                        FieldInfo objErrorFieldInfo        = objErrorType.GetField(strValidationErrorCode);
                        strErrorMessage = objErrorFieldInfo.GetValue(objErrorMessageConstants) + "<br/>";
                    }
                }
            }
            return(strErrorMessage.Replace("#$#", strControlCaption.Trim()));
        }
Esempio n. 36
0
 public HekaDAQException(string msg, uint errorCode) :
     base(msg)
 {
     HekaError     = ErrorDescription.ErrorString(errorCode);
     HekaErrorCode = errorCode;
 }
Esempio n. 37
0
        private void SavePersonInBackendSystems()
        {
            var message = new ErrorDescription("Registration succeeded.", new Information());

            _person.Errors.Add(message);
        }
Esempio n. 38
0
    private void OnError(ErrorDescription errorDescription)
    {
        switch (errorDescription.error)
        {
        case Error.PasswordResetingNotAllowedForProject:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.TokenVerificationException:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.RegistrationNotAllowedException:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.UsernameIsTaken:
            OpenPopUp("Username Is Taken.", PopUpWindows.Error);
            break;

        case Error.EmailIsTaken:
            OpenPopUp("Email Is Taken", PopUpWindows.Error);
            break;

        case Error.UserIsNotActivated:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.CaptchaRequiredException:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.InvalidProjectSettings:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.InvalidLoginOrPassword:
            OpenPopUp("Wrong username or password", PopUpWindows.Error);
            break;

        case Error.MultipleLoginUrlsException:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.SubmittedLoginUrlNotFoundException:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;

        case Error.InvalidToken:
            OpenPopUp("Invalid Token", PopUpWindows.Error);
            break;

        case Error.NetworkError:
            OpenPopUp(string.Format("Network Error: {0}", errorDescription.description), PopUpWindows.Error);
            break;

        case Error.IdentifiedError:
            OpenPopUp(errorDescription.ToString(), PopUpWindows.Error);
            break;
        }
    }
        private void DisplayErrors(IList<ProgramLine> errorLines)
        {
            IList<ErrorDescription> errors = new List<ErrorDescription>();
            textMarkerService.Clear();

            foreach (ProgramLine errorLine in errorLines)
            {
                ErrorDescription error = new ErrorDescription()
                {
                    LineNumber = errorLine.LineNumber,
                    LineAddress = errorLine.LineAddress,
                    StartColumnIndex = errorLine.Error.StartColumnIndex,
                    EndColumnIndex = errorLine.Error.EndColumnIndex,
                    ErrorMessage = errorLine.Error.ErrorMessage
                };
                errors.Add(error);

                int offset = textEditor.Document.GetOffset(new TextLocation(error.LineNumber, error.StartColumnIndex));
                int endOffset = textEditor.Document.GetOffset(new TextLocation(error.LineNumber, error.EndColumnIndex));
                int length = endOffset - offset;
                if (length < 2)
                {
                    length = Math.Min(2, textEditor.Document.TextLength - offset);
                }
                textMarkerService.Create(offset, length, error.ErrorMessage);
            }

            errorsListView.ItemsSource = errors;
        }