Exemplo n.º 1
0
        protected AbstractSocketChannel(IChannel parent, Socket socket)
            : base(parent)
        {
            Socket = socket;
            _state = StateFlags.Open;

            try
            {
                Socket.Blocking = false;
            }
            catch (SocketException ex)
            {
                try
                {
                    socket.Close();
                }
                catch (SocketException ex2)
                {
                    if (Logger.IsWarningEnabled)
                    {
                        Logger.Warning("Failed to close a partially initialized socket.", ex2);
                    }
                }

                throw new ChannelException("Failed to enter non-blocking mode.", ex);
            }
        }
Exemplo n.º 2
0
        public override void Render(CellContext context, StateFlags state, double cellWidth, double cellHeight)
        {
            if (BoundObject == null) {
                return;
            }

            if (!(BoundObject is TrackInfo)) {
                throw new InvalidCastException ("ColumnCellAlbum can only bind to AlbumInfo objects");
            }

            TrackInfo track = (TrackInfo)BoundObject;

            context.Layout.Width = (int)((cellWidth - 8) * Pango.Scale.PangoScale);
            context.Layout.Ellipsize = Pango.EllipsizeMode.End;
            context.Layout.FontDescription.Weight = font_weight;
            context.Layout.SetMarkup (String.Format ("<b>{0}</b>\n<small><i>{1}</i></small>",
                GLib.Markup.EscapeText (track.DisplayTrackTitle),
                GLib.Markup.EscapeText (track.DisplayArtistName)));

            int text_width;
            int text_height;
            context.Layout.GetPixelSize (out text_width, out text_height);

            context.Context.MoveTo (4, ((int)cellHeight - text_height) / 2);
            context.Widget.StyleContext.Save ();
            context.Widget.StyleContext.AddClass ("entry");
            Cairo.Color color = CairoExtensions.GdkRGBAToCairoColor (context.Widget.StyleContext.GetColor (StateFlags.Selected));
            context.Widget.StyleContext.Restore ();
            color.A = (!context.Opaque) ? 0.3 : 1.0;
            context.Context.SetSourceColor (color);

            PangoCairoHelper.ShowLayout (context.Context, context.Layout);
        }
        public override void Render(CellContext context, StateFlags state, double cellWidth, double cellHeight)
        {
            PodcastTrackInfo podcast = PodcastTrackInfo.From (BoundTrack);
            if (podcast != null) {
                if (podcast.Activity == PodcastItemActivity.DownloadPending) {
                    context.Opaque = false;
                }
            }

            base.Render (context, state, cellWidth, cellHeight);
        }
 internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack)
 {
     if (forceCaptureContext)
     {
         this._Flags = StateFlags.CaptureContext;
     }
     if (captureIdentity)
     {
         this._Flags |= StateFlags.CaptureIdentity;
     }
     if (threadSafeContextCopy)
     {
         this._Flags |= StateFlags.ThreadSafeContextCopy;
     }
 }
Exemplo n.º 5
0
        public override bool Deserialize()
        {
            var result = base.Deserialize();

            _unknown = Data.ReadInt32(); // Not always zero, looks like flags or mask?

            ProbeMask = Data.ReadInt32();
            IgnoreMask = Data.ReadInt64();

            LabelTableOffset = Data.ReadInt16();

            // This can't be processed here unless the bytecode is also processed for virtual address space
            /*if (LabelTableOffset >= 0)
            {
                LabelTable = new List<LabelTableEntry>();
                var tableReader = new ObjectReader(ByteScript);
                tableReader.ReadRawData(LabelTableOffset);

                var NameRef = tableReader.ReadNameRef();
                var Offset = tableReader.ReadUInt32();
                while (Offset != 0x0000FFFF)
                {
                    var entry = new LabelTableEntry();
                    entry.NameRef = NameRef;
                    entry.Name = PCC.GetName(NameRef);
                    entry.Offset = Offset;
                    LabelTable.Add(entry);

                    NameRef = tableReader.ReadNameRef();
                    Offset = tableReader.ReadUInt32();
                }
            }*/

            StateFlags = (StateFlags)Data.ReadInt32();

            FunctionMapCount = Data.ReadInt32();
            for (int i = 0; i < FunctionMapCount; i++)
            {
                var funcEntry = new FunctionMapEntry();
                funcEntry.NameRef.Index = Data.ReadInt32();
                funcEntry.NameRef.ModNumber = Data.ReadInt32();
                funcEntry.FunctionObjectIndex = Data.ReadInt32();
                _FunctionMap.Add(funcEntry);
            }

            return result;
        }
Exemplo n.º 6
0
 public IS_CPP(byte[] data) {
     Size = data[0];
     Type = (PacketType)data[1];
     ReqI = data[2];
     Zero = data[3];
     Pos1 = BitConverter.ToInt32(data, 4);
     Pos2 = BitConverter.ToInt32(data, 8);
     Pos3 = BitConverter.ToInt32(data, 12);
     H = BitConverter.ToUInt16(data, 16);
     P = BitConverter.ToUInt16(data, 18);
     R = BitConverter.ToUInt16(data, 20);
     ViewPLID = data[22];
     InGameCam = (CameraViews)data[23];
     FOV = BitConverter.ToSingle(data, 24);
     Time = BitConverter.ToUInt16(data, 28);
     Flags = (StateFlags)BitConverter.ToUInt16(data, 30);
 }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a RegistryKey.
        /// This key is bound to hkey, if writable is <b>false</b> then no write operations
        /// will be allowed. If systemkey is set then the hkey won't be released
        /// when the object is GC'ed.
        /// The remoteKey flag when set to true indicates that we are dealing with registry entries
        /// on a remote machine and requires the program making these calls to have full trust.
        /// </summary>
        private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view)
        {
            ValidateKeyView(view);

            _hkey = hkey;
            _keyName = "";
            _remoteKey = remoteKey;
            _regView = view;

            if (systemkey)
            {
                _state |= StateFlags.SystemKey;
            }
            if (writable)
            {
                _state |= StateFlags.WriteAccess;
            }
            if (isPerfData)
            {
                _state |= StateFlags.PerfData;
            }
        }
Exemplo n.º 8
0
        public override void SetState(StateFlags AState, bool Enable)
        {
            base.SetState(AState, Enable);
            switch (AState)
            {
            case StateFlags.Active:
            case StateFlags.Dragging:
                Lock();
                ForEach(new ForEachProc(DoSetState), AState, Enable);
                Unlock();
                break;

            case StateFlags.Focused:
                if (Current != null)
                {
                    Current.SetState(StateFlags.Focused, Enable);
                }
                break;

            case StateFlags.Exposed:
                ForEach(new ForEachProc(DoExpose), Enable);
                break;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Closes channel
        /// </summary>
        async void Shutdown(IChannelHandlerContext context, Exception cause)
        {
            if (this.IsInState(StateFlags.Closed))
            {
                return;
            }

            try
            {
                this.stateFlags |= StateFlags.Closed; // "or" not to interfere with ongoing logic which has to honor Closed state when it's right time to do (case by case)

                // only decrement connection current counter if the state had connected state in this session
                if (this.IsInState(StateFlags.Connected))
                {
                    //PerformanceCounters.ConnectionsCurrent.Decrement();
                }

                Queue <Packet> connectQueue = this.connectPendingQueue;
                if (connectQueue != null)
                {
                    while (connectQueue.Count > 0)
                    {
                        Packet packet = connectQueue.Dequeue();
                        ReferenceCountUtil.Release(packet);
                    }
                }

                //await this.CloseServiceConnection(context, cause, will);
                await context.CloseAsync();
            }
            catch (Exception ex)
            {
                //LOG
                Console.WriteLine("Error occurred while shutting down the channel.", ex, this.ChannelId);
            }
        }
Exemplo n.º 10
0
        void ProcessConnectAck(IChannelHandlerContext context, ConnAckPacket packet)
        {
            if (packet.ReturnCode != ConnectReturnCode.Accepted)
            {
                string reason          = "CONNECT failed: " + packet.ReturnCode;
                var    iotHubException = new IotHubException(reason);
                ShutdownOnError(context, iotHubException);
                return;
            }

            if (!this.IsInState(StateFlags.Connecting))
            {
                string reason          = "CONNECT has been received, however a session has already been established. Only one CONNECT/CONNACK pair is expected per session.";
                var    iotHubException = new IotHubException(reason);
                ShutdownOnError(context, iotHubException);
                return;
            }

            this.stateFlags = StateFlags.Connected;

            this.ResumeReadingIfNecessary(context);

            this.onConnected();
        }
Exemplo n.º 11
0
        private void PlayBgm()
        {
            if (m_Implements.Sounder == null)
            {
                return;
            }

            string bgm = string.Empty;

            m_LayerController.ForEachAnything(layer =>
            {
                if (!StateFlags.IsVisible(layer.State))
                {
                    return;
                }

                if (!string.IsNullOrEmpty(bgm))
                {
                    return;
                }

                if (!string.IsNullOrEmpty(layer.Base.Bgm))
                {
                    bgm = layer.Base.Bgm;
                }
            });

            if (string.IsNullOrEmpty(bgm))
            {
                m_Implements.Sounder.StopBGM();
            }
            else
            {
                m_Implements.Sounder.PlayBGM(bgm);
            }
        }
Exemplo n.º 12
0
        protected FABSocketChannel(IFABChannel parent, Socket socket)
            : base(parent)
        {
            this.Socket = socket;
            this.state  = StateFlags.Open;

            try
            {
                this.Socket.Blocking = false;
            }
            catch (SocketException ex)
            {
                try
                {
                    socket.Dispose();
                }
                catch (SocketException ex2)
                {
                    throw ex2;
                }

                throw new FABChannelException("Failed to enter non-blocking mode.", ex);
            }
        }
Exemplo n.º 13
0
 protected bool IsInState(StateFlags stateToCheck)
 {
     return((this.state & stateToCheck) == stateToCheck);
 }
 internal object StartPostingAsyncOp(bool lockCapture)
 {
     this._Lock = lockCapture ? new object() : null;
     this._Flags |= StateFlags.PostBlockStarted;
     return this._Lock;
 }
 internal bool FinishPostingAsyncOp()
 {
     if ((this._Flags & (StateFlags.PostBlockFinished | StateFlags.PostBlockStarted)) != StateFlags.PostBlockStarted)
     {
         return false;
     }
     this._Flags |= StateFlags.PostBlockFinished;
     ExecutionContext cachedContext = null;
     return this.CaptureOrComplete(ref cachedContext, false);
 }
        /// <summary>
        ///     Performs complete initialization of <see cref="MqttAdapter" /> based on received CONNECT packet.
        /// </summary>
        /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param>
        /// <param name="packet">CONNECT packet.</param>
        async void Connect(IChannelHandlerContext context, ConnectPacket packet)
        {
            bool connAckSent = false;

            Exception exception = null;

            try
            {
                if (!this.IsInState(StateFlags.WaitingForConnect))
                {
                    ShutdownOnError(context, ConnectProcessingScope, new ProtocolGatewayException(ErrorCode.DuplicateConnectReceived, "CONNECT has been received in current session already. Only one CONNECT is expected per session."));
                    return;
                }

                this.stateFlags = StateFlags.ProcessingConnect;
                this.identity   = await this.authProvider.GetAsync(packet.ClientId,
                                                                   packet.Username, packet.Password, context.Channel.RemoteAddress);

                if (!this.identity.IsAuthenticated)
                {
                    CommonEventSource.Log.Info("ClientNotAuthenticated", this.ChannelId, $"Client ID: {packet.ClientId}; Username: {packet.Username}");
                    connAckSent = true;
                    await Util.WriteMessageAsync(context, new ConnAckPacket
                    {
                        ReturnCode = ConnectReturnCode.RefusedNotAuthorized
                    });

                    PerformanceCounters.ConnectionFailedAuthPerSecond.Increment();
                    ShutdownOnError(context, ConnectProcessingScope, new ProtocolGatewayException(ErrorCode.AuthenticationFailed, "Authentication failed."));
                    return;
                }

                CommonEventSource.Log.Info("ClientAuthenticated", this.ChannelId, this.Id);

                this.messagingBridge = await this.messagingBridgeFactory(this.identity, this.lifetimeCancellation.Token);

                bool sessionPresent = await this.EstablishSessionStateAsync(packet.CleanSession);

                this.keepAliveTimeout = this.DeriveKeepAliveTimeout(context, packet);

                if (packet.HasWill)
                {
                    var will = new PublishPacket(packet.WillQualityOfService, false, packet.WillRetain);
                    will.TopicName  = packet.WillTopicName;
                    will.Payload    = packet.WillMessage;
                    this.willPacket = will;
                }

                connAckSent = true;
                await Util.WriteMessageAsync(context, new ConnAckPacket
                {
                    SessionPresent = sessionPresent,
                    ReturnCode     = ConnectReturnCode.Accepted
                });

                this.CompleteConnect(context);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                if (!connAckSent)
                {
                    try
                    {
                        await Util.WriteMessageAsync(context, new ConnAckPacket
                        {
                            ReturnCode = ConnectReturnCode.RefusedServerUnavailable
                        });
                    }
                    catch (Exception ex)
                    {
                        if (CommonEventSource.Log.IsVerboseEnabled)
                        {
                            CommonEventSource.Log.Verbose("Error sending 'Server Unavailable' CONNACK:" + ex, this.ChannelId, this.Id);
                        }
                    }
                }

                ShutdownOnError(context, ConnectProcessingScope, exception);
            }
        }
Exemplo n.º 17
0
 void ResetState(StateFlags stateFlagsToReset)
 {
     this.stateFlags &= ~stateFlagsToReset;
 }
Exemplo n.º 18
0
 internal static bool IsInitial(this StateFlags info) => (info & StateFlags.IsInitialFlag) != 0;
Exemplo n.º 19
0
        public override void Render(CellContext context, StateFlags state, double cellWidth, double cellHeight)
        {
            context.Context.Translate (0, 0.5);
            int draw_x = 0;

            foreach (int i in AttributesForBoundObject) {
                Gdk.Pixbuf render_pixbuf = pixbufs[i];

                if (render_pixbuf != null) {
                    Cairo.Rectangle pixbuf_area = new Cairo.Rectangle (draw_x,
                        (cellHeight - render_pixbuf.Height) / 2, render_pixbuf.Width, render_pixbuf.Height);

                    if (!context.Opaque) {
                        context.Context.Save ();
                    }

                    Gdk.CairoHelper.SetSourcePixbuf (context.Context, render_pixbuf, pixbuf_area.X, pixbuf_area.Y);
                    context.Context.Rectangle (pixbuf_area);

                    if (!context.Opaque) {
                        context.Context.Clip ();
                        context.Context.PaintWithAlpha (0.5);
                        context.Context.Restore ();
                    } else {
                        context.Context.Fill ();
                    }
                }

                draw_x += ICON_SIZE;
            }
        }
Exemplo n.º 20
0
 internal static bool SimulatesBacktracking(this StateFlags info) => (info & StateFlags.SimulatesBacktrackingFlag) != 0;
Exemplo n.º 21
0
        protected override void OnRender(Cairo.Context cr, Widget widget, Gdk.Rectangle background_area,
                                         Gdk.Rectangle cell_area, CellRendererState flags)
        {
            if (source == null || source is SourceManager.GroupSource)
            {
                return;
            }

            view = widget as SourceView;
            bool       selected = view != null && view.Selection.IterIsSelected(iter);
            StateFlags state    = RendererStateToWidgetState(widget, flags);

            RenderBackground(cr, background_area, selected, state);

            int title_layout_width = 0, title_layout_height = 0;
            int count_layout_width = 0, count_layout_height = 0;
            int max_title_layout_width;

            int  img_padding           = 6;
            int  expander_icon_spacing = 3;
            int  x      = cell_area.X;
            bool np_etc = (source.Order + Depth * 100) < 40;

            if (!np_etc)
            {
                x += Depth * img_padding + (int)Xpad;
            }
            else
            {
                // Don't indent NowPlaying and Play Queue as much
                x += Math.Max(0, (int)Xpad - 2);
            }

            // Draw the expander if the source has children
            double exp_h = (cell_area.Height - 2.0 * Ypad) / 2.0;
            double exp_w = exp_h * 1.6;
            int    y     = Middle(cell_area, (int)exp_h);

            if (view != null && source.Children != null && source.Children.Count > 0)
            {
                var r = new Gdk.Rectangle(x, y, (int)exp_w, (int)exp_h);
                view.Theme.DrawArrow(cr, r, source.Expanded ? Math.PI / 2.0 : 0.0);
            }

            if (!np_etc)
            {
                x += (int)exp_w;
                x += 2; // a little spacing after the expander
                expander_right_x = x;
            }

            // Draw icon
            Pixbuf icon = SourceIconResolver.ResolveIcon(source, RowHeight);

            bool dispose_icon = false;

            if (state == StateFlags.Insensitive)
            {
                // Code ported from gtk_cell_renderer_pixbuf_render()
                var icon_source = new IconSource()
                {
                    Pixbuf         = icon,
                    Size           = IconSize.SmallToolbar,
                    SizeWildcarded = false
                };

                icon = widget.StyleContext.RenderIconPixbuf(icon_source, (IconSize)(-1));

                dispose_icon = true;
                icon_source.Dispose();
            }

            if (icon != null)
            {
                x += expander_icon_spacing;

                cr.Save();
                Gdk.CairoHelper.SetSourcePixbuf(cr, icon, x, Middle(cell_area, icon.Height));
                cr.Paint();
                cr.Restore();

                x += icon.Width;

                if (dispose_icon)
                {
                    icon.Dispose();
                }
            }

            // Setup font info for the title/count, and see if we should show the count
            bool            hide_count = source.EnabledCount <= 0 || source.Properties.Get <bool> ("SourceView.HideCount");
            FontDescription fd         = widget.PangoContext.FontDescription.Copy();

            fd.Weight = (ISource)ServiceManager.PlaybackController.NextSource == (ISource)source
                ? Pango.Weight.Bold
                : Pango.Weight.Normal;

            if (view != null && source == view.NewPlaylistSource)
            {
                fd.Style   = Pango.Style.Italic;
                hide_count = true;
            }

            Pango.Layout title_layout = new Pango.Layout(widget.PangoContext);
            Pango.Layout count_layout = null;

            // If we have a count to draw, setup its fonts and see how wide it is to see if we have room
            if (!hide_count)
            {
                count_layout = new Pango.Layout(widget.PangoContext);
                count_layout.FontDescription = fd;
                count_layout.SetMarkup(String.Format("<span size=\"small\">{0}</span>", source.EnabledCount));
                count_layout.GetPixelSize(out count_layout_width, out count_layout_height);
            }

            // Hide the count if the title has no space
            max_title_layout_width = cell_area.Width - x - count_layout_width;//(icon == null ? 0 : icon.Width) - count_layout_width - 10;
            if (!hide_count && max_title_layout_width <= 0)
            {
                hide_count = true;
            }

            // Draw the source Name
            title_layout.FontDescription = fd;
            title_layout.Width           = (int)(max_title_layout_width * Pango.Scale.PangoScale);
            title_layout.Ellipsize       = EllipsizeMode.End;
            title_layout.SetText(source.Name);
            title_layout.GetPixelSize(out title_layout_width, out title_layout_height);

            x += img_padding;
            widget.StyleContext.RenderLayout(cr, x, Middle(cell_area, title_layout_height), title_layout);

            title_layout.Dispose();

            // Draw the count
            if (!hide_count)
            {
                if (view != null)
                {
                    cr.SetSourceColor(state == StateFlags.Normal || (view != null && state == StateFlags.Prelight)
                        ? view.Theme.TextMidColor
                        : CairoExtensions.GdkRGBAToCairoColor(view.Theme.Widget.StyleContext.GetColor(state)));

                    cr.MoveTo(
                        cell_area.X + cell_area.Width - count_layout_width - 2,
                        cell_area.Y + 0.5 + (double)(cell_area.Height - count_layout_height) / 2.0);
                    Pango.CairoHelper.ShowLayout(cr, count_layout);
                }

                count_layout.Dispose();
            }

            fd.Dispose();
        }
Exemplo n.º 22
0
 internal static bool CanBeNullable(this StateFlags info) => (info & StateFlags.CanBeNullableFlag) != 0;
Exemplo n.º 23
0
 internal static bool IsNullable(this StateFlags info) => (info & StateFlags.IsNullableFlag) != 0;
Exemplo n.º 24
0
 internal static bool IsDeadend(this StateFlags info) => (info & StateFlags.IsDeadendFlag) != 0;
Exemplo n.º 25
0
		protected MemberSpec (MemberKind kind, TypeSpec declaringType, IMemberDefinition definition, Modifiers modifiers)
		{
			this.Kind = kind;
			this.declaringType = declaringType;
			this.definition = definition;
			this.modifiers = modifiers;

			state = StateFlags.Obsolete_Undetected | StateFlags.CLSCompliant_Undetected | StateFlags.MissingDependency_Undetected;
		}
Exemplo n.º 26
0
		//
		// Returns member CLS compliance based on full member hierarchy
		//
		public bool IsCLSCompliant ()
		{
			if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
				state &= ~StateFlags.CLSCompliant_Undetected;

				if (IsNotCLSCompliant ())
					return false;

				bool compliant;
				if (DeclaringType != null) {
					compliant = DeclaringType.IsCLSCompliant ();
				} else {
					// TODO: NEED AssemblySpec
					if (MemberDefinition.IsImported) {
						var attr = MemberDefinition.Assembly.GetCustomAttributes (typeof (CLSCompliantAttribute), false);
						compliant = attr.Length > 0 && ((CLSCompliantAttribute) attr[0]).IsCompliant;
					} else {
						compliant = CodeGen.Assembly.IsClsCompliant;
					}
				}

				if (compliant)
					state |= StateFlags.CLSCompliant;
			}

			return (state & StateFlags.CLSCompliant) != 0;
		}
 protected bool IsInState(StateFlags stateToCheck) => (this.state & stateToCheck) == stateToCheck;
Exemplo n.º 28
0
 public void SetState(StateFlags flags)
 {
     SetProgressState(Hwnd, flags);
 }
Exemplo n.º 29
0
        async void Connect(IChannelHandlerContext context)
        {

            var connectPacket = new ConnectPacket
            {
                ClientId = this.deviceId,
                HasUsername = true,
                Username = this.iotHubHostName + "/" + this.deviceId,
                HasPassword = true,
                Password = this.password,
                KeepAliveInSeconds = this.mqttTransportSettings.KeepAliveInSeconds,
                CleanSession = this.mqttTransportSettings.CleanSession,
                HasWill = this.mqttTransportSettings.HasWill
            };
            if (connectPacket.HasWill)
            {
                Message message = this.willMessage.Message;
                QualityOfService publishToServerQoS = this.mqttTransportSettings.PublishToServerQoS;
                string topicName = string.Format(TelemetryTopicFormat, this.deviceId);
                PublishPacket will = await Util.ComposePublishPacketAsync(context, message, publishToServerQoS, topicName);

                connectPacket.WillMessage = will.Payload;
                connectPacket.WillQualityOfService = this.willMessage.QoS;
                connectPacket.WillRetain = false;
                connectPacket.WillTopicName = will.TopicName;
            }
            this.stateFlags = StateFlags.Connecting;

            await Util.WriteMessageAsync(context, connectPacket, ShutdownOnWriteErrorHandler);
            this.lastChannelActivityTime = DateTime.UtcNow;
            this.ScheduleKeepConnectionAlive(context);

            this.ScheduleCheckConnectTimeout(context);
        }
Exemplo n.º 30
0
 public override void ChannelActive(IChannelHandlerContext context)
 {
     this.capturedContext = context;
     this.stateFlags      = StateFlags.NotConnected;
     base.ChannelActive(context);
 }
Exemplo n.º 31
0
        protected override void DoBeginRead()
        {
            if (_inputShutdown)
            {
                return;
            }

            if (!IsOpen)
            {
                return;
            }

            _readPending = true;

            if (!IsInState(StateFlags.ReadScheduled))
            {
                _state |= StateFlags.ReadScheduled;
                ScheduleSocketRead();
            }
        }
Exemplo n.º 32
0
        void ProcessConnectAck(IChannelHandlerContext context, ConnAckPacket packet)
        {
            if (packet.ReturnCode != ConnectReturnCode.Accepted)
            {
                string reason = "CONNECT failed: " + packet.ReturnCode;
                var iotHubException = new IotHubException(reason);
                ShutdownOnError(context, iotHubException);
                return;
            }

            if (!this.IsInState(StateFlags.Connecting))
            {
                string reason = "CONNECT has been received, however a session has already been established. Only one CONNECT/CONNACK pair is expected per session.";
                var iotHubException = new IotHubException(reason);
                ShutdownOnError(context, iotHubException);
                return;
            }

            this.stateFlags = StateFlags.Connected;

            this.ResumeReadingIfNecessary(context);

            this.onConnected();
        }
 void ProcessSubAck()
 {
     this.stateFlags &= ~StateFlags.Subscribing;
     this.stateFlags |= StateFlags.Receiving;
     this.subscribeCompletion.TryComplete();
 }
Exemplo n.º 34
0
        async Task SubscribeAsync(IChannelHandlerContext context)
        {
            if (this.IsInState(StateFlags.Receiving) || this.IsInState(StateFlags.Subscribing))
            {
                return;
            }

            this.stateFlags |= StateFlags.Subscribing;

            this.subscribeCompletion = new TaskCompletionSource();

            string topicFilter = CommandTopicFilterFormat.FormatInvariant(this.deviceId);

            var subscribePacket = new SubscribePacket(Util.GetNextPacketId(), new SubscriptionRequest(topicFilter, this.mqttTransportSettings.ReceivingQoS));

            await Util.WriteMessageAsync(context, subscribePacket, ShutdownOnWriteErrorHandler);

            await this.subscribeCompletion.Task;
        }
Exemplo n.º 35
0
 private static extern uint SetProgressState(IntPtr hwnd, StateFlags flags);
Exemplo n.º 36
0
 void ProcessSubAck()
 {
     this.stateFlags &= ~StateFlags.Subscribing;
     this.stateFlags |= StateFlags.Receiving;
     this.subscribeCompletion.TryComplete();
 }
Exemplo n.º 37
0
 void StartReceiving(IChannelHandlerContext context)
 {
     this.stateFlags |= StateFlags.Receiving;
     this.Receive(context);
 }
Exemplo n.º 38
0
        async void Shutdown(IChannelHandlerContext context)
        {
            if (this.IsInState(StateFlags.Closed))
            {
                return;
            }

            try
            {
                this.stateFlags |= StateFlags.Closed; // "or" not to interfere with ongoing logic which has to honor Closed state when it's right time to do (case by case)

                this.CloseIotHubConnection();
                await context.CloseAsync();
            }
            catch
            {
                // ignored
            }
        }
 bool IsInState(StateFlags stateFlagsToCheck) => (this.stateFlags & stateFlagsToCheck) == stateFlagsToCheck;
 // TODO: directly use HasFlag
 bool IsInState(StateFlags stateFlagsToCheck)
 {
     return((this.stateFlags & stateFlagsToCheck) == stateFlagsToCheck);
 }
Exemplo n.º 41
0
        public void IntroOutroTest(StateFlags flags)
        {
            Task.From.Attachments = new List <Attachment>();
            string introArg = null;

            if (flags.HasFlag(StateFlags.Intro))
            {
                introArg = "D:\\temp\\intro.wav";
                Task.From.Attachments.Add(new Attachment
                {
                    Type      = AttachmentType.Intro,
                    Path      = introArg,
                    Arguments = new Dictionary <string, string>()
                    {
                        { "Duration", "10000" }
                    }
                });
                Task.To.Flags |= StateFlags.Intro;
            }
            string outroArg = null;

            if (flags.HasFlag(StateFlags.Outro))
            {
                outroArg = "D:\\temp\\outro.wav";
                Task.From.Attachments.Add(new Attachment
                {
                    Type      = AttachmentType.Outro,
                    Path      = outroArg,
                    Arguments = new Dictionary <string, string>()
                    {
                        { "Duration", "10000" }
                    }
                });
                Task.To.Flags |= StateFlags.Outro;
            }
            Assert.That(sut.CheckAndEstimate(Task));

            mockFFMPegService = new Mock <IFFMpegService>(MockBehavior.Strict);
            var jobGuid = Guid.NewGuid();

            mockFFMPegService.Setup(m => m.PostAudioJob(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ObservableCollection <AudioDestinationFormat> >(), introArg, outroArg))
            .Returns(jobGuid);

            FfmpegJobModel job = new FfmpegJobModel()
            {
                State = FfmpegJobModelState.Done,
                Tasks = new ObservableCollection <FfmpegTaskModel>()
                {
                    new FfmpegTaskModel()
                    {
                        DestinationFilename = "\\\\sdfsdfsdf\\sdfgsdf\\1_64.mp3"
                    },
                    new FfmpegTaskModel()
                    {
                        DestinationFilename = "\\\\sdfsdfsdf\\sdfgsdf\\1_192.mp3"
                    },
                    new FfmpegTaskModel()
                    {
                        DestinationFilename = "\\\\sdfsdfsdf\\sdfgsdf\\1_64.mp4"
                    }
                }
            };

            mockFFMPegService.Setup(m => m.GetAudioJob(jobGuid)).Returns(job);

            sut          = new FFMpeg.FFMpeg(_pluginUrn, MockTimeProvider.Object, Logging, mockFFMPegService.Object, mockPresetProvider.Object);
            Task.To.Path = "\\\\sdfsdfsdf\\sdfgsdf";

            sut.Assign(Task);
            sut.Pulse(Task);
            Assert.That(Task.To.Files, Is.Not.Empty);
        }
Exemplo n.º 42
0
 public bool HasStateFlag(StateFlags flag)
 {
     return((_StateFlags & (uint)flag) != 0);
 }
 internal bool FinishPostingAsyncOp(ref CallbackClosure closure)
 {
     ExecutionContext context;
     if ((this._Flags & (StateFlags.PostBlockFinished | StateFlags.PostBlockStarted)) != StateFlags.PostBlockStarted)
     {
         return false;
     }
     this._Flags |= StateFlags.PostBlockFinished;
     CallbackClosure closure2 = closure;
     if (closure2 == null)
     {
         context = null;
     }
     else if (!closure2.IsCompatible(base.AsyncCallback))
     {
         closure = null;
         context = null;
     }
     else
     {
         base.AsyncCallback = closure2.AsyncCallback;
         context = closure2.Context;
     }
     bool flag = this.CaptureOrComplete(ref context, true);
     if (((closure == null) && (base.AsyncCallback != null)) && (context != null))
     {
         closure = new CallbackClosure(context, base.AsyncCallback);
     }
     return flag;
 }
Exemplo n.º 44
0
		//
		// Returns a list of missing dependencies of this member. The list
		// will contain types only but it can have numerous values for members
		// like methods where both return type and all parameters are checked
		//
		public List<TypeSpec> GetMissingDependencies ()
		{
			if ((state & (StateFlags.MissingDependency | StateFlags.MissingDependency_Undetected)) == 0)
				return null;

			state &= ~StateFlags.MissingDependency_Undetected;

			var imported = definition as ImportedDefinition;
			List<TypeSpec> missing;
			if (imported != null) {
				missing = ResolveMissingDependencies ();
			} else if (this is ElementTypeSpec) {
				missing = ((ElementTypeSpec) this).Element.GetMissingDependencies ();
			} else {
				missing = null;
			}

			if (missing != null) {
				state |= StateFlags.MissingDependency;
			}

			return missing;
		}
Exemplo n.º 45
0
 bool IsInState(StateFlags stateFlagsToCheck)
 {
     return (this.stateFlags & stateFlagsToCheck) == stateFlagsToCheck;
 }
Exemplo n.º 46
0
 public bool CheckAndEstimateReturnsFalseIfFromAndToFlagsAreDifferentAndNotLogo(StateFlags from, StateFlags to)
 {
     Task.From.Flags = from;
     Task.To.Flags   = to;
     return(sut.CheckAndEstimate(Task));
 }
Exemplo n.º 47
0
 private void SetDirty() => _state |= StateFlags.Dirty;
Exemplo n.º 48
0
        public override void ChannelActive(IChannelHandlerContext context)
        {
            this.stateFlags = StateFlags.NotConnected;

            this.Connect(context);

            base.ChannelActive(context);
        }
Exemplo n.º 49
0
		public virtual ObsoleteAttribute GetAttributeObsolete ()
		{
			if ((state & (StateFlags.Obsolete | StateFlags.Obsolete_Undetected)) == 0)
				return null;

			state &= ~StateFlags.Obsolete_Undetected;

			var oa = definition.GetAttributeObsolete ();
			if (oa != null)
				state |= StateFlags.Obsolete;

			return oa;
		}
Exemplo n.º 50
0
        private void ParseToken(StringBuilder buffer, StateFlags state, StateFlags?nextState, StringBuilder executionSql)
        {
            var token = buffer.ToString().Replace("\r", "");

            if (state.HasFlag(StateFlags.Comment))
            {
                if (!state.HasFlag(StateFlags.Multiline))
                {
                    var match = _descriptionRegex.Match(token);

                    if (match.Success)
                    {
                        var name      = match.Groups["name"].Value;
                        var parameter = Parameters.ContainsKey(name) ? Parameters[name] : new QueryParameter();

                        parameter.Label = match.Groups["label"].Value;

                        if (match.Groups["description"].Success)
                        {
                            parameter.Description = match.Groups["description"].Value;
                        }

                        Parameters[name] = parameter;
                    }

                    executionSql.Append('\n');
                }

                _sql.Append(token);
            }
            else
            {
                _sql.Append(token);

                if (!state.HasFlag(StateFlags.String))
                {
                    token = _whitespaceRegex.Replace(token, "${whitespace}");
                    token = _boundarySpacesRegex.Replace(token, "");

                    if (nextState.HasValue && nextState.Value.HasFlag(StateFlags.Comment) && !nextState.Value.HasFlag(StateFlags.Multiline))
                    {
                        token = token.TrimEnd(' ');
                    }
                }

                var matches = _paramsRegex.Matches(token);

                foreach (Match match in matches)
                {
                    var name      = match.Groups["name"].Value;
                    var parameter = Parameters.ContainsKey(name) ? Parameters[name] : new QueryParameter();

                    if (match.Groups["type"].Success)
                    {
                        var type = match.Groups["type"].Value.ToLower();

                        if (CheckIfTypeIsKnown(type))
                        {
                            parameter.Type = type;
                        }
                        else
                        {
                            Errors.Add($"{name} has unknown parameter type {type}!");
                        }
                    }

                    if (match.Groups["default"].Success)
                    {
                        var value = match.Groups["default"].Value;

                        if (!parameter.Type.HasValue() || ValidateType(parameter.Type, value))
                        {
                            parameter.Default = value;
                        }
                        else
                        {
                            Errors.Add($"{name}'s default value of {value} is invalid for the type {parameter.Type}!");
                        }
                    }

                    parameter.Required = parameter.Default == null;

                    Parameters[name] = parameter;
                    token            = token.ReplaceFirst(match.Value, "##" + name + "##");
                }

                if (executionSql.Length > 0 && executionSql[executionSql.Length - 1] == '\n')
                {
                    token = token.TrimStart('\n', ' ');
                }

                executionSql.Append(token);
            }
        }
Exemplo n.º 51
0
		//
		// Returns member CLS compliance based on full member hierarchy
		//
		public bool IsCLSCompliant ()
		{
			if ((state & StateFlags.CLSCompliant_Undetected) != 0) {
				state &= ~StateFlags.CLSCompliant_Undetected;

				bool compliant;
				if (IsNotCLSCompliant (out compliant))
					return false;

				if (!compliant) {
					if (DeclaringType != null) {
						compliant = DeclaringType.IsCLSCompliant ();
					} else {
						compliant = ((ITypeDefinition) MemberDefinition).DeclaringAssembly.IsCLSCompliant;
					}
				}

				if (compliant)
					state |= StateFlags.CLSCompliant;
			}

			return (state & StateFlags.CLSCompliant) != 0;
		}
Exemplo n.º 52
0
        async void Connect(IChannelHandlerContext context)
        {
            if (Logging.IsEnabled)
            {
                Logging.Enter(this, context.Name, nameof(Connect));
            }

            try
            {
                string id       = string.IsNullOrWhiteSpace(this.moduleId) ? this.deviceId : $"{this.deviceId}/{this.moduleId}";
                string password = null;
                if (this.passwordProvider != null)
                {
                    password = await this.passwordProvider.GetPasswordAsync().ConfigureAwait(true);
                }
                else
                {
                    Debug.Assert(this.mqttTransportSettings.ClientCertificate != null);
                }

                var connectPacket = new ConnectPacket
                {
                    ClientId           = id,
                    HasUsername        = true,
                    Username           = $"{this.iotHubHostName}/{id}/?api-version={ClientApiVersionHelper.ApiVersionString}&DeviceClientType={Uri.EscapeDataString(this.productInfo.ToString())}",
                    HasPassword        = !string.IsNullOrEmpty(password),
                    Password           = password,
                    KeepAliveInSeconds = this.mqttTransportSettings.KeepAliveInSeconds,
                    CleanSession       = this.mqttTransportSettings.CleanSession,
                    HasWill            = this.mqttTransportSettings.HasWill
                };
                if (connectPacket.HasWill)
                {
                    Message          message            = this.willMessage.Message;
                    QualityOfService publishToServerQoS = this.mqttTransportSettings.PublishToServerQoS;
                    string           topicName          = this.GetTelemetryTopicName();
                    PublishPacket    will = await Util.ComposePublishPacketAsync(context, message, publishToServerQoS, topicName).ConfigureAwait(true);

                    connectPacket.WillMessage          = will.Payload;
                    connectPacket.WillQualityOfService = this.willMessage.QoS;
                    connectPacket.WillRetain           = false;
                    connectPacket.WillTopicName        = will.TopicName;
                }
                this.stateFlags = StateFlags.Connecting;

                await Util.WriteMessageAsync(context, connectPacket, ShutdownOnWriteErrorHandler).ConfigureAwait(true);

                this.lastChannelActivityTime = DateTime.UtcNow;
                this.ScheduleKeepConnectionAlive(context);

                this.ScheduleCheckConnectTimeout(context);
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                ShutdownOnError(context, ex);
            }
            finally
            {
                if (Logging.IsEnabled)
                {
                    Logging.Exit(this, context.Name, nameof(Connect));
                }
            }
        }
 protected NativeChannel(IChannel parent) : base(parent)
 {
     this.state = StateFlags.Open;
 }
Exemplo n.º 54
0
        protected override bool OnEnterNotifyEvent(Gdk.EventCrossing evnt)
        {
            if (!CanActivate) {
                return base.OnEnterNotifyEvent (evnt);
            }

            pending_state = StateFlags;
            SetStateFlags (StateFlags.Prelight, true);

            return base.OnEnterNotifyEvent (evnt);
        }
 protected void SetState(StateFlags stateToSet) => this.state |= stateToSet;
Exemplo n.º 56
0
 protected void SetState(StateFlags stateToSet)
 {
     _state |= stateToSet;
 }
Exemplo n.º 57
0
 /// <summary>
 /// Creates a new camera position packet.
 /// </summary>
 /// <param name="buffer">A buffer contaning the packet data.</param>
 public IS_CPP(byte[] buffer)
     : this() {
     PacketReader reader = new PacketReader(buffer);
     Size = reader.ReadByte();
     Type = (PacketType)reader.ReadByte();
     ReqI = reader.ReadByte();
     reader.Skip(1);
     Pos = new Vec(reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32());
     H = reader.ReadUInt16();
     P = reader.ReadUInt16();
     R = reader.ReadUInt16();
     ViewPLID = reader.ReadByte();
     InGameCam = (ViewIndentifier)reader.ReadByte();
     FOV = reader.ReadSingle();
     Time = TimeSpan.FromMilliseconds(reader.ReadUInt16());
     Flags = (StateFlags)reader.ReadUInt16();
 }
Exemplo n.º 58
0
 protected bool ResetState(StateFlags stateToReset)
 {
     var oldState = _state;
     if ((oldState & stateToReset) != 0)
     {
         _state = oldState & ~stateToReset;
         return true;
     }
     return false;
 }
Exemplo n.º 59
0
 private void SetDirty() => _state |= StateFlags.Dirty;
Exemplo n.º 60
0
 protected bool IsInState(StateFlags stateToCheck)
 {
     return (_state & stateToCheck) == stateToCheck;
 }