Example #1
0
        public static Fault ParseXml(System.Xml.Linq.XElement fault_el)
        {
            var value_el = fault_el.GetElement("value");
            var fault_value = (Struct)XmlRpc.Value.ParseXml(value_el);

            int fault_code = -1;
            var fault_code_val = fault_value.Get("faultCode");
            if (fault_code_val != null)
            {
                if (fault_code_val is StringValue)
                {
                    var s = (StringValue)fault_code_val;
                    fault_code = int.Parse(s.String);
                }
                else if (fault_code_val is IntegerValue)
                {
                    var i = (IntegerValue)fault_code_val;
                    fault_code = i.Integer;
                }
                else
                {
                    string msg = string.Format("Fault Code value is not int or string {0}", value_el.ToString());
                    throw new MetaWeblogException(msg);
                }
            }

            string fault_string = fault_value.Get<StringValue>("faultString").String;

            var f = new Fault();
            f.FaultCode = fault_code;
            f.FaultString = fault_string;
            f.RawData = fault_el.Document.ToString();
            return f;
        }
Example #2
0
		public static bool Activate(Fault fault)
		{
			if (fault == null)
				return false;

			fault.TryActivate();
			return fault.IsActivated;
		}
        protected static void Because_of()
        {
            client = new HttpClient(ServiceUrl["Location"] +
                "crossmap?source-system=" + trayport.Name + "&destination-system=" + endur.Name + "&mapping-string=" + trayportMapping.MappingValue);

            response = client.Get();

            mappingResponse = response.Content.ReadAsDataContract<EnergyTrading.Mdm.Contracts.Fault>();
        }
        public ErrorEvent(Fault fault)
        {
            this.Fault = fault;

            if (fault != null)
            {
                this.Error = fault.Message;
            }
        }
 public CcDepositResponse FromClearingFault(Fault<ClearingRequest> source)
 {
     return new CcDepositResponse
         {
             AccountNumber = source.Message.AccountNumber,
             Status = DepositStatus.Failed,
             ErrorMessage = $"Clearing Api call failed. FaultId={source.FaultId} Host={source.Host.MachineName}",
             TransactionId = source.Message.TransactionId
         };
 }
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="result">The result of the analysis</param>
		/// <param name="firstFault">The fault that must be activated first.</param>
		/// <param name="secondFault">The fault that must be activated subsequently.</param>
		/// <param name="kind">Determines the kind of the order relationship.</param>
		internal OrderRelationship(AnalysisResult result, Fault firstFault, Fault secondFault, OrderRelationshipKind kind)
		{
			Requires.NotNull(result, nameof(result));
			Requires.NotNull(firstFault, nameof(firstFault));
			Requires.NotNull(secondFault, nameof(secondFault));
			Requires.InRange(kind, nameof(kind));

			Witness = result.CounterExample;
			FirstFault = firstFault;
			SecondFault = secondFault;
			Kind = kind;
		}
 private static Fault FaultFor(HttpResponseMessage response)
 {
     Fault fault;
     try
     {
         fault = response.Content.ReadAsDataContract<Fault>();
     }
     catch (Exception)
     {
         fault = new Fault() {Message = response.StatusCode.ToString()};
     }
     return fault;
 }
		/// <summary>
		///     Initializes a new instance.
		/// </summary>
		/// <param name="fault">The fault the fault effect belongs to.</param>
		/// <param name="faultEffect">The CLR method the metadata is provided for.</param>
		/// <param name="affectedMethod">The CLR method representing the method affected by the fault effect.</param>
		/// <param name="name">The name of the fault effect; if <c>null</c>, the method's CLR name is used.</param>
		internal FaultEffectMetadata(Fault fault, MethodInfo faultEffect, MethodInfo affectedMethod, string name = null)
			: base(fault, faultEffect, name)
		{
			Requires.NotNull(fault, () => fault);
			Requires.NotNull(faultEffect, () => faultEffect);
			Requires.NotNull(affectedMethod, () => affectedMethod);

			_affectedMethod = affectedMethod;

			var priorityAttribute = faultEffect.GetCustomAttribute<PriorityAttribute>();
			if (priorityAttribute != null)
				Priority = priorityAttribute.Priority;
		}
        private Fault GetFault(HttpResponseMessage response)
        {
            Fault fault;
            try
            {
                fault = response.Content.ReadAsAsync<Fault>().Result;
            }
            catch (Exception)
            {
                fault = new Fault { Message = response.StatusCode.ToString() };
            }

            return fault;
        }
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var exception = actionExecutedContext.Exception;

            if (exception is VersionConflictException || exception is ValidationException)
            {
                var fault = new Fault
                {
                    Message = actionExecutedContext.Exception.Message,
                    Reason = "Validation failure"
                };

                var statusCode = exception is VersionConflictException
                                     ? HttpStatusCode.PreconditionFailed
                                     : HttpStatusCode.BadRequest;

                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(statusCode, fault);
            }
            else if (exception is NotFoundException)
            {
                var fault = new Fault
                {
                    Message = exception.Message,
                    Reason = exception.Message
                };

                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.NotFound, fault);
            }
            else if (exception is MdmFaultException)
            {
                // At the moment, any such exceptions are returned as NotFound, but this may need to be changed if other exception types are bundled up
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.NotFound, ((MdmFaultException)exception).Fault);
            }
            else if (actionExecutedContext.Exception is NotImplementedException)
            {
                actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
            else
            {
                var fault = new Fault
                {
                    Message = actionExecutedContext.Exception.AllExceptionMessages(),
                    Reason = "Unknown"
                };

                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError, fault);
            }
        }
Example #11
0
        public void ShowFault(Fault fault)
        {
            var error = "Error occured!";

            if (fault.Reason != null && fault.Reason.Length > 0 && !string.IsNullOrEmpty(fault.Reason[0].Value))
            {
                error = fault.Reason[0].Value;
            }

            MessageBox.Show(
                this,
                error,
                Title,
                MessageBoxButton.OK,
                MessageBoxImage.Error);
        }
        public void CreateEntityFails()
        {
            var requester = new Mock<IMessageRequester>();
            var service = new MdmEntityService<SourceSystem>("sourcesystem", requester.Object);
            var fault = new Fault() { Message = "faulting" };

            requester.Setup(x => x.Create<SourceSystem>(It.IsAny<string>(), It.IsAny<SourceSystem>(), It.IsAny<MdmRequestInfo>())).Returns(new WebResponse<SourceSystem>() { Code = HttpStatusCode.InternalServerError, IsValid = false, Fault = fault });

            // Act
            var result = service.Create(new SourceSystem());

            // Assert
            Assert.AreEqual(HttpStatusCode.InternalServerError, result.Code, "Status code differ");
            Assert.AreEqual(false, result.IsValid, "IsValid differ");
            Assert.AreEqual(fault, result.Fault, "Fault not returned");
        }
        public void can_notify_failure_of_CreateOrderMessage()
        {
            var message = new OrderRequestReceivedMessage {BusinessPartnerCode = "WWT"};
            var exception = new Exception("Test Exception");
            var fault = new Fault<OrderRequestReceivedMessage>(message, exception);

            _sut.NotifyFailureOf(fault);

            _notificationSender.Verify(x => x.SendNotification(
                                                It.IsAny<string>(),
                                                It.Is<IList<EmailAddress>>(
                                                    a =>
                                                    a[0].Address ==
                                                    EmailAddressConstants.InformationtechnologygroupEmailAddress &&
                                                    a[1].Address == EmailAddressConstants.LogisticsEmailAddress),
                                                It.Is<string>(body => body.Contains(message.ToString()) &&
                                                                      body.Contains(exception.ToString()))));
        }
        private Exception CreateException()
        {
            var fault = new Fault
            {
                Message = "hello",
                ErrorCode = "B29",
                Inner = new Fault
                {
                    Message = "there",
                    ErrorCode = "oops"
                }
            };

            var ex = new FaultException<Fault>(fault, "this is the reason");

            ex.Data.Add("key1", "value");
            ex.Data.Add("key2", "value");
            ex.Data.Add("key3", "value");

            return ex;
        }
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="firstFault">The fault that is expected to be activated first.</param>
		/// <param name="secondFault">The fault that is expected to be activated subsequently.</param>
		/// <param name="forceSimultaneous">Indicates whether both faults must occur simultaneously.</param>
		public FaultOrderModifier(Fault firstFault, Fault secondFault, bool forceSimultaneous)
		{
			_firstFault = firstFault;
			_secondFault = secondFault;
			_forceSimultaneous = forceSimultaneous;
		}
Example #16
0
 public void AddFault(Fault _fault)
 {
     fault = _fault;
 }
Example #17
0
			public C2(Fault f = null)
			{
				f.AddEffect<E>(this);
			}
Example #18
0
        private void PopulateFaultInfo(Fault fault, DataGroup dataGroup, VICycleDataGroup viCycleDataGroup)
        {
            int      samplesPerCycle  = (int)Math.Round(dataGroup[0].SampleRate / m_systemFrequency);
            int      calculationCycle = GetCalculationCycle(fault, viCycleDataGroup, samplesPerCycle);
            DateTime startTime        = dataGroup[0][fault.StartSample].Time;
            DateTime endTime          = dataGroup[0][fault.EndSample].Time;

            List <Fault.Summary> validSummaries;

            Fault.Summary summary;

            fault.CalculationCycle = calculationCycle;
            fault.InceptionTime    = startTime;
            fault.ClearingTime     = endTime;
            fault.Duration         = endTime - startTime;
            fault.PrefaultCurrent  = GetPrefaultCurrent(fault, dataGroup, viCycleDataGroup);
            fault.PostfaultCurrent = GetPostfaultCurrent(fault, dataGroup, viCycleDataGroup);
            fault.IsSuppressed     = GetPostfaultPeak(fault, dataGroup, viCycleDataGroup) > m_breakerSettings.OpenBreakerThreshold;

            if (fault.Segments.Any())
            {
                fault.Type = fault.Segments
                             .Where(segment => segment.StartSample <= fault.CalculationCycle)
                             .Where(segment => fault.CalculationCycle <= segment.EndSample)
                             .Select(segment => segment.FaultType)
                             .FirstOrDefault();

                fault.CurrentMagnitude = GetFaultCurrentMagnitude(viCycleDataGroup, fault.Type, calculationCycle);
                fault.CurrentLag       = GetFaultCurrentLag(viCycleDataGroup, fault.Type, calculationCycle);
            }

            if (calculationCycle >= 0)
            {
                for (int i = 0; i < fault.Curves.Count; i++)
                {
                    summary = new Fault.Summary();
                    summary.DistanceAlgorithmIndex = i;
                    summary.DistanceAlgorithm      = fault.Curves[i].Algorithm;
                    summary.Distance = fault.Curves[i][calculationCycle].Value;
                    summary.IsValid  = IsValid(summary.Distance, dataGroup);

                    fault.Summaries.Add(summary);
                }

                if (fault.Summaries.Any(s => !s.IsValid))
                {
                    fault.IsSuppressed |= fault.CurrentLag < 0;
                }

                validSummaries = fault.Summaries
                                 .Where(s => s.IsValid)
                                 .OrderBy(s => s.Distance)
                                 .ToList();

                if (!validSummaries.Any())
                {
                    validSummaries = fault.Summaries
                                     .Where(s => !double.IsNaN(s.Distance))
                                     .OrderBy(s => s.Distance)
                                     .ToList();
                }

                if (validSummaries.Any())
                {
                    validSummaries[validSummaries.Count / 2].IsSelectedAlgorithm = true;
                }
            }
            else
            {
                fault.IsSuppressed = true;
            }
        }
Example #19
0
        public virtual IEnumerator <ITask> ConnectToBrickHandler(ConnectToBrick update)
        {
            // Validate the sensor port.
            if ((update.Body.SensorPort & NxtSensorPort.AnySensorPort)
                != update.Body.SensorPort)
            {
                update.ResponsePort.Post(
                    Fault.FromException(
                        new ArgumentException(
                            string.Format("Invalid Sensor Port: {0}",
                                          ((LegoNxtPort)update.Body.SensorPort)))));
                yield break;
            }

            _state.SensorPort = update.Body.SensorPort;
            _state.Connected  = false;

            if (!string.IsNullOrEmpty(update.Body.Name))
            {
                _state.Name = update.Body.Name;
            }
            _state.PollingFrequencyMs = update.Body.PollingFrequencyMs;

            Fault fault = null;

            pxbrick.Registration registration = new pxbrick.Registration(
                new LegoNxtConnection((LegoNxtPort)_state.SensorPort),
                LegoDeviceType.DigitalSensor,
                Contract.DeviceModel,
                Contract.Identifier,
                ServiceInfo.Service,
                _state.Name);

            // Reserve the port
            yield return(Arbiter.Choice(_legoBrickPort.ReserveDevicePort(registration),
                                        delegate(pxbrick.AttachResponse reserveResponse)
            {
                if (reserveResponse.DeviceModel == registration.DeviceModel)
                {
                    registration.Connection = reserveResponse.Connection;
                }
            },
                                        delegate(Fault f)
            {
                fault = f;
                LogError(fault);
                registration.Connection.Port = LegoNxtPort.NotConnected;
            }));


            if (registration.Connection.Port == LegoNxtPort.NotConnected)
            {
                if (fault == null)
                {
                    fault = Fault.FromException(new Exception("Failure Configuring HiTechnic Compass on Port " + update.Body.ToString()));
                }
                update.ResponsePort.Post(fault);
                yield break;
            }

            pxbrick.AttachRequest attachRequest = new pxbrick.AttachRequest(registration);

            attachRequest.InitializationCommands = new nxtcmd.NxtCommandSequence(
                new nxtcmd.LegoSetInputMode((NxtSensorPort)registration.Connection.Port, LegoSensorType.I2C_9V, LegoSensorMode.RawMode));

            attachRequest.PollingCommands = new nxtcmd.NxtCommandSequence(_state.PollingFrequencyMs,
                                                                          new I2CReadHiTechnicCompassSensor(_state.SensorPort));

            pxbrick.AttachResponse response = null;

            yield return(Arbiter.Choice(_legoBrickPort.AttachAndSubscribe(attachRequest, _legoBrickNotificationPort),
                                        delegate(pxbrick.AttachResponse rsp) { response = rsp; },
                                        delegate(Fault f) { fault = f; }));

            if (response == null)
            {
                if (fault == null)
                {
                    fault = Fault.FromException(new Exception("Failure Configuring HiTechnic Compass"));
                }
                update.ResponsePort.Post(fault);
                yield break;
            }

            _state.Connected = (response.Connection.Port != LegoNxtPort.NotConnected);
            if (_state.Connected)
            {
                _state.SensorPort = (NxtSensorPort)response.Connection.Port;
            }
            else if (update.Body.SensorPort != NxtSensorPort.NotConnected)
            {
                update.ResponsePort.Post(Fault.FromException(new Exception(string.Format("Failure Configuring HiTechnic Compass on port: {0}", update.Body.SensorPort))));
                yield break;
            }

            // Set the compass name
            if (string.IsNullOrEmpty(_state.Name) ||
                _state.Name.StartsWith("Compass Sensor on "))
            {
                _state.Name = "Compass Sensor on " + response.Connection.Port.ToString();
            }

            // Send a notification of the connected port
            update.Body.Name = _state.Name;
            update.Body.PollingFrequencyMs = _state.PollingFrequencyMs;
            update.Body.SensorPort         = _state.SensorPort;
            SendNotification <ConnectToBrick>(_subMgrPort, update);

            // Send the message response
            update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }
Example #20
0
 public virtual IEnumerator <ITask> ReplaceHandler(pxanalogsensor.Replace replace)
 {
     replace.ResponsePort.Post(Fault.FromException(new InvalidOperationException("The HiTechnic Compass sensor is updated from hardware.")));
     yield break;
 }
 public static string GetExceptionMessages(this Fault faulted)
 {
     return(faulted.Exceptions != null?string.Join(Environment.NewLine, faulted.Exceptions.Select(x => x.Message)) : string.Empty);
 }
Example #22
0
        public virtual IEnumerator <ITask> ConnectToBrickHandler(ConnectToBrick update)
        {
            // Validate the sensor port.
            if ((update.Body.SensorPort & NxtSensorPort.AnySensorPort)
                != update.Body.SensorPort)
            {
                update.ResponsePort.Post(
                    Fault.FromException(
                        new ArgumentException(
                            string.Format("Invalid Sensor Port: {0}",
                                          ((LegoNxtPort)update.Body.SensorPort)))));
                yield break;
            }

            _state.SensorPort = update.Body.SensorPort;
            _state.Connected  = false;

            if (!string.IsNullOrEmpty(update.Body.Name))
            {
                _state.Name = update.Body.Name;
            }
            _state.PollingFrequencyMs = update.Body.PollingFrequencyMs;
            _state.SensorMode         = update.Body.SensorMode;

            // Set the hardware identifier from the connected sensor port.
            _genericState.HardwareIdentifier = NxtCommon.HardwareIdentifier(_state.SensorPort);

            Fault fault = null;

            brick.AttachRequest attachRequest = new brick.AttachRequest(
                new brick.Registration(
                    new LegoNxtConnection((LegoNxtPort)_state.SensorPort),
                    LegoDeviceType.AnalogSensor,
                    Contract.DeviceModel,
                    Contract.Identifier,
                    ServiceInfo.Service,
                    _state.Name));

            // Get the correct code for the Sensor Type that the Brick understands
            LegoSensorType st;

            switch (_state.SensorMode)
            {
            case ColorSensorMode.Color:
                st = LegoSensorType.ColorFull;
                break;

            case ColorSensorMode.Red:
                st = LegoSensorType.ColorRed;
                break;

            case ColorSensorMode.Green:
                st = LegoSensorType.ColorGreen;
                break;

            case ColorSensorMode.Blue:
                st = LegoSensorType.ColorBlue;
                break;

            case ColorSensorMode.None:
                st = LegoSensorType.ColorNone;
                break;

            default:
                st = LegoSensorType.ColorFull;
                break;
            }

            // The Color Sensor is a special case of an Analog sensor so if uses the
            // LegoSetInputMode request. Note that it is in Raw mode.
            attachRequest.InitializationCommands = new NxtCommandSequence(
                new LegoSetInputMode(_state.SensorPort, st, LegoSensorMode.RawMode));

            // Polling uses LegoGetInputValues to read the analog value
            attachRequest.PollingCommands = new NxtCommandSequence(_state.PollingFrequencyMs,
                                                                   new LegoGetInputValues(_state.SensorPort));

            brick.AttachResponse response = null;

            yield return(Arbiter.Choice(_legoBrickPort.AttachAndSubscribe(attachRequest, _legoBrickNotificationPort),
                                        delegate(brick.AttachResponse rsp) { response = rsp; },
                                        delegate(Fault f) { fault = f; }));

            if (response == null)
            {
                if (fault == null)
                {
                    fault = Fault.FromException(new Exception("Failure Configuring NXT Color Sensor"));
                }
                update.ResponsePort.Post(fault);
                yield break;
            }

            _state.Connected = (response.Connection.Port != LegoNxtPort.NotConnected);
            if (_state.Connected)
            {
                _state.SensorPort = (NxtSensorPort)response.Connection.Port;
            }
            else if (update.Body.SensorPort != NxtSensorPort.NotConnected)
            {
                fault = Fault.FromException(new Exception("Failure Configuring NXT Color Sensor on Port " + update.Body.ToString()));
                update.ResponsePort.Post(fault);
                yield break;
            }

            // Set the Color Sensor name
            if (string.IsNullOrEmpty(_state.Name) ||
                _state.Name.StartsWith("Color Sensor on "))
            {
                _state.Name = "Color Sensor on " + response.Connection.ToString();
            }

            // Send a notification of the connected port
            // Only send connection notifications to native subscribers
            update.Body.Name = _state.Name;
            update.Body.PollingFrequencyMs = _state.PollingFrequencyMs;
            update.Body.SensorPort         = _state.SensorPort;
            update.Body.SensorMode         = _state.SensorMode;
            SendNotification <ConnectToBrick>(_subMgrPort, update);

            update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }
Example #23
0
        public virtual IEnumerator <ITask> SetModeHandler(SetMode setMode)
        {
            _state.SensorMode = setMode.Body.Mode;

            // Convert Sensor Mode to a Sensor Type
            // The Color Sensor has several sensor types just for it
            LegoSensorType st;

            switch (_state.SensorMode)
            {
            case ColorSensorMode.Color:
                st = LegoSensorType.ColorFull;
                break;

            case ColorSensorMode.Red:
                st = LegoSensorType.ColorRed;
                break;

            case ColorSensorMode.Green:
                st = LegoSensorType.ColorGreen;
                break;

            case ColorSensorMode.Blue:
                st = LegoSensorType.ColorBlue;
                break;

            case ColorSensorMode.None:
                st = LegoSensorType.ColorNone;
                break;

            default:
                st = LegoSensorType.ColorFull;
                break;
            }

            LegoSetInputMode cmd = new LegoSetInputMode(_state.SensorPort, st, LegoSensorMode.RawMode);

            _legoBrickPort.SendNxtCommand(cmd);

            yield return(Arbiter.Choice(_legoBrickPort.SendNxtCommand(cmd),
                                        delegate(LegoResponse response)
            {
                if (response.Success)
                {
                    setMode.ResponsePort.Post(DefaultUpdateResponseType.Instance);
                    // SetMode notifications are only sent to subscribers to the native service
                    SendNotification <SetMode>(_subMgrPort, setMode);
                }
                else
                {
                    setMode.ResponsePort.Post(
                        Fault.FromException(
                            new InvalidOperationException(response.ErrorCode.ToString())));
                }
            },
                                        delegate(Fault fault)
            {
                setMode.ResponsePort.Post(fault);
            }));

            yield break;
        }
Example #24
0
 public static void UpdateFaultStatus(Fault f)
 {
     FaultDAL.UpdateStatus(FaultConverter.ToDAL(f));
 }
Example #25
0
 public static void AddFault(Fault fault)
 {
     FaultDAL.Add(FaultConverter.ToDAL(fault));
 }
Example #26
0
 private List <XElement> GetSegmentElements(Fault fault)
 {
     return(fault.Segments
            .Select(GetSegmentElement)
            .ToList());
 }
 public virtual IEnumerator <ITask> AccelerometerUpdateHandler(AccelerometerUpdate update)
 {
     update.ResponsePort.Post(Fault.FromException(new InvalidOperationException("The MindSensors Accelerometer sensor is updated from hardware.")));
     yield break;
 }
Example #28
0
        public override Fault GetMonitorData()
        {
            try
            {
                logger.Debug(">> GetMonitorData");

                var fault = new Fault();
                fault.type            = FaultType.Data;
                fault.title           = "SSH Downloader: " + File != null ? File : Folder;
                fault.detectionSource = "SshDownloader";
                fault.description     = "";

                using (var client = new SftpClient(connectionInfo))
                {
                    client.Connect();

                    if (!string.IsNullOrWhiteSpace(File))
                    {
                        using (var sout = new MemoryStream())
                        {
                            logger.Debug("Trying to download \"" + File + "\".");

                            client.DownloadFile(File, sout);
                            if (Remove)
                            {
                                client.DeleteFile(File);
                            }

                            sout.Position = 0;
                            fault.collectedData[Path.GetFileName(File)] = sout.ToArray();
                        }

                        fault.description = File;

                        return(fault);
                    }

                    if (string.IsNullOrWhiteSpace(Folder))
                    {
                        return(null);
                    }

                    logger.Debug("Downloading all files from \"" + Folder + "\".");
                    foreach (var file in client.ListDirectory(Folder))
                    {
                        if (file.FullName.EndsWith("/.") || file.FullName.EndsWith("/..") || file.FullName.EndsWith(@"\.") || file.FullName.EndsWith(@"\.."))
                        {
                            logger.Debug("Skipping \"" + file.FullName + "\".");
                            continue;
                        }

                        logger.Debug("Downloading \"" + file.FullName + "\".");

                        using (var sout = new MemoryStream((int)file.Length))
                        {
                            try
                            {
                                client.DownloadFile(file.FullName, sout);
                                if (Remove)
                                {
                                    client.DeleteFile(file.FullName);
                                }

                                sout.Position = 0;
                                fault.collectedData[Path.GetFileName(file.FullName)] = sout.ToArray();

                                fault.description += file.FullName + "\n";
                            }
                            catch (Exception ex)
                            {
                                logger.Warn("Warning, could not d/l file [" + file.FullName + "]: " + ex.Message);
                                fault.description += "Warning, could not d/l file [" + file.FullName + "]\n";
                            }
                        }
                    }

                    logger.Debug("<< GetMonitorData");
                    return(fault);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                throw;
            }
        }
Example #29
0
        private void M()
        {
            Fault x = null;

            x.Name = "";
        }
Example #30
0
 void Fail(Fault <TRequest> fault)
 {
     Fail(new RequestFaultException(TypeMetadataCache <TRequest> .ShortName, fault));
 }
Example #31
0
 static void FaultDragLeave(object obj, Gtk.DragLeaveArgs args)
 {
     DestroySplitter();
     dragFault = null;
 }
 public IActionResult Create(Fault faults)
 {
     _db.Faults.Add(faults);
     _db.SaveChanges();
     return(RedirectToAction("Index", "Faults"));
 }
Example #33
0
 public virtual IEnumerator <ITask> CompassSensorUpdateHandler(CompassSensorUpdate update)
 {
     update.ResponsePort.Post(Fault.FromException(new InvalidOperationException("The HiTechnic Compass sensor is updated from hardware.")));
     yield break;
 }
Example #34
0
 public C2(Fault f = null)
 {
     f.AddEffect <E>(this);
 }
Example #35
0
        /// <summary>
        /// Extracts the Fault from the Error Response.
        /// </summary>
        /// <param name="errorString">The error string.</param>
        /// <returns>Fault object.</returns>
        private Fault ExtractFaultFromResponse(string errorString)
        {
            Fault fault = null;

            // If the error string is null return null.
            if (string.IsNullOrWhiteSpace(errorString))
            {
                return(fault);
            }

            try
            {
                //// TODO: Remove this code after service returns proper response
                //// This is put in since the service is not returning proper xml header
                ////if (!errorString.StartsWith("<?xml"))
                ////{
                ////    errorString = errorString.Insert(16, " xmlns=\"http://schema.intuit.com/finance/v3\" ");
                ////    errorString = errorString.Insert(0, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                ////}


                if (errorString.Contains("EntitlementsResponse"))
                {
                    EntitlementsResponse entitlements = (EntitlementsResponse)CoreHelper.GetSerializer(this.context, false).Deserialize <EntitlementsResponse>(errorString);
                }
                // Deserialize to IntuitResponse using the Serializer of the context.
                else
                {
                    IntuitResponse intuitResponse = (IntuitResponse)CoreHelper.GetSerializer(this.context, false).Deserialize <IntuitResponse>(errorString);

                    // Check whether the object is null or note. Also check for Items property since it has the fault.
                    if (intuitResponse != null && intuitResponse.AnyIntuitObject != null)
                    {
                        // TODO: Check whether only the first item will have fault or not.
                        // Cast the Items to Fault.
                        fault = intuitResponse.AnyIntuitObject as Fault;
                    }
                }
                // TODO: Uncomment this if exception has to be added for batch requests.
                // This is executed if the response is BatchItemResponse for batch requests.
                // else
                // {
                // Deserialize to BatchItemResponse using the Serializer of the context.
                //     BatchItemResponse batchItemResponse = (BatchItemResponse)this.context.Serializer.Deserialize<BatchItemResponse>(errorString);

                // Check whether the object is null or note. Also check for Item property since it has the fault.
                //     if (batchItemResponse != null && batchItemResponse.Item != null)
                //     {
                // Cast the Item to Fault.
                //         fault = batchItemResponse.Item as Fault;
                //     }
                // }
            }
            catch (System.Exception ex)
            {
                //Download might have Uri in body
                try
                {
                    if (new System.Uri(errorString) != null)
                    {
                        return(null);
                    }
                }
                catch (UriFormatException)
                {
                    return(null);
                }

                throw;
            }

            // Return the fault.
            return(fault);
        }
 void OnSubscribeFailed(Fault fault)
 {
     LogError(LogGroups.Console, "Failed to subscribe to camera");
     _mainPort.Post(new DsspDefaultDrop());
 }
Example #37
0
        public ActionResult Add(FaultDTO model, HttpPostedFileBase postedfile)
        {
            ViewBag.Priorities   = FaultPrioritiesRepository.GetActivePriorities();
            ViewBag.Complexities = FaultComplexityRepository.GetActiveComplexities();
            ViewBag.Companies    = CompanyRepository.GetAllActive();
            ViewBag.Enigineers   = UsersinfoRepository.GetAllActiveEngineers();
            try
            {
                if (model.CompanyId == null || model.CompanyId <= 0)
                {
                    ViewBag.Message = "Please select company";
                    ViewBag.IsError = true;
                    return(View(model));
                }
                if (string.IsNullOrEmpty(model.Location))
                {
                    ViewBag.Message = "Please enter location name";
                    ViewBag.IsError = true;
                    return(View(model));
                }
                if (model.Priority == null)
                {
                    ViewBag.Message = "Please select priority";
                    ViewBag.IsError = true;
                    return(View(model));
                }
                if (model.Complexity == null)
                {
                    ViewBag.Message = "Please select complexity";
                    ViewBag.IsError = true;
                    return(View(model));
                }
                if (model.AssignedTo == null || model.AssignedTo <= 0)
                {
                    ViewBag.Message = "Please select an engineer";
                    ViewBag.IsError = true;
                    return(View(model));
                }
                var imageLibrary = new FaultLibrary();
                if (postedfile != null)
                {
                    var filePath = SaveImage(postedfile);
                    imageLibrary.FileName     = postedfile.FileName;
                    imageLibrary.Url          = filePath;
                    imageLibrary.ModifiedBy   = this.CurrentSession.LoggedUser.Id;
                    imageLibrary.ModifiedDate = DateTime.Now;
                    imageLibrary.CreatedDate  = DateTime.Now;
                    imageLibrary.CreatedBy    = this.CurrentSession.LoggedUser.Id;
                }
                var fault = new Fault()
                {
                    CompanyId          = model.CompanyId,
                    CreatedDate        = DateTime.Now,
                    CreatedBy          = this.CurrentSession.LoggedUser.Id,
                    Complexity         = model.Complexity,
                    FaultDescription   = model.FaultDescription,
                    FaultStatus        = model.Priority < 1 ? 0 : 1,
                    Location           = model.Location,
                    MachineDescription = model.MachineDescription,
                    ModifiedBy         = this.CurrentSession.LoggedUser.Id,
                    ModifiedDate       = DateTime.Now,
                    Priority           = model.Priority,
                    StartDate          = DateTime.Now,
                    Status             = 1,
                    AssignedTo         = model.AssignedTo,
                    FaultLibraries     = new List <FaultLibrary>()
                };
                if (!string.IsNullOrEmpty(imageLibrary.Url))
                {
                    imageLibrary.FaultId = fault.Id;
                    fault.FaultLibraries.Add(imageLibrary);
                }

                FaultRepository.SaveFault(fault);
                TempData["Message"] = "Job added successfully !!!";
                TempData["IsError"] = false;
                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ViewBag.Message = "Failed to save job details";
                ViewBag.IsError = true;
            }
            return(View(model));
        }
 public RequestFaultException(string requestType, Fault fault)
     : base($"The {requestType} request faulted: {string.Join(Environment.NewLine, fault.Exceptions.Select(x => x.Message))}")
 {
     RequestType = requestType;
     Fault = fault;
 }
Example #39
0
 public void HandleError <T>(Fault <T> correlatedMessage, string errorSummary)
     where T : class
 {
     Console.WriteLine(correlatedMessage.OccurredAt);
     Console.WriteLine(correlatedMessage.StackTrace);
 }
Example #40
0
 public virtual IEnumerator <ITask> SoundSensorUpdateHandler(SoundSensorUpdate update)
 {
     update.ResponsePort.Post(Fault.FromException(new InvalidOperationException("The LEGO NXT sound sensor is updated from hardware.")));
     yield break;
 }
Example #41
0
 // Use this for initialization
 void Awake()
 {
     fault = null;
     spriteRend = GetComponent<SpriteRenderer> ();
 }
Example #42
0
 public ActionResult LogLoad(string plant)
 {
     Hashtable table = new Hashtable();
     Pager page = new Pager() { PageIndex = 1, PageSize = ComConst.PageSize };
     Fault log = new Fault() { sendTime = DateTime.Now, confirmed = null, inforank = "1,2,3", collectorID = int.Parse(plant) };
     table.Add("page", page);
     table.Add("fault", log);
     IList<Fault> logs = logService.GetPlantLoglist(table);
     ViewData["page"] = page;
     return View("logajax", logs);
 }
Example #43
0
 /// <summary>
 /// Send Http Post Failure Response
 /// </summary>
 /// <param name="httpPost"></param>
 /// <param name="fault"></param>
 private static void HttpPostFailure(HttpPost httpPost, Fault fault)
 {
     HttpResponseType rsp =
         new HttpResponseType(HttpStatusCode.BadRequest, fault);
     httpPost.ResponsePort.Post(rsp);
 }
Example #44
0
        public virtual IEnumerator <ITask> ConnectToBrickHandler(ConnectToBrick update)
        {
            // Validate the sensor port.
            if ((update.Body.SensorPort & NxtSensorPort.AnySensorPort)
                != update.Body.SensorPort)
            {
                update.ResponsePort.Post(
                    Fault.FromException(
                        new ArgumentException(
                            string.Format("Invalid Sensor Port: {0}",
                                          ((LegoNxtPort)update.Body.SensorPort)))));
                yield break;
            }

            _state.SensorPort = update.Body.SensorPort;
            _state.Connected  = false;

            if (!string.IsNullOrEmpty(update.Body.Name))
            {
                _state.Name = update.Body.Name;
            }
            _state.PollingFrequencyMs = update.Body.PollingFrequencyMs;

            _genericState.HardwareIdentifier = NxtCommon.HardwareIdentifier(_state.SensorPort);

            Fault fault = null;

            brick.AttachRequest attachRequest = new brick.AttachRequest(
                new brick.Registration(
                    new LegoNxtConnection((LegoNxtPort)_state.SensorPort),
                    LegoDeviceType.AnalogSensor,
                    Contract.DeviceModel,
                    Contract.Identifier,
                    ServiceInfo.Service,
                    _state.Name));

            attachRequest.InitializationCommands = new nxtcmd.NxtCommandSequence(
                new nxtcmd.LegoSetInputMode(_state.SensorPort, LegoSensorType.SoundDb, LegoSensorMode.PercentFullScaleMode));

            attachRequest.PollingCommands = new nxtcmd.NxtCommandSequence(_state.PollingFrequencyMs,
                                                                          new nxtcmd.LegoGetInputValues(_state.SensorPort));

            brick.AttachResponse response = null;

            yield return(Arbiter.Choice(_legoBrickPort.AttachAndSubscribe(attachRequest, _legoBrickNotificationPort),
                                        delegate(brick.AttachResponse rsp) { response = rsp; },
                                        delegate(Fault f) { fault = f; }));

            if (response == null)
            {
                if (fault == null)
                {
                    fault = Fault.FromException(new Exception("Failure Configuring NXT Sound Sensor"));
                }
                update.ResponsePort.Post(fault);
                yield break;
            }

            if (response.Connection.Port == LegoNxtPort.NotConnected && update.Body.SensorPort != NxtSensorPort.NotConnected)
            {
                if (fault == null)
                {
                    fault = Fault.FromException(new Exception("Failure Configuring NXT Sound Sensor on Port " + update.Body.ToString()));
                }
                update.ResponsePort.Post(fault);
                yield break;
            }

            _state.Connected = (response.Connection.Port != LegoNxtPort.NotConnected);
            if (_state.Connected)
            {
                _state.SensorPort = (NxtSensorPort)response.Connection.Port;
                _genericState.HardwareIdentifier = NxtCommon.HardwareIdentifier(_state.SensorPort);
            }

            // Set the motor name
            if (string.IsNullOrEmpty(_state.Name) ||
                _state.Name.StartsWith("Sound Sensor on "))
            {
                _state.Name = "Sound Sensor on " + response.Connection.ToString();
            }

            // Send a notification of the connected port
            update.Body.Name = _state.Name;
            update.Body.PollingFrequencyMs = _state.PollingFrequencyMs;
            update.Body.SensorPort         = _state.SensorPort;
            SendNotification <ConnectToBrick>(_subMgrPort, update);

            // Send the message response
            update.ResponsePort.Post(DefaultUpdateResponseType.Instance);
            yield break;
        }
 public void ShouldReturnTrueForServiceUnavailable()
 {
     var fault = new Fault { Message = "ServiceUnavailable" };
     Assert.IsTrue(fault.IsServiceUnavailable());
 }
Example #46
0
File: DND.cs Project: mono/stetic
 static void FaultDragLeave(object obj, Gtk.DragLeaveArgs args)
 {
     DestroySplitter ();
     dragFault = null;
 }
Example #47
0
 public ActionResult Log(DateTime t, int state, int plant, int pindex, string errorCode, string logList, string ctype)
 {
     string collectorString = string.Empty;
     if (plant == -1)
     {
         foreach (Plant p in UserUtil.getCurUser().displayPlants)
         {
             foreach (PlantUnit unit in p.allFactUnits)
             {
                 collectorString += string.Format("{0},", unit.collector.id);
             }
         }
     }
     else
     {
         foreach (PlantUnit unit in FindPlant(plant).plantUnits)
         {
             collectorString += string.Format("{0},", unit.collector.id);
         }
     }
     if (collectorString.Length > 1)
         collectorString = collectorString.Substring(0, collectorString.Length - 1);
     string stateStr = string.Empty;
     if (state == -1)
         stateStr = "1,0";
     else
         stateStr = state.ToString();
     Hashtable table = new Hashtable();
     Pager page = new Pager() { PageIndex = pindex, PageSize = ComConst.PageSize };
     Fault fault = new Fault() { sendTime = t, confirmed = null, inforank = errorCode.Substring(0, errorCode.Length - 1), collectorString = collectorString };
     table.Add("page", page);
     table.Add("fault", fault);
     ViewData["page"] = table["page"];
     IList<Fault> logs = null;
     try
     {
         logs = logService.GetPlantLoglist(table);
     }
     catch
     {
         logs = new List<Fault>();
     }
     return View("logajax", logs);
 }
Example #48
0
File: DND.cs Project: mono/stetic
 static void HideFaults()
 {
     foreach (Hashtable widgetFaults in faultGroups.Values) {
         foreach (Gdk.Window win in widgetFaults.Keys)
             win.Hide ();
     }
     DestroySplitter ();
     dragFault = null;
 }
Example #49
0
        private IdsException IterateFaultAndPrepareException(Fault fault)
        {
            if (fault == null)
            {
                return(null);
            }

            IdsException idsException = null;

            // Create a list of exceptions.
            List <IdsError> aggregateExceptions = new List <IdsError>();

            // Check whether the fault is null or not.
            if (fault != null)
            {
                // Fault types can be of Validation, Service, Authentication and Authorization. Run them through the switch case.
                switch (fault.type)
                {
                // If Validation errors iterate the Errors and add them to the list of exceptions.
                case "Validation":
                case "ValidationFault":
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw specific exception like ValidationException.
                        idsException = new ValidationException(aggregateExceptions);
                    }

                    break;

                // If Validation errors iterate the Errors and add them to the list of exceptions.
                case "Service":
                case "ServiceFault":
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw specific exception like ServiceException.
                        idsException = new ServiceException(aggregateExceptions);
                    }

                    break;

                // If Validation errors iterate the Errors and add them to the list of exceptions.
                case "Authentication":
                case "AuthenticationFault":
                case "Authorization":
                case "AuthorizationFault":
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw specific exception like AuthenticationException which is wrapped in SecurityException.
                        idsException = new SecurityException(aggregateExceptions);
                    }

                    break;

                // Use this as default if there was some other type of Fault
                default:
                    if (fault.Error != null && fault.Error.Count() > 0)
                    {
                        foreach (var item in fault.Error)
                        {
                            // Add commonException to aggregateExceptions
                            // CommonException defines four properties: Message, Code, Element, Detail.
                            aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail));
                        }

                        // Throw generic exception like IdsException.
                        idsException = new IdsException(string.Format(CultureInfo.InvariantCulture, "Fault Exception of type: {0} has been generated.", fault.type), aggregateExceptions);
                    }

                    break;
                }
            }

            // Return idsException which will be of type Validation, Service or Security.
            return(idsException);
        }
        IEnumerator <ITask> ProcessImage(List <ColorBin> bins)
        {
            Fault fault = null;

            cam.QueryFrameRequest request = new cam.QueryFrameRequest();
            request.Format = Guid.Empty;// new Guid("b96b3cae-0728-11d3-9d7b-0000f81ef32e");

            byte[]   frame     = null;
            DateTime timestamp = DateTime.MinValue;
            int      height    = 0;
            int      width     = 0;

            yield return(Arbiter.Choice(
                             _camPort.QueryFrame(request),
                             delegate(cam.QueryFrameResponse response)
            {
                timestamp = response.TimeStamp;
                frame = response.Frame;
                width = response.Size.Width;
                height = response.Size.Height;
            },
                             delegate(Fault f)
            {
                fault = f;
            }
                             ));

            ImageProcessedRequest processed = new ImageProcessedRequest();

            if (fault != null)
            {
                _mainPort.Post(new ImageProcessed(processed));
                yield break;
            }

            int size = width * height * 3;

            processed.TimeStamp = timestamp;
            List <FoundBlob> results = processed.Results;

            foreach (ColorBin bin in bins)
            {
                FoundBlob blob = new FoundBlob();

                blob.Name        = bin.Name;
                blob.XProjection = new int[width];
                blob.YProjection = new int[height];

                results.Add(blob);
            }

            int offset;

            for (int y = 0; y < height; y++)
            {
                offset = y * width * 3;

                for (int x = 0; x < width; x++, offset += 3)
                {
                    int r, g, b;

                    b = frame[offset];
                    g = frame[offset + 1];
                    r = frame[offset + 2];

                    for (int i = 0; i < bins.Count; i++)
                    {
                        ColorBin bin = bins[i];

                        if (bin.Test(r, g, b))
                        {
                            results[i].AddPixel(x, y);
                        }
                    }
                }
            }

            foreach (FoundBlob blob in results)
            {
                if (blob.Area > 0)
                {
                    blob.MeanX = blob.MeanX / blob.Area;
                    blob.MeanY = blob.MeanY / blob.Area;

                    blob.CalculateMoments();
                }
            }

            _mainPort.Post(new ImageProcessed(processed));
        }
 public MdmFaultException(Fault fault)
 {
     Fault = fault;
 }
Example #52
0
 public void Consume(Fault <Hello, Guid> message)
 {
     _fault.Set(message);
 }
 public void ShouldReturnFalseForOther()
 {
     var fault = new Fault { Message = "Other errors" };
     Assert.IsFalse(fault.IsServiceUnavailable());
 }
 public RPCConnectResult(RPCConnectResultType result, Fault fault)
 {
     Result         = result;
     FlexLoginFault = fault;
 }
 public void ShouldReturnTrueForUnableToConnect()
 {
     var fault = new Fault { Message = "Unable to connect to the remote server CA01230" };
     Assert.IsTrue(fault.IsServiceUnavailable());
 }
Example #56
0
            private IEnumerable <FaultLocationData.FaultSummaryRow> CreateFaultSummaryRows(Fault fault, int faultNumber)
            {
                FaultLocationData.FaultSummaryRow faultSummaryRow;
                double durationSeconds;

                foreach (Fault.Summary summary in fault.Summaries)
                {
                    // Calculate the duration of the fault in seconds
                    durationSeconds = fault.Duration.TotalSeconds;

                    // Create the fault summary record to be written to the database
                    faultSummaryRow                     = FaultSummaryTable.NewFaultSummaryRow();
                    faultSummaryRow.Algorithm           = summary.DistanceAlgorithm;
                    faultSummaryRow.FaultNumber         = faultNumber;
                    faultSummaryRow.CalculationCycle    = fault.CalculationCycle;
                    faultSummaryRow.Distance            = ToDbFloat(summary.Distance);
                    faultSummaryRow.CurrentMagnitude    = ToDbFloat(fault.CurrentMagnitude);
                    faultSummaryRow.CurrentLag          = ToDbFloat(fault.CurrentLag);
                    faultSummaryRow.PrefaultCurrent     = ToDbFloat(fault.PrefaultCurrent);
                    faultSummaryRow.PostfaultCurrent    = ToDbFloat(fault.PostfaultCurrent);
                    faultSummaryRow.Inception           = fault.InceptionTime;
                    faultSummaryRow.DurationSeconds     = durationSeconds;
                    faultSummaryRow.DurationCycles      = durationSeconds * m_systemFrequency;
                    faultSummaryRow.FaultType           = fault.Type.ToString();
                    faultSummaryRow.IsSelectedAlgorithm = summary.IsSelectedAlgorithm ? 1 : 0;
                    faultSummaryRow.IsValid             = summary.IsValid ? 1 : 0;
                    faultSummaryRow.IsSuppressed        = fault.IsSuppressed ? 1 : 0;

                    yield return(faultSummaryRow);
                }
            }
Example #57
0
File: DND.cs Project: mono/stetic
        static void FaultDragMotion(object obj, Gtk.DragMotionArgs args)
        {
            int wx, wy, width, height, depth;

            Gtk.Widget widget = (Gtk.Widget) obj;
            int px = args.X + widget.Allocation.X;
            int py = args.Y + widget.Allocation.Y;

            Fault fault = FindFault (px, py, widget);

            // If there's a splitter visible, and we're not currently dragging
            // in the fault that owns that splitter, hide it
            if (splitter != null && dragFault != fault)
                DestroySplitter ();

            if (dragFault != fault) {
                dragFault = fault;
                if (dragFault == null)
                    return;

                splitter = NewWindow (fault.Owner.Wrapped, Gdk.WindowClass.InputOutput);
                fault.Window.GetGeometry (out wx, out wy, out width, out height, out depth);
                if (fault.Orientation == Gtk.Orientation.Horizontal) {
                    splitter.MoveResize (wx, wy + height / 2 - FaultOverlap,
                                 width, 2 * FaultOverlap);
                } else {
                    splitter.MoveResize (wx + width / 2 - FaultOverlap, wy,
                                 2 * FaultOverlap, height);
                }
                splitter.ShowUnraised ();
                fault.Window.Lower ();
            } else if (dragFault == null)
                return;

            Gdk.Drag.Status (args.Context, Gdk.DragAction.Move, args.Time);
            args.RetVal = true;
        }
Example #58
0
        public IEnumerator <ITask> OnHttpPost(HttpPost httpPost)
        {
            HttpListenerContext context    = httpPost.Body.Context;
            NameValueCollection parameters = null;
            Fault fault = null;

            try
            {
                ReadFormData readForm = new ReadFormData(httpPost);
                _utilitiesPort.Post(readForm);

                yield return(Arbiter.Choice(
                                 readForm.ResultPort,
                                 delegate(NameValueCollection success)
                {
                    parameters = success;
                },
                                 delegate(Exception e)
                {
                    LogError("Error reading form data", e);
                    fault = Fault.FromException(e);
                }
                                 ));

                if (fault != null)
                {
                    yield break;
                }

                string name           = string.Empty;
                string deleteName     = null;
                string expandName     = null;
                int    left           = 0;
                int    top            = 0;
                int    width          = 0;
                int    height         = 0;
                int    deleteY        = 0;
                int    deleteCb       = 0;
                int    deleteCr       = 0;
                double threshold      = 1.0;
                int    minBlobSize    = 0;
                bool   showPartial    = false;
                bool   despeckle      = false;
                bool   updateSettings = false;
                bool   save           = false;

                foreach (string key in parameters.Keys)
                {
                    if (key.StartsWith("Delete."))
                    {
                        string[] segments = key.Split('.');

                        deleteName = segments[1];
                        deleteY    = int.Parse(segments[2]);
                        deleteCb   = int.Parse(segments[3]);
                        deleteCr   = int.Parse(segments[4]);
                    }
                    else if (key.StartsWith("ExpandY."))
                    {
                        string[] segments = key.Split('.');

                        expandName = segments[1];
                        deleteY    = int.Parse(segments[2]);
                        deleteCb   = int.Parse(segments[3]);
                        deleteCr   = int.Parse(segments[4]);
                    }
                    else
                    {
                        switch (key)
                        {
                        case "Save":
                            save = true;
                            break;

                        case "Threshold":
                            threshold = double.Parse(parameters[key]);
                            break;

                        case "ShowPartial":
                            showPartial = parameters[key] == "on";
                            break;

                        case "Despeckle":
                            despeckle = parameters[key] == "on";
                            break;

                        case "UpdateSettings":
                            updateSettings = true;
                            break;

                        case "MinBlobSize":
                            minBlobSize = int.Parse(parameters[key]);
                            break;

                        case "New.Left":
                            left = int.Parse(parameters[key]);
                            break;

                        case "New.Top":
                            top = int.Parse(parameters[key]);
                            break;

                        case "New.Width":
                            width = int.Parse(parameters[key]);
                            break;

                        case "New.Height":
                            height = int.Parse(parameters[key]);
                            break;

                        case "New.Name":
                            name = parameters[key].Trim();
                            break;

                        default:
                            break;
                        }
                    }
                }

                if (save)
                {
                    yield return(Arbiter.Choice(
                                     SaveState(_state.SmallCopy),
                                     EmptyHandler,
                                     EmptyHandler
                                     ));
                }
                else if (!string.IsNullOrEmpty(deleteName))
                {
                    ColorDefinition definition = new ColorDefinition(deleteName, deleteY, deleteCb, deleteCr);

                    RemoveColorDefinition remove = new RemoveColorDefinition(definition);

                    OnRemoveColorDefinition(remove);
                }
                else if (!string.IsNullOrEmpty(expandName))
                {
                    ColorDefinition definition = new ColorDefinition(expandName, deleteY, deleteCb, deleteCr);
                    ColorSet        set        = _state.Colors.Find(definition.Compare);
                    if (set != null)
                    {
                        ColorDefinition existing = set.Colors.Find(definition.CompareColor);

                        definition.SigmaCb = existing.SigmaCb;
                        definition.SigmaCr = existing.SigmaCr;
                        if (existing.SigmaY < 1)
                        {
                            definition.SigmaY = 2;
                        }
                        else
                        {
                            definition.SigmaY = 3 * existing.SigmaY / 2;
                        }
                    }

                    UpdateColorDefinition update = new  UpdateColorDefinition(definition);

                    OnUpdateColorDefinition(update);
                }
                else if (updateSettings)
                {
                    UpdateSettings update = new UpdateSettings(
                        new Settings(
                            threshold,
                            showPartial,
                            despeckle,
                            minBlobSize
                            )
                        );

                    OnUpdateSettings(update);
                }
                else
                {
                    webcam.QueryFrameResponse response = null;

                    yield return(Arbiter.Choice(
                                     _webcamPort.QueryFrame(),
                                     delegate(webcam.QueryFrameResponse success)
                    {
                        response = success;
                    },
                                     delegate(Fault failure)
                    {
                        LogError("Unable to query frame for update", failure);
                    }
                                     ));

                    if (response == null)
                    {
                        yield break;
                    }

                    int    right     = left + width;
                    int    bottom    = top + height;
                    byte[] data      = response.Frame;
                    int    stride    = data.Length / response.Size.Height;
                    int    rowOffset = left * 3;
                    int    offset;

                    int    r, g, b;
                    int[]  yProjection  = new int[256];
                    int[]  cbProjection = new int[256];
                    int[]  crProjection = new int[256];
                    int    count        = 0;
                    double yMean        = 0;
                    double cbMean       = 0;
                    double crMean       = 0;

                    for (int y = top; y < bottom; y++)
                    {
                        offset = rowOffset + y * stride;

                        for (int x = left; x < right; x++)
                        {
                            b = data[offset++];
                            g = data[offset++];
                            r = data[offset++];

                            ColorDefinition pixel = new ColorDefinition(r, g, b, "pixel");

                            yProjection[pixel.Y]++;
                            cbProjection[pixel.Cb]++;
                            crProjection[pixel.Cr]++;

                            count++;

                            yMean  += pixel.Y;
                            cbMean += pixel.Cb;
                            crMean += pixel.Cr;
                        }
                    }

                    if (count <= 16)
                    {
                        LogError("The area was too small to generalize a color");
                        yield break;
                    }

                    yMean  /= count;
                    cbMean /= count;
                    crMean /= count;

                    double ySigma  = CalculateStdDev(yMean, yProjection, count);
                    double cbSigma = CalculateStdDev(cbMean, cbProjection, count);
                    double crSigma = CalculateStdDev(crMean, crProjection, count);

                    ColorDefinition definition = new ColorDefinition(
                        name,
                        (int)Math.Round(yMean),
                        (int)Math.Round(cbMean),
                        (int)Math.Round(crMean)
                        );
                    definition.SigmaY  = (int)Math.Max(1, Math.Round(2 * ySigma));
                    definition.SigmaCb = (int)Math.Max(1, Math.Round(2 * cbSigma));
                    definition.SigmaCr = (int)Math.Max(1, Math.Round(2 * crSigma));

                    if (!string.IsNullOrEmpty(expandName))
                    {
                        definition.Name = expandName;
                        UpdateColorDefinition update = new UpdateColorDefinition(definition);
                        OnUpdateColorDefinition(update);
                    }
                    else
                    {
                        AddColorDefinition add = new AddColorDefinition(definition);

                        OnAddColorDefinition(add);
                    }
                }
            }
            finally
            {
                httpPost.ResponsePort.Post(new HttpResponseType(HttpStatusCode.OK, _state.SmallCopy, _transform));
            }
        }
Example #59
0
File: DND.cs Project: mono/stetic
        public static void AddFault(Stetic.Wrapper.Widget owner, object faultId,
					     Gtk.Orientation orientation,
					     int x, int y, int width, int height)
        {
            Gtk.Widget widget = owner.Wrapped;
            if (!widget.IsRealized)
                return;

            Gdk.Window win = NewWindow (widget, Gdk.WindowClass.InputOnly);
            win.MoveResize (x, y, width, height);

            Hashtable widgetFaults = faultGroups[widget] as Hashtable;
            if (widgetFaults == null) {
                faultGroups[widget] = widgetFaults = new Hashtable ();
                widget.Destroyed += FaultWidgetDestroyed;
                widget.DragMotion += FaultDragMotion;
                widget.DragLeave += FaultDragLeave;
                widget.DragDrop += FaultDragDrop;
                widget.DragDataReceived += FaultDragDataReceived;
                DND.DestSet (widget, false);
            }
            widgetFaults[win] = new Fault (owner, faultId, orientation, win);
        }
Example #60
0
 public FaultReceivedException(Fault fault) : base(Strings.FromFault(fault))
 {
     Fault = fault;
     //Console.WriteLine("***" + this.ToString());
 }