コード例 #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserDTO"/> class.
 /// </summary>
 /// <param name="UserToWrap">The user to wrap.</param>
 public UserDTO(Open.GI.hypermart.Models.User UserToWrap)
 {
     username = UserToWrap.username;
     PhoneNumnber = UserToWrap.PhoneNumnber;
     Photo_byteArray = UserToWrap.Photo.ImageToByteArray();
     Email = UserToWrap.Email;
 }
コード例 #2
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Can_Close_Connection()
        {
            Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);
            connection.CloseConnection(null);

            var response = DecodeLastFrame() as Close;
            Assert.NotNull(response);
            Assert.AreEqual(ConnectionStateEnum.CLOSE_SENT, connection.State);
        }
コード例 #3
0
ファイル: CommandDispatcher.cs プロジェクト: vuuvv/zecms
        public Response DispatchCommand()
        {
            var cmdName = Parameters["cmd"];

            if (string.IsNullOrEmpty(cmdName))
            {
                return new ErrorResponse("Command not set");
            }

            ICommand cmd = null;

            switch (cmdName)
            {
                case "open":
                    if (!string.IsNullOrEmpty(Parameters["init"]) && Parameters["init"] == "true")
                        cmd = new Init();
                    else
                    {
                        cmd = new Open(Parameters["target"]);
                    }
                    break;
                case "mkdir":
                    cmd = new MkDir(Parameters["current"], Parameters["name"]);
                    break;
                case "rm":
                    cmd = new Rm(Parameters["current"], Parameters["targets[]"]);
                    break;
                case "rename":
                    cmd = new Rename(Parameters["current"], Parameters["target"], Parameters["name"]);
                    break;
                case "upload":
                    cmd = new Upload(Parameters["current"], Files);
                    break;
                case "ping":
                    cmd = new Ping();
                    break;
                case "duplicate":
                    cmd = new Duplicate(Parameters["current"], Parameters["target"]);
                    break;
                case "paste":
                    cmd = new Paste(Parameters["src"], Parameters["dst"], Parameters["targets[]"], Parameters["cut"]);
                    break;
            }

            if (cmd == null)
            {
                return new ErrorResponse("Unknown command");
            }

            return cmd.Execute();

            return new ErrorResponse("Unknown error");
        }
コード例 #4
0
        public void Can_Encode_And_Decode_MulipleValue_Fields_SingleValue()
        {
            var buffer = new ByteBuffer(1024, false);

            var value = new Open();
            value.DesiredCapabilities = new Symbol[] { Guid.NewGuid().ToString() };

            AmqpCodec.EncodeObject(buffer, value);

            var decodedValue = AmqpCodec.DecodeObject<Open>(buffer);

            CollectionAssert.AreEqual(value.DesiredCapabilities, decodedValue.DesiredCapabilities);
        }
コード例 #5
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Can_Close()
        {
            Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);

            var close = new Close();
            EncodeAndSend(close);

            Assert.AreEqual(ConnectionStateEnum.END, connection.State);
            Assert.True(socket.Closed);
            Assert.AreEqual(2, socket.WriteBuffer.Count);
        }
コード例 #6
0
 public FileDTO AddFile(int ProductID, Open.GI.hypermart.Models.File FileToAdd)
 {
     var AddedFile = db.Files.Add(FileToAdd);
     return new FileDTO()
     {
         ID = AddedFile.ID,
         BLOB = AddedFile.BLOB,
         FileName = AddedFile.FileName,
         Link = AddedFile.Link,
         Platforms = AddedFile.Platforms,
         Product = AddedFile.Product,
         ProductID = AddedFile.ProductID,
         StorageType = AddedFile.StorageType,
         Version = AddedFile.Version
     };
 }
コード例 #7
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Can_Ignore_IdleTimeOut()
        {
            Given_Exchanged_Headers();

            var open = new Open()
            {
                ContainerID = Guid.NewGuid().ToString(),
                Hostname = "localhost",
                MaxFrameSize = 600,
                ChannelMax = 10,
                //IdleTimeOut = 1000,
            };
            EncodeAndSend(open);
            var response = DecodeLastFrame() as Open;

            Assert.AreEqual(AmqpConnection.DefaultIdleTimeout, response.IdleTimeOut, "IdleTimeOut");
        }
コード例 #8
0
		public override void Visit(Open open)
		{
			// include links to all the query dsl usage and aggregation usage pages on the landing query dsl and aggregations pages, respectively.
			string usageFilePath;
			if (IncludeDirectories.TryGetValue(_destination.Name, out usageFilePath))
			{
				var usageDoc = Document.Load(Path.Combine(Program.OutputDirPath, usageFilePath));

				var includeAttribute = usageDoc.Attributes.FirstOrDefault(a => a.Name == "includes-from-dirs");

				if (includeAttribute != null)
				{
					var directories = includeAttribute.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

					var list = new UnorderedList();

					foreach (var directory in directories)
					{
						foreach (var file in Directory.EnumerateFiles(Path.Combine(Program.OutputDirPath, directory), "*usage.asciidoc", SearchOption.AllDirectories))
						{
							var fileInfo = new FileInfo(file);
							var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileInfo.Name);

							list.Items.Add(new UnorderedListItem
							{
								new Paragraph(new InternalAnchor(fileNameWithoutExtension, fileNameWithoutExtension.LowercaseHyphenToPascal()))
							});
						}
					}

					open.Add(list);
				}
			}

			base.Visit(open);
		}
コード例 #9
0
ファイル: APro.cs プロジェクト: burstas/rmps
 public void ShowOpen(string file, CallBackHandler<string> handler)
 {
     if (_Open == null)
     {
         _Open = new Open();
     }
     _Open.CallBack = handler;
     _Open.Show(_ASec, file);
 }
コード例 #10
0
ファイル: Connection.cs プロジェクト: pisees/amqpnetlite
        void Connect(SaslProfile saslProfile, Open open)
        {
            if (open != null)
            {
                this.maxFrameSize = open.MaxFrameSize;
                this.channelMax   = open.ChannelMax;
            }
            else
            {
                open = new Open()
                {
                    ContainerId  = Guid.NewGuid().ToString(),
                    HostName     = this.address.Host,
                    MaxFrameSize = this.maxFrameSize,
                    ChannelMax   = this.channelMax
                };
            }

            if (open.IdleTimeOut > 0)
            {
                this.heartBeat = new HeartBeat(this, open.IdleTimeOut);
            }

            ITransport transport;

#if NETFX
            if (WebSocketTransport.MatchScheme(address.Scheme))
            {
                WebSocketTransport wsTransport = new WebSocketTransport();
                wsTransport.ConnectAsync(address, null).ConfigureAwait(false).GetAwaiter().GetResult();
                transport = wsTransport;
            }
            else
#endif
            {
                TcpTransport tcpTransport = new TcpTransport();
                tcpTransport.Connect(this, this.address, DisableServerCertValidation);
                transport = tcpTransport;
            }

            try
            {
                if (saslProfile != null)
                {
                    transport = saslProfile.Open(this.address.Host, transport);
                }
                else if (this.address.User != null)
                {
                    transport = new SaslPlainProfile(this.address.User, this.address.Password).Open(this.address.Host, transport);
                }
            }
            catch
            {
                transport.Close();
                throw;
            }

            this.writer = new Writer(transport);

            // after getting the transport, move state to open pipe before starting the pump
            this.SendHeader();
            this.SendOpen(open);
            this.state = ConnectionState.OpenPipe;

            this.reader = new Pump(this, transport);
            this.reader.Start();
        }
コード例 #11
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Receives_Open_Frame_In_Response_To_Open()
        {
            Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);
            var responseOpen = DecodeLastFrame() as Open;

            Assert.NotNull(responseOpen);
        }
コード例 #12
0
ファイル: AmqpCFXEndpoint.cs プロジェクト: njkowlski/CFX
        /// <summary>
        /// Tests if this endpoint is capable of subscribing to and receiving message from the specified network address and AMQP source address.
        /// </summary>
        /// <param name="networkAddress">The network address of the target channel.</param>
        /// <param name="address">The AMQP source address from which messages will be received.</param>
        /// <param name="error">In the case of an error, returns information about the nature of the error.</param>
        /// <param name="virtualHostName">The name of the virtual host at the destination endpoint.  Default is null for default virtual host.</param>
        /// <returns>A boolean value indicated whether or not the channel is valid.</returns>
        public bool TestSubscribeChannel(Uri networkAddress, string address, out Exception error, string virtualHostName = null)
        {
            error = null;
            Connection   conn = null;
            Session      sess = null;
            ReceiverLink link = null;
            Exception    ex   = null;

            try
            {
                Open o = new Open()
                {
                    ContainerId  = Guid.NewGuid().ToString(),
                    HostName     = virtualHostName,
                    MaxFrameSize = (uint)AmqpCFXEndpoint.MaxFrameSize.Value
                };

                Amqp.Framing.Source source = new Amqp.Framing.Source()
                {
                    Address = address,
                    Durable = AmqpCFXEndpoint.DurableReceiverSetting.Value
                };

                ConnectionFactory fact = new ConnectionFactory();
                if (string.IsNullOrWhiteSpace(networkAddress.UserInfo))
                {
                    fact.SASL.Profile = SaslProfile.Anonymous;
                }

                Task <Connection> tConn = fact.CreateAsync(new Address(networkAddress.ToString()), o);
                tConn.Wait(3000);
                if (tConn.Status != TaskStatus.RanToCompletion)
                {
                    throw new Exception("Timeout");
                }

                conn         = tConn.Result;
                conn.Closed += (IAmqpObject s, Error e) => { if (e != null)
                                                             {
                                                                 ex = new Exception(e.Description);
                                                             }
                };
                sess         = new Session(conn);
                sess.Closed += (IAmqpObject s, Error e) => { if (e != null)
                                                             {
                                                                 ex = new Exception(e.Description);
                                                             }
                };
                if (ex != null)
                {
                    throw ex;
                }
                link         = new ReceiverLink(sess, address, source, null);
                link.Closed += (IAmqpObject s, Error e) => { if (e != null)
                                                             {
                                                                 ex = new Exception(e.Description);
                                                             }
                };
                link.Close();
                Task.Delay(10).Wait();
                if (ex != null)
                {
                    throw ex;
                }
            }
            catch (Exception ex2)
            {
                error = ex2;
                Debug.WriteLine(ex2.Message);
            }
            finally
            {
                if (sess != null && !sess.IsClosed)
                {
                    sess.CloseAsync();
                }
                if (conn != null && !conn.IsClosed)
                {
                    conn.CloseAsync();
                }
            }

            if (error == null)
            {
                return(true);
            }
            return(false);
        }
コード例 #13
0
 /// <summary>
 /// Creates a new connection with a custom open frame and a callback to handle remote open frame.
 /// </summary>
 /// <param name="address">The address of remote endpoint to connect to.</param>
 /// <param name="open">If specified, it is sent to open the connection, otherwise an open frame created from the AMQP settings property is sent.</param>
 /// <param name="onOpened">If specified, it is invoked when an open frame is received from the remote peer.</param>
 /// <returns>A task for the connection creation operation. On success, the result is an AMQP <see cref="Connection"/></returns>
 public Task <Connection> CreateAsync(Address address, Open open = null, OnOpened onOpened = null)
 {
     return(this.CreateAsync(address, open, onOpened, null));
 }
コード例 #14
0
ファイル: AStar_0.cs プロジェクト: wjk17/WSA
 Close Shift(Open q)
 {
     return(q.list[--q.length]);
 }
コード例 #15
0
 public void CloseOpenMeasurement()
 {
     Open?.CloseMeasurement();
 }
コード例 #16
0
 private void ExecuteOpenReplaceCommand()
 {
     _openReplace(Open.ChooseFile());
 }
コード例 #17
0
 /// <summary>
 /// Gives the size of the unpacked archive files
 /// </summary>
 /// <param name="total">Size of the unpacked archive files (in bytes)</param>
 public void SetTotal(ulong total)
 {
     _bytesCount = (long)total;
     Open?.Invoke(this, new OpenEventArgs(total));
 }
コード例 #18
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Must_Have_Received_Header_Before_Open_Frame()
        {
            //Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);

            Assert.AreEqual(ConnectionStateEnum.END, connection.State);
            Assert.True(socket.Closed);
            Assert.AreEqual(1, socket.WriteBuffer.Count);
            Assert.AreEqual(8, socket.WriteBuffer[0].LengthAvailableToRead); // 8 byte for proto header
        }
コード例 #19
0
 private void ExecuteOpenFolderCommand()
 {
     _addFile(Open.GetAllFile(Open.ChooseFolder()));
     _showMessage($"总共有{FileList.Count}个文件!");
 }
コード例 #20
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Can_Open_Connection()
        {
            Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);

            Assert.AreEqual(ConnectionStateEnum.OPENED, connection.State);
            Assert.True(socket.IsNotClosed);
            Assert.AreEqual(1, socket.WriteBuffer.Count);
        }
コード例 #21
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Can_Negotiate_Open_Limitations()
        {
            Given_Exchanged_Headers();

            var open = new Open()
            {
                ContainerID = Guid.NewGuid().ToString(),
                Hostname = "localhost",
                MaxFrameSize = 600,
                ChannelMax = 10,
            };
            EncodeAndSend(open);
            var response = DecodeLastFrame() as Open;

            Assert.AreEqual(600, response.MaxFrameSize, "MaxFrameSize");
            Assert.AreEqual(10, response.ChannelMax, "ChannelMax");
        }
コード例 #22
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void On_Idle_Sends_Close()
        {
            Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);
            connection.CloseDueToTimeout();

            var response = DecodeLastFrame() as Close;
            Assert.NotNull(response);
            Assert.AreEqual(ConnectionStateEnum.DISCARDING, connection.State);
        }
コード例 #23
0
        /// <summary>
        /// Open the Serial Port
        /// </summary>
        /// <param name="open"></param>
        private IEnumerator<ITask> CommOpenHandler(Open open)
        {
            //////Debugger.Break();
            Fault responseFault = null;
            bool connected = false;

            try
            {
                if (buffer == null)
                    buffer = new byte[2];

                if (open.Body.BaudRate < 1200)
                    open.Body.BaudRate = 115200;

                _state.ConnectOverBluetooth = (open.Body.ConnectionType == LegoConnectionType.Bluetooth);

                CloseSerialPort();

                if (open.Body.SerialPort > 0)
                {
                    string portName = "COM" + open.Body.SerialPort.ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
                    if (_commState.SerialPort != null)
                    {
                        try
                        {
                            _commState.SerialPort.Dispose();
                        }
                        catch(Exception ex)
                        {
                            LogError(ex);
                        }
                        yield return Arbiter.Receive(false, TimeoutPort(300), EmptyHandler<DateTime>);
                        _commState.SerialPort = null;
                    }

                    try
                    {
                        _commState.SerialPort = new SerialPort(portName, open.Body.BaudRate);
                        _commState.SerialPort.Encoding = Encoding.Default;
                        _commState.SerialPort.Parity = Parity.None;
                        _commState.SerialPort.DataBits = 8;
                        _commState.SerialPort.StopBits = StopBits.One;
                        _commState.SerialPort.WriteTimeout = 2000;
                        _commState.SerialPort.ReadTimeout = 2000;
                        _commState.SerialPort.Handshake = Handshake.RequestToSend;

                        int tryCount = 0;
                        Fault fault = null;
                        while (!_commState.SerialPort.IsOpen && tryCount < 4)
                        {
                            try
                            {
                                tryCount++;
                                _commState.SerialPort.Open();
                            }
                            catch (Exception ex)
                            {
                                fault = Fault.FromException(ex);
                            }
                        }
                        if (_commState.SerialPort.IsOpen)
                        {
                            connected = true;

                            // Wait for a request/response
                            ActivateNextRequest();
                        }
                        else
                        {
                            LogError(LogGroups.Console, "Invalid Serial Port", fault);
                            responseFault = fault;
                        }
                    }
                    catch (Exception ex)
                    {
                        responseFault = Fault.FromException(ex);
                    }

                }
                else
                {
                    responseFault = Fault.FromException(new ArgumentException("The LEGO NXT Serial Port is not specified"));
                }
            }
            finally
            {
                if (connected)
                {
                    open.ResponsePort.Post(DefaultSubmitResponseType.Instance);
                }
                else
                {
                    if (responseFault == null)
                        responseFault = Fault.FromException(new ArgumentException("Failed to connect to the LEGO NXT Serial Port."));

                    open.ResponsePort.Post(responseFault);
                }

            }
            yield break;
        }
 private void Openfile_Click(object sender, EventArgs e)
 {
     Open.ShowDialog();
     Settings.Default.AlarmSrc = Open.FileName;
     Settings.Default.Save();
 }
コード例 #25
0
ファイル: OAuthService.cs プロジェクト: newlysoft/WeiXinSDK-1
 /// <summary>
 /// 初始化一个新的授权服务实例。
 /// </summary>
 /// <param name="accountModel">账号模型。</param>
 /// <param name="openAccountModel">开放平台账号模型。</param>
 public OAuthService(AccountModel accountModel, Open.Api.AccountModel openAccountModel)
 {
     _accountModel = accountModel;
     _openAccountModel = openAccountModel;
 }
コード例 #26
0
ファイル: GoblinBat.cs プロジェクト: w1r2p1/GoblinBat
        internal GoblinBat(char initial, Secret secret, string key, CancellationTokenSource cts, Strategy.Retrieve retrieve)
        {
            var collect = ((char)Port.Collecting).Equals(initial);

            this.key      = key;
            this.initial  = initial;
            this.secret   = secret;
            this.cts      = cts;
            this.retrieve = retrieve;
            InitializeComponent();
            Opacity = 0;

            if (collect)
            {
                Open = OpenAPI.ConnectAPI.GetInstance(key, 205);
                Open.SetAPI(axAPI);
                Open.SendCount += OnReceiveNotifyIcon;
            }
            switch (initial)
            {
            case collecting:
            case trading:
            case (char)83:
                if (Statistical == null)
                {
                    Statistical = initial.Equals((char)Port.Trading) ? new StatisticalControl(Strategy.Retrieve.Code, secret.strategy, secret.rate, secret.commission) : new StatisticalControl(Strategy.Retrieve.Code, secret.rate, secret.commission);
                    panel.Controls.Add(Statistical);
                    Statistical.Dock = DockStyle.Fill;
                    Statistical.Show();
                }
                if (Quotes == null)
                {
                    Quotes = new QuotesControl();
                    panel.Controls.Add(Quotes);
                    Quotes.Dock = DockStyle.Fill;
                    Quotes.Show();
                    strip.ItemClicked += OnItemClick;
                }
                if (collect)
                {
                    Open.SendQuotes += Quotes.OnReceiveQuotes;
                    Open.StartProgress(new OpenAPI.Temporary(Open, new StringBuilder(1024), key));
                }
                else
                {
                    Specify         = Statistical.Statistics(retrieve.GetUserStrategy());
                    Xing            = XingAPI.ConnectAPI.GetInstance(Strategy.Retrieve.Code, Strategy.Retrieve.Date);
                    Xing.Send      += OnReceiveNotifyIcon;
                    notifyIcon.Text = string.Concat("Trading Code_", Strategy.Retrieve.Code);
                    Text            = Xing.Account;
                    BeginInvoke(new Action(() => OnEventConnect()));
                    OnClickMinimized = quo;
                }
                Size = new Size(281, 5);
                break;

            default:
                Open.StartProgress();
                Size = new Size(238, 35);
                break;
            }
            CenterToScreen();
        }
コード例 #27
0
 /* ----------------------------------------------------------------- */
 ///
 /// OnOpen
 ///
 /// <summary>
 /// Open イベントを発生させます。
 /// </summary>
 ///
 /* ----------------------------------------------------------------- */
 protected virtual void OnOpen(ValueEventArgs <string[]> e)
 => Open?.Invoke(this, e);
コード例 #28
0
ファイル: AmqpConnection.cs プロジェクト: Mesjasz82/CFX
        public void OpenConnection()
        {
            Cleanup();

            Exception connectException = null;

            Task.Run(() =>
            {
                try
                {
                    bool anonymous = false;
                    if (AuthenticationMode == AuthenticationMode.Anonymous)
                    {
                        anonymous = true;
                    }
                    else if (AuthenticationMode == AuthenticationMode.Auto)
                    {
                        if (!NetworkUri.ToString().Contains("@"))
                        {
                            anonymous = true;
                        }
                    }

                    Open o = new Open()
                    {
                        ContainerId = Endpoint.CFXHandle != null ? Endpoint.CFXHandle : Guid.NewGuid().ToString(),
                        HostName    = TargetHostName
                    };

                    if (!anonymous || Certificate != null)
                    {
                        isAsync = true;

                        ConnectionFactory factory = new ConnectionFactory();
                        if (anonymous)
                        {
                            factory.SASL.Profile = SaslProfile.External;
                        }
                        else
                        {
                            factory.SASL.Profile = SaslProfile.Anonymous;
                        }
                        //if (Certificate != null) factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;

                        Task <Connection> t = factory.CreateAsync(new Address(NetworkUri.ToString()), o, null);
                        t.Wait(5000);
                        if (t.IsCanceled)
                        {
                            throw new Exception("Timeout on CreateAsync");
                        }

                        connection = t.Result;
                    }
                    else
                    {
                        isAsync    = false;
                        connection = new Connection(new Address(NetworkUri.ToString()), SaslProfile.Anonymous, o, null);
                    }

                    connection.Closed += AmqpObject_Closed;
                    session            = new Session(connection);
                    session.Closed    += AmqpObject_Closed;
                }
                catch (Exception ex)
                {
                    connectException = ex;
                    Debug.WriteLine(ex.Message);
                    Cleanup();
                }
            }).Wait();

            if (connectException != null)
            {
                Cleanup();
                throw connectException;
            }
        }
コード例 #29
0
 /// <summary>
 /// Determines whether the specified <see cref="Open" />, is equal to this instance.
 /// </summary>
 /// <param name="other">The other.</param>
 /// <returns>true if equal; otherwise, false</returns>
 protected bool Equals(Open other) =>
 base.Equals(other) &&
 Equals(Attributes, other.Attributes);
コード例 #30
0
ファイル: Items.cs プロジェクト: The1fEst/TestAppAvalonia
 public void OpenItem(string message)
 {
     Open?.Invoke(message);
 }
コード例 #31
0
 /// <summary>
 /// Event invocator for the <see cref="Open"/> event
 /// </summary>
 protected virtual void OnOpen()
 {
     Log.Trace($"WebSocketClientWrapper.OnOpen(): Connection opened (IsOpen:{IsOpen}, State:{_client.State}): {_url}");
     Open?.Invoke(this, EventArgs.Empty);
 }
コード例 #32
0
    public CloudViewModel(
        CloudState state,
        CreateFolderViewModelFactory createFolderFactory,
        RenameFileViewModelFactory renameFactory,
        FileViewModelFactory fileFactory,
        FolderViewModelFactory folderFactory,
        IAuthViewModel auth,
        IFileManager files,
        ICloud cloud)
    {
        _cloud = cloud;
        Folder = createFolderFactory(this);
        Rename = renameFactory(this);
        Auth   = auth;

        var canInteract = this
                          .WhenAnyValue(
            x => x.Folder.IsVisible,
            x => x.Rename.IsVisible,
            (folder, rename) => !folder && !rename);

        _canInteract = canInteract
                       .ToProperty(this, x => x.CanInteract);

        var canRefresh = this
                         .WhenAnyValue(
            x => x.Folder.IsVisible,
            x => x.Rename.IsVisible,
            x => x.Auth.IsAuthenticated,
            (folder, rename, authenticated) => !folder && !rename && authenticated);

        Refresh = ReactiveCommand.CreateFromTask(
            () => cloud.GetFiles(CurrentPath),
            canRefresh);

        _files = Refresh
                 .Select(
            items => items
            .Select(file => fileFactory(file, this))
            .OrderByDescending(file => file.IsFolder)
            .ThenBy(file => file.Name)
            .ToList())
                 .Where(items => Files == null || !items.SequenceEqual(Files))
                 .ToProperty(this, x => x.Files);

        _isLoading = Refresh
                     .IsExecuting
                     .ToProperty(this, x => x.IsLoading);

        _isReady = Refresh
                   .IsExecuting
                   .Skip(1)
                   .Select(executing => !executing)
                   .ToProperty(this, x => x.IsReady);

        var canOpenCurrentPath = this
                                 .WhenAnyValue(x => x.SelectedFile)
                                 .Select(file => file != null && file.IsFolder)
                                 .CombineLatest(Refresh.IsExecuting, canInteract, (folder, busy, ci) => folder && ci && !busy);

        Open = ReactiveCommand.Create(
            () => Path.Combine(CurrentPath, SelectedFile.Name),
            canOpenCurrentPath);

        var canCurrentPathGoBack = this
                                   .WhenAnyValue(x => x.CurrentPath)
                                   .Where(path => path != null)
                                   .Select(path => path.Length > cloud.InitialPath.Length)
                                   .CombineLatest(Refresh.IsExecuting, canInteract, (valid, busy, ci) => valid && ci && !busy);

        Back = ReactiveCommand.Create(
            () => Path.GetDirectoryName(CurrentPath),
            canCurrentPathGoBack);

        SetPath = ReactiveCommand.Create <string, string>(path => path);

        _currentPath = Open
                       .Merge(Back)
                       .Merge(SetPath)
                       .Select(path => path ?? cloud.InitialPath)
                       .DistinctUntilChanged()
                       .Log(this, $"Current path changed in {cloud.Name}")
                       .ToProperty(this, x => x.CurrentPath, state.CurrentPath ?? cloud.InitialPath);

        var getBreadCrumbs = ReactiveCommand.CreateFromTask(
            () => cloud.GetBreadCrumbs(CurrentPath));

        _breadCrumbs = getBreadCrumbs
                       .Where(items => items != null && items.Any())
                       .Select(items => items.Select(folder => folderFactory(folder, this)))
                       .ToProperty(this, x => x.BreadCrumbs);

        _showBreadCrumbs = getBreadCrumbs
                           .ThrownExceptions
                           .Select(exception => false)
                           .Merge(getBreadCrumbs.Select(items => items != null && items.Any()))
                           .ObserveOn(RxApp.MainThreadScheduler)
                           .ToProperty(this, x => x.ShowBreadCrumbs);

        _hideBreadCrumbs = this
                           .WhenAnyValue(x => x.ShowBreadCrumbs)
                           .Select(show => !show)
                           .ToProperty(this, x => x.HideBreadCrumbs);

        this.WhenAnyValue(x => x.CurrentPath, x => x.IsReady)
        .Where(x => x.Item1 != null && x.Item2)
        .Select(_ => Unit.Default)
        .InvokeCommand(getBreadCrumbs);

        this.WhenAnyValue(x => x.CurrentPath)
        .Skip(1)
        .Select(_ => Unit.Default)
        .InvokeCommand(Refresh);

        this.WhenAnyValue(x => x.CurrentPath)
        .Subscribe(_ => SelectedFile = null);

        _isCurrentPathEmpty = this
                              .WhenAnyValue(x => x.Files)
                              .Skip(1)
                              .Where(items => items != null)
                              .Select(items => !items.Any())
                              .ToProperty(this, x => x.IsCurrentPathEmpty);

        _hasErrorMessage = Refresh
                           .ThrownExceptions
                           .Select(exception => true)
                           .ObserveOn(RxApp.MainThreadScheduler)
                           .Merge(Refresh.Select(x => false))
                           .ToProperty(this, x => x.HasErrorMessage);

        var canUploadToCurrentPath = this
                                     .WhenAnyValue(x => x.CurrentPath)
                                     .Select(path => path != null)
                                     .CombineLatest(Refresh.IsExecuting, canInteract, (up, loading, can) => up && can && !loading);

        UploadToCurrentPath = ReactiveCommand.CreateFromObservable(
            () => Observable
            .FromAsync(files.OpenRead)
            .Where(response => response.Name != null && response.Stream != null)
            .Select(args => _cloud.UploadFile(CurrentPath, args.Stream, args.Name))
            .SelectMany(task => task.ToObservable()),
            canUploadToCurrentPath);

        UploadToCurrentPath.InvokeCommand(Refresh);

        var canDownloadSelectedFile = this
                                      .WhenAnyValue(x => x.SelectedFile)
                                      .Select(file => file != null && !file.IsFolder)
                                      .CombineLatest(Refresh.IsExecuting, canInteract, (down, loading, can) => down && !loading && can);

        DownloadSelectedFile = ReactiveCommand.CreateFromObservable(
            () => Observable
            .FromAsync(() => files.OpenWrite(SelectedFile.Name))
            .Where(stream => stream != null)
            .Select(stream => _cloud.DownloadFile(SelectedFile.Path, stream))
            .SelectMany(task => task.ToObservable()),
            canDownloadSelectedFile);

        var canLogout = cloud
                        .IsAuthorized
                        .DistinctUntilChanged()
                        .Select(loggedIn => loggedIn && (
                                    cloud.SupportsDirectAuth ||
                                    cloud.SupportsOAuth ||
                                    cloud.SupportsHostAuth))
                        .CombineLatest(canInteract, (logout, interact) => logout && interact)
                        .ObserveOn(RxApp.MainThreadScheduler);

        Logout = ReactiveCommand.CreateFromTask(cloud.Logout, canLogout);

        _canLogout = canLogout
                     .ToProperty(this, x => x.CanLogout);

        var canDeleteSelection = this
                                 .WhenAnyValue(x => x.SelectedFile)
                                 .Select(file => file != null && !file.IsFolder)
                                 .CombineLatest(Refresh.IsExecuting, canInteract, (del, loading, ci) => del && !loading && ci);

        DeleteSelectedFile = ReactiveCommand.CreateFromTask(
            () => cloud.Delete(SelectedFile.Path, SelectedFile.IsFolder),
            canDeleteSelection);

        DeleteSelectedFile.InvokeCommand(Refresh);

        var canUnselectFile = this
                              .WhenAnyValue(x => x.SelectedFile)
                              .Select(selection => selection != null)
                              .CombineLatest(Refresh.IsExecuting, canInteract, (sel, loading, ci) => sel && !loading && ci);

        UnselectFile = ReactiveCommand.Create(
            () => { SelectedFile = null; },
            canUnselectFile);

        UploadToCurrentPath.ThrownExceptions
        .Merge(DeleteSelectedFile.ThrownExceptions)
        .Merge(DownloadSelectedFile.ThrownExceptions)
        .Merge(Refresh.ThrownExceptions)
        .Merge(getBreadCrumbs.ThrownExceptions)
        .Log(this, $"Exception occured in provider {cloud.Name}")
        .Subscribe();

        this.WhenAnyValue(x => x.CurrentPath)
        .Subscribe(path => state.CurrentPath = path);

        this.WhenAnyValue(x => x.Auth.IsAuthenticated)
        .Select(authenticated => authenticated ? _cloud.Parameters?.Token : null)
        .Subscribe(token => state.Token = token);

        this.WhenAnyValue(x => x.Auth.IsAuthenticated)
        .Select(authenticated => authenticated ? _cloud.Parameters?.User : null)
        .Subscribe(user => state.User = user);

        this.WhenActivated(ActivateAutoRefresh);
    }
コード例 #33
0
ファイル: Connection.cs プロジェクト: pisees/amqpnetlite
 /// <summary>
 /// Initializes a connection with SASL profile, open and open callback.
 /// </summary>
 /// <param name="address">The address.</param>
 /// <param name="saslProfile">The SASL profile to do authentication (optional). If it is
 /// null and address has user info, SASL PLAIN profile is used.</param>
 /// <param name="open">The open frame to send (optional). If not null, all mandatory
 /// fields must be set. Ensure that other fields are set to desired values.</param>
 /// <param name="onOpened">The callback to handle remote open frame (optional).</param>
 /// <remarks>
 /// The connection initialization includes establishing the underlying transport,
 /// which typically has blocking network I/O. Depending on the current synchronization
 /// context, it may cause deadlock or UI freeze. Please use the ConnectionFactory.CreateAsync
 /// method instead.
 /// </remarks>
 public Connection(Address address, SaslProfile saslProfile, Open open, OnOpened onOpened)
     : this(address, DefaultMaxSessions, DefaultMaxFrameSize)
 {
     this.onOpened = onOpened;
     this.Connect(saslProfile, open);
 }
コード例 #34
0
ファイル: GoblinBat.cs プロジェクト: hur-kyuh-leez/Strategy
        void OnReceiveItem(string item)
        {
            switch (item)
            {
            case quo:
                if (Array.Exists(XingConnect, o => o.Equals(initial)))
                {
                    foreach (var ctor in Xing.orders)
                    {
                        if (initial.Equals(trading))
                        {
                            ((IStates <State>)ctor).SendState += Quotes.OnReceiveState;
                        }

                        ((IMessage <NotifyIconText>)ctor).SendMessage += OnReceiveNotifyIcon;
                    }
                    for (int i = 0; i < Xing.reals.Length; i++)
                    {
                        switch (i)
                        {
                        case 0:
                            ((IEvents <EventHandler.XingAPI.Quotes>)Xing.reals[i]).Send += Quotes.OnReceiveQuotes;
                            continue;

                        case 1:
                            if (initial.Equals(trading))
                            {
                                ((ITrends <Trends>)Xing.reals[i]).SendTrend += Quotes.OnReceiveTrend;
                            }

                            continue;

                        case 2:
                            Text = XingAPI.ConnectAPI.Code;
                            continue;

                        default:
                            if (initial.Equals(trading))
                            {
                                ((IStates <State>)Xing.reals[i]).SendState += Quotes.OnReceiveState;
                            }

                            continue;
                        }
                    }
                    Xing.OnReceiveBalance = true;
                }
                else
                {
                    Open.SendQuotes += Quotes.OnReceiveQuotes;
                    Open.SendState  += Quotes.OnReceiveState;
                    Open.SendTrend  += Quotes.OnReceiveTrend;
                }
                Size = new Size(323, 493);
                Quotes.Show();
                break;

            case ex:
                Text = secret.GetIdentify();
                Size = new Size(241, 0);
                CenterToScreen();
                Close();
                return;

            case st:
                if (Xing != null && Array.Exists(XingConnect, o => o.Equals(initial)))
                {
                    Text = Xing.GetAccountName(Xing.Accounts.Length == 1 ? Xing.Accounts[0] : Array.Find(Xing.Accounts, o => o.Substring(o.Length - 2, 2).Equals("02")));
                }

                Size = new Size(795, 433);
                Statistical.Show();
                break;

            case acc:
                if (Array.Exists(XingConnect, o => o.Equals(initial)))
                {
                    Text = (Xing.Accounts.Length == 1 ? Xing.Accounts[0] : Array.Find(Xing.Accounts, o => o.Substring(o.Length - 2, 2).Equals("02"))).Insert(5, "-").Insert(3, "-");
                    var query = Xing.querys[0];
                    ((IEvents <Deposit>)query).Send += Account.OnReceiveDeposit;
                    ((IMessage <NotifyIconText>)query).SendMessage += OnReceiveNotifyIcon;
                    query.QueryExcute();
                }
                else
                {
                    Open.SendDeposit += Account.OnReceiveDeposit;
                    Open.LookUpTheDeposit(Acc);
                }
                Size = new Size(749, 372);
                Account.Show();
                break;

            case bal:
                if (Array.Exists(XingConnect, o => o.Equals(initial)))
                {
                    Text = Xing.DetailName;
                    var query = Xing.querys[1];
                    ((IEvents <Balance>)query).Send += Balance.OnReceiveBalance;
                    ((IMessage <NotifyIconText>)query).SendMessage += OnReceiveNotifyIcon;
                    query.QueryExcute();
                }
                else
                {
                    Open.SendBalance += Balance.OnReceiveBalance;
                    Open.LookUpTheBalance(Acc);
                }
                Size = new Size(249, 0);
                Balance.SendReSize += OnReceiveSize;
                break;
            }
        }
コード例 #35
0
 private void ExecuteOpenFolderCommand()
 {
     _findDir(Open.ChooseFolder());
 }
コード例 #36
0
ファイル: ConnectionTests.cs プロジェクト: jdaigle/LightRail
        public void Sends_Close_on_Close()
        {
            Given_Exchanged_Headers();

            var open = new Open();
            EncodeAndSend(open);

            var close = new Close();
            EncodeAndSend(close);

            var response = DecodeLastFrame() as Close;
            Assert.NotNull(response);
        }
コード例 #37
0
ファイル: GoblinBat.cs プロジェクト: w1r2p1/GoblinBat
        void OnReceiveNotifyIcon(object sender, NotifyIconText e)
        {
            switch (e.NotifyIcon.GetType().Name)
            {
            case GoblinBat.array:
                var array = (string[])e.NotifyIcon;
                notifyIcon.Text = string.Concat(array[0], array[1]);
                return;

            case tuple:
                new Task(() => new Strategy.OpenAPI.Consecutive(key, ((Tuple <string, string>)e.NotifyIcon).Item1.Split(';'))).Start();
                notifyIcon.Text = ((Tuple <string, string>)e.NotifyIcon).Item2.Replace(';', '\n');
                return;

            case dic:
                var temp = (Dictionary <int, string>)e.NotifyIcon;

                if (temp.TryGetValue(0, out string code))
                {
                    if (secret.GetIsSever(key))
                    {
                        notifyIcon.Text = checkDataBase;
                        Open.StartProgress(0xE15);
                    }
                    notifyIcon.Text = secret.GetIdentify();

                    return;
                }
                var first = temp.First();
                notifyIcon.Text = string.Concat(DateTime.Now.ToShortTimeString(), " Remains_", first.Key, " Code_", first.Value);
                return;

            case sb:
                strip.ItemClicked += OnItemClick;
                BeginInvoke(new Action(() =>
                {
                    if (Quotes == null)
                    {
                        Quotes = new QuotesControl();
                        panel.Controls.Add(Quotes);
                        Open.SendQuotes += Quotes.OnReceiveQuotes;
                        Quotes.Dock      = DockStyle.Fill;
                    }
                    if (Account == null)
                    {
                        Account = new AccountControl();
                        panel.Controls.Add(Account);
                        Account.Dock      = DockStyle.Fill;
                        Open.SendDeposit += Account.OnReceiveDeposit;
                    }
                    if (Balance == null)
                    {
                        Balance = new BalanceControl();
                        panel.Controls.Add(Balance);
                        Balance.Dock      = DockStyle.Fill;
                        Open.SendBalance += Balance.OnReceiveBalance;
                    }
                    if (Statistical == null)
                    {
                        Statistical = new StatisticalControl(Strategy.Retrieve.Code, secret.strategy, secret.rate, secret.commission);
                        panel.Controls.Add(Statistical);
                        Statistical.Dock = DockStyle.Fill;
                    }
                    var chart = Retrieve.GetInstance(key, Open.Code).Chart;
                    var check = e.NotifyIcon.ToString().Split((char)0x3B);
                    Acc       = new string[check.Length - 3];
                    Server    = check[check.Length - 1].Equals(secret.Mock);

                    if (!Server && new VerifyIdentity().Identify(check[check.Length - 3], check[check.Length - 2]) == false)
                    {
                        if (TimerBox.Show(new Secret(check[check.Length - 2]).Identify, secret.GoblinBat, MessageBoxButtons.OK, MessageBoxIcon.Warning, 3750).Equals(DialogResult.OK))
                        {
                            ClosingForm = true;
                            Dispose();
                        }
                        return;
                    }
                    for (int i = 0; i < check.Length - 3; i++)
                    {
                        Acc[i] = check[i];
                    }

                    new Task(() =>
                    {
                        var specify = new Specify
                        {
                            Account  = Acc,
                            Assets   = 0x10B0760,
                            Code     = Open.Code,
                            Strategy = "TF",
                            Time     = 30,
                            Short    = 4,
                            Long     = 60
                        };
                        new Strategy.OpenAPI.Trading(Open, specify, new Strategy.OpenAPI.Quotes(specify, Open), chart);
                    }).Start();
                    new Task(() =>
                    {
                        var liquidate = new Specify
                        {
                            Account  = Acc,
                            Assets   = 0x10B0760,
                            Code     = Open.Code,
                            Strategy = "WU",
                            Time     = 15,
                            Short    = 4,
                            Long     = 60
                        };
                        new Strategy.OpenAPI.Trading(Open, liquidate, new Strategy.OpenAPI.Quotes(liquidate, Open), chart);
                    }).Start();
                    new Task(() => new Strategy.OpenAPI.Trading(Open, new Specify
                    {
                        Account  = Acc,
                        Assets   = 0x10B0760,
                        Code     = Open.Code,
                        Strategy = "DL",
                        Time     = 0x5A0,
                        Short    = 4,
                        Long     = 60,
                        Reaction = 531
                    }, chart)).Start();
                    Open.SendState += Quotes.OnReceiveState;
                    Open.SendTrend += Quotes.OnReceiveTrend;
                    Retrieve.Dispose();
                }));
                return;

            case str:
                BeginInvoke(new Action(() => Quotes.OnReceiveOrderMsg(e.NotifyIcon.ToString())));
                return;

            case bt:
                if (Array.Exists(XingConnect, o => o.Equals(initial)))
                {
                    BeginInvoke(new Action(() =>
                    {
                        Xing            = XingAPI.ConnectAPI.GetInstance(initial.Equals(collecting) ? Open.Code : Strategy.Retrieve.Code, Strategy.Retrieve.Date);
                        Xing.Send      += OnReceiveNotifyIcon;
                        notifyIcon.Text = string.Concat("Trading Code_", initial.Equals(collecting) ? Open.Code : Strategy.Retrieve.Code);
                        OnEventConnect();
                        OnClickMinimized = quo;
                        Application.DoEvents();

                        if (secret.GetIsSever(key))
                        {
                            retrieve.SetInitializeTheChart();
                        }
                    }));
                }
                else
                {
                    Account.Show();
                    Open.SendDeposit -= Account.OnReceiveDeposit;
                    Account.Hide();
                    Balance.Show();
                    Open.SendBalance -= Balance.OnReceiveBalance;
                    Balance.Hide();
                    Open.SendState -= Quotes.OnReceiveState;
                    Open.SendTrend -= Quotes.OnReceiveTrend;
                }
                return;

            case int32:
                if ((int)e.NotifyIcon < 0)
                {
                    if (Temporary != null && initial.Equals(collecting))
                    {
                        Temporary.SetStorage(Open.Code);
                    }

                    Dispose();
                }
                else
                {
                    foreach (var ctor in Xing.querys)
                    {
                        switch (ctor.GetType().Name)
                        {
                        case cfobq10500:
                        case ccebq10500:
                            ((IEvents <Deposit>)ctor).Send -= Account.OnReceiveDeposit;
                            ((IMessage <NotifyIconText>)ctor).SendMessage -= OnReceiveNotifyIcon;
                            Account.Hide();
                            break;

                        case t0441:
                        case cceaq50600:
                            ((IEvents <Balance>)ctor).Send -= Balance.OnReceiveBalance;
                            ((IMessage <NotifyIconText>)ctor).SendMessage -= OnReceiveNotifyIcon;
                            Balance.Hide();
                            break;
                        }
                    }
                    Statistical.Hide();
                    return;
                }
                break;

            case cha:
                switch ((char)e.NotifyIcon)
                {
                case (char)69:
                    new ExceptionMessage(((char)e.NotifyIcon).ToString());
                    Dispose();
                    return;

                case (char)41:
                    if (initial.Equals(collecting) == false && ClosingForm == false)
                    {
                        if (cts == null)
                        {
                            Process.Start("shutdown.exe", "-r");
                        }

                        new ExceptionMessage(((char)e.NotifyIcon).ToString());
                        Dispose();
                    }
                    break;

                case (char)21:
                    new ExceptionMessage(((char)e.NotifyIcon).ToString());
                    break;

                default:
                    return;
                }
                break;

            case boolean:
                break;
            }
        }
コード例 #38
0
 private void ExecuteVisitCommand()
 {
     Open.ExplorePath(AppDomain.CurrentDomain.BaseDirectory + "Mobile");
 }
コード例 #39
0
    public IEnumerable <Node> GetPath(Node start, Node goal)
    {
        this.Parent[start] = null;
        this.Cost[start]   = 0;
        this.Open.Enqueue(start);

        while (Open.Count > 0)
        {
            Node currentNode = Open.Dequeue();
            if (currentNode.Equals(goal))
            {
                break;
            }


            List <Node> neighbours = new List <Node>
            {
                new Node(currentNode.Row + 1, currentNode.Col),
                new Node(currentNode.Row - 1, currentNode.Col),
                new Node(currentNode.Row, currentNode.Col + 1),
                new Node(currentNode.Row, currentNode.Col - 1)
            };

            foreach (Node neighbour in neighbours)
            {
                if (neighbour.Row >= Map.GetLength(0) || (neighbour.Row < 0))
                {
                    continue;
                }

                if (neighbour.Col >= Map.GetLength(1) || (neighbour.Col < 0))
                {
                    continue;
                }

                if (Map[neighbour.Row, neighbour.Col] == 'W' || Map[neighbour.Row, neighbour.Col] == 'P')
                {
                    continue;
                }

                int newCost = Cost[currentNode] + 1;

                if (!Cost.ContainsKey(neighbour) || Cost[neighbour] > newCost)
                {
                    Cost[neighbour] = newCost;
                    neighbour.F     = newCost + GetH(neighbour, goal);
                    Open.Enqueue(neighbour);
                    Parent[neighbour] = currentNode;
                }
            }
        }

        List <Node> result = new List <Node>();

        Node lastNode = goal;

        if (!Parent.ContainsKey(lastNode))
        {
            result.Add(start);
        }
        else
        {
            result.Add(lastNode);
            while (Parent[lastNode] != null)
            {
                result.Add(Parent[lastNode]);
                lastNode = Parent[lastNode];
            }
        }

        result.Reverse();
        return(result);

        //Node lastNode = goal;
        //if (!Parent.ContainsKey(lastNode))
        //{
        //    yield return start;
        //}
        //else
        //{
        //    yield return lastNode;
        //    while (Parent[lastNode] != null)
        //    {
        //        yield return Parent[lastNode];
        //        lastNode = Parent[lastNode];
        //    }
        //}
    }
コード例 #40
0
 protected virtual void onOpen(object sender, EventArgs e)
 {
     Open.Raise(this, null);
 }
コード例 #41
0
ファイル: Connection.cs プロジェクト: npnelson/amqpnetlite
 void SendOpen(Open open)
 {
     this.SendCommand(0, open);
 }
コード例 #42
0
        protected override void OnRender(ChartControl chartControl, ChartScale chartScale)
        {
            base.OnRender(chartControl, chartScale);

            BodyWidth = (int)ChartControl.BarWidth + Math.Min(ShadowWidth * 2, 4);
            if (ChartBars != null)
            {
                // loop through all of the viewable range of the chart
                for (int barIndex = ChartBars.FromIndex; barIndex <= ChartBars.ToIndex; barIndex++)
                {
                    if (ShadowColor == Brushes.Transparent)
                    {
                        if (Close.GetValueAt(barIndex) > Open.GetValueAt(barIndex))
                        {
                            DrawLineNT("BarBrushUp",
                                       barIndex,
                                       HAHigh.GetValueAt(barIndex),
                                       barIndex,
                                       Math.Max(HAClose.GetValueAt(barIndex), HAOpen.GetValueAt(barIndex)),
                                       ShadowWidth,
                                       chartScale);

                            DrawLineNT("BarBrushUp",
                                       barIndex,
                                       HALow.GetValueAt(barIndex),
                                       barIndex,
                                       Math.Min(HAClose.GetValueAt(barIndex), HAOpen.GetValueAt(barIndex)),
                                       ShadowWidth,
                                       chartScale);
                        }
                        else
                        {
                            DrawLineNT("BarBrushDown",
                                       barIndex,
                                       HAHigh.GetValueAt(barIndex),
                                       barIndex,
                                       Math.Max(HAClose.GetValueAt(barIndex), HAOpen.GetValueAt(barIndex)),
                                       ShadowWidth,
                                       chartScale);

                            DrawLineNT("BarBrushDown",
                                       barIndex,
                                       HALow.GetValueAt(barIndex),
                                       barIndex,
                                       Math.Min(HAClose.GetValueAt(barIndex), HAOpen.GetValueAt(barIndex)),
                                       ShadowWidth,
                                       chartScale);
                        }
                    }
                    else
                    {
                        DrawLineNT("ShadowBrush",
                                   barIndex,
                                   HAHigh.GetValueAt(barIndex),
                                   barIndex,
                                   Math.Max(HAClose.GetValueAt(barIndex), HAOpen.GetValueAt(ShadowWidth)),
                                   ShadowWidth,
                                   chartScale);

                        DrawLineNT("ShadowBrush",
                                   barIndex,
                                   HALow.GetValueAt(barIndex),
                                   barIndex,
                                   Math.Min(HAClose.GetValueAt(barIndex), HAOpen.GetValueAt(ShadowWidth)),
                                   ShadowWidth,
                                   chartScale);
                    }

                    if (HAClose.GetValueAt(barIndex) > HAOpen.GetValueAt(barIndex))
                    {
                        DrawLineNT("BarBrushUp",
                                   barIndex,
                                   HAOpen.GetValueAt(barIndex),
                                   barIndex,
                                   HAClose.GetValueAt(barIndex),
                                   BodyWidth,
                                   chartScale);
                    }
                    else
                    {
                        DrawLineNT("BarBrushDown",
                                   barIndex,
                                   HAOpen.GetValueAt(barIndex),
                                   barIndex,
                                   HAClose.GetValueAt(barIndex),
                                   BodyWidth,
                                   chartScale);
                    }
                }
                // Draw price line if wanted

                if (ShowPriceLine)
                {
                    DrawLineNT("PriceLineBrush",
                               Math.Max(PriceLineLength, CurrentBar - 15),
                               Close.GetValueAt(CurrentBar),
                               CurrentBar,
                               Close.GetValueAt(CurrentBar),
                               PriceLineWidth,
                               PriceLineStyle,
                               chartScale);

                    DrawStringNT("  -- " + Close.GetValueAt(CurrentBar).ToString() + " = Last Price",
                                 Font,
                                 "PriceTextBrush",
                                 CurrentBar,
                                 Close.GetValueAt(CurrentBar),
                                 "PriceAreaBrush",
                                 chartScale);
                }
            }
        }
コード例 #43
0
ファイル: Pocetna.cs プロジェクト: acastoiljkovic/TabulaRasa
        private void Pocetna_FormClosing(object sender, FormClosingEventArgs e)
        {
            Open o = new Open();

            o.Close();
        }
コード例 #44
0
        internal void Connect()
        {
            if (this.state.CompareAndSet(ConnectionState.INITIAL, ConnectionState.CONNECTING))
            {
                Address addr = UriUtil.ToAddress(connInfo.remoteHost, connInfo.username, connInfo.password ?? string.Empty);
                Tracer.InfoFormat("Creating Address: {0}", addr.Host);
                if (this.clientIdCanSet.CompareAndSet(true, false))
                {
                    if (this.ClientId == null)
                    {
                        connInfo.ResourceId = this.clientIdGenerator.GenerateId();
                    }
                    else
                    {
                        connInfo.ResourceId = new Id(ClientId);
                    }
                    Tracer.InfoFormat("Staring Connection with Client Id : {0}", this.ClientId);
                }

                Open openFrame = CreateOpenFrame(this.connInfo);

                Task <Amqp.Connection> fconn = this.implCreate(addr, openFrame, this.OpenResponse);
                // wait until the Open request is sent
                this.impl = TaskUtil.Wait(fconn, connInfo.connectTimeout);
                if (fconn.Exception != null)
                {
                    // exceptions thrown from TaskUtil are typically System.AggregateException and are usually transport exceptions for secure transport.
                    // extract the innerException of interest and wrap it as an NMS exception
                    if (fconn.Exception is AggregateException)
                    {
                        throw ExceptionSupport.Wrap(fconn.Exception.InnerException,
                                                    "Failed to connect host {0}. Cause: {1}", openFrame.HostName, fconn.Exception.InnerException?.Message ?? fconn.Exception.Message);
                    }
                    else
                    {
                        throw ExceptionSupport.Wrap(fconn.Exception,
                                                    "Failed to connect host {0}. Cause: {1}", openFrame.HostName, fconn.Exception?.Message);
                    }
                }

                this.impl.Closed += OnInternalClosed;
                this.impl.AddClosedCallback(OnInternalClosed);
                this.latch = new CountDownLatch(1);

                ConnectionState finishedState = ConnectionState.UNKNOWN;
                // Wait for Open response
                try
                {
                    bool received = this.latch.await((this.Info.requestTimeout == 0) ? Timeout.InfiniteTimeSpan : this.RequestTimeout);
                    if (received && this.impl.Error == null && fconn.Exception == null)
                    {
                        Tracer.InfoFormat("Connection {0} has connected.", this.impl.ToString());
                        finishedState = ConnectionState.CONNECTED;
                        // register connection factory once client Id accepted.
                        MessageFactory <ConnectionInfo> .Register(this);
                    }
                    else
                    {
                        if (!received)
                        {
                            // Timeout occured waiting on response
                            Tracer.InfoFormat("Connection Response Timeout. Failed to receive response from {0} in {1}ms", addr.Host, this.Info.requestTimeout);
                        }
                        finishedState = ConnectionState.INITIAL;

                        if (fconn.Exception == null)
                        {
                            if (!received)
                            {
                                throw ExceptionSupport.GetTimeoutException(this.impl, "Connection {0} has failed to connect in {1}ms.", ClientId, connInfo.closeTimeout);
                            }
                            Tracer.ErrorFormat("Connection {0} has Failed to connect. Message: {1}", ClientId, (this.impl.Error == null ? "Unknown" : this.impl.Error.ToString()));

                            throw ExceptionSupport.GetException(this.impl, "Connection {0} has failed to connect.", ClientId);
                        }
                        else
                        {
                            throw ExceptionSupport.Wrap(fconn.Exception, "Connection {0} failed to connect.", ClientId);
                        }
                    }
                }
                finally
                {
                    this.latch = null;
                    this.state.GetAndSet(finishedState);
                    if (finishedState != ConnectionState.CONNECTED)
                    {
                        this.impl.Close(TimeSpan.FromMilliseconds(connInfo.closeTimeout), null);
                    }
                }
            }
        }
コード例 #45
0
        public void Can_Encode_And_Decode_Simple_DescribedList()
        {
            var buffer = new ByteBuffer(1024, false);

            var value = new Open();
            value.ContainerID = Guid.NewGuid().ToString();
            value.IdleTimeOut = (uint)randNum.Next(0, 1000);
            value.ChannelMax = (ushort)randNum.Next(0, 1000);

            AmqpCodec.EncodeObject(buffer, value);

            var decodedValue = AmqpCodec.DecodeObject<Open>(buffer);

            Assert.AreEqual(value.ContainerID, decodedValue.ContainerID);
            Assert.AreEqual(value.IdleTimeOut, decodedValue.IdleTimeOut);
            Assert.AreEqual(value.ChannelMax, decodedValue.ChannelMax);
        }
コード例 #46
0
 // open
 public static uint MaxFrameSize(this Open open)
 {
     return(open.MaxFrameSize == null ? uint.MaxValue : open.MaxFrameSize.Value);
 }
コード例 #47
0
 public void OpenHandler(Open open)
 {
     _commOpenClosePort.Post(open);
 }
コード例 #48
0
 public static ushort ChannelMax(this Open open)
 {
     return(open.ChannelMax == null ? ushort.MaxValue : open.ChannelMax.Value);
 }
コード例 #49
0
 public static uint IdleTimeOut(this Open open)
 {
     return(open.IdleTimeOut == null || open.IdleTimeOut.Value == 0 ? uint.MaxValue : open.IdleTimeOut.Value);
 }
コード例 #50
0
        /// <summary>
        /// Posts the product file.
        /// </summary>
        /// <param name="ProductID">The product identifier.</param>
        /// <param name="FileToAdd">The file to add.</param>
        /// <returns></returns>
        /// <exception cref="System.Web.Http.HttpResponseException"></exception>
        /// <exception cref="System.Exception">Cannot add a product file</exception>
        public FileDTO PostProductFile(int ProductID, Open.GI.hypermart.Models.File FileToAdd)
        {
            try
            {
                Product product = db.Products.Find(ProductID);
                if (product == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                FileToAdd.Product = product;

                var AddedFile = db.Files.Add(FileToAdd);
                db.SaveChanges();
                return new FileDTO(AddedFile);
            }
            catch (Exception ex)
            {

                throw new Exception("Cannot add a product file", ex);
            }
        }