public override async Task<Connections> GetConnections()
        {
            var identifyingSubstring = "VID_2341";

            try
            {
                var devices = SerialDevice.GetDeviceSelector();
                var peers = await DeviceInformation.FindAllAsync(devices);

                var connections = new Connections();
                foreach (var peer in peers)
                {
                    if (peer.Name.Contains(identifyingSubstring) || peer.Id.Contains(identifyingSubstring))
                    {
                        connections.Add(new Connection(peer.Name, peer));
                    }
                }

                return connections;
            }
            catch (Exception)
            {
                return null;
            }
        }
    public SoapEditorProxy(Connections.ConnectionData connData, ServiceDescription description, XmlSchemaSet schemas)
    {
      _connData = connData;
      _descrip = description;
      _schemas = schemas;
      _helper = new XmlCompletionDataProvider(schemas, "http://schemas.xmlsoap.org/soap/envelope/"
        , "soapenv", () => "xmlns:soap=\"" + description.TargetNamespace + "\""
        , e => (e.Name == "Envelope" && e.QualifiedName.Namespace == "http://schemas.xmlsoap.org/soap/envelope/")
          || TypeMatchesAction(e.QualifiedName, this.Action));

      _baseUrl = new Uri(_connData.Url).GetLeftPart(UriPartial.Path);
      switch (_connData.Authentication)
      {
        case Connections.Authentication.Windows:
          _cred = CredentialCache.DefaultNetworkCredentials;
          break;
        case Connections.Authentication.Explicit:
          _cred = new NetworkCredential(_connData.UserName, _connData.Password);
          break;
      }

      _actionUrls = _descrip.Services.OfType<Service>()
        .SelectMany(s => s.Ports.OfType<Port>().Where(SoapPort))
        .SelectMany(p => _descrip.Bindings[p.Binding.Name].Operations.OfType<OperationBinding>())
        .Select(o => new { Name = o.Name, Address = o.Extensions.OfType<SoapOperationBinding>().First().SoapAction })
        .Distinct()
        .ToDictionary(a => a.Name, a => a.Address);
    }
Exemple #3
0
 //BACK-BURNER
 public static void Init(IPoderosaContainer container)
 {
     GConst.Init();
     _frame = container;
     _textSelection = new TextSelection();
     _connections = new Connections();
 }
 public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
 {
     return (
         connections.Contains(ConnectionName)
         && !string.IsNullOrWhiteSpace(TargetPath)
         ) ? DTSExecResult.Success : DTSExecResult.Failure;
 }
 public static Connections Add()
 {
     long localVersion = Interlocked.Increment(ref nextVersion);
     Connections connections = new Connections(localVersion);
     history.Add(localVersion, connections);
     return connections;
 }
        /// <summary>
        /// The edit.
        /// </summary>
        /// <param name="parentWindow">
        /// The parent window.
        /// </param>
        /// <param name="variables">
        /// The variables.
        /// </param>
        /// <param name="connections">
        /// The connections.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool Edit(IWin32Window parentWindow, Variables variables, Connections connections)
        {
            string jsonString = string.Empty;
            var value = this.metaData.CustomPropertyCollection["Settings"].Value;

            if (value != null)
            {
                jsonString = value.ToString();
            }

            List<InputColumnInfo> inputColumnInfos = new List<InputColumnInfo>();
            foreach (IDTSInputColumn100  col in this.metaData.InputCollection[0].InputColumnCollection)
            {
                inputColumnInfos.Add(
                    new InputColumnInfo() { ColumnName = col.Name, DataType = col.DataType, LineageId = col.LineageID });
            }

            FillablePdfDestinationUIForm editor = new FillablePdfDestinationUIForm(
                jsonString,
                inputColumnInfos.ToArray());

            editor.ShowDialog(parentWindow);

            if (editor.DialogResult == DialogResult.OK || editor.DialogResult == DialogResult.Yes)
            {
                this.metaData.CustomPropertyCollection["Settings"].Value = editor.OutputConfigJsonString;
                return true;
            }

            return false;
        }
Exemple #7
0
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {

            System.Threading.Thread.Sleep(this._interval * 60000);

            return DTSExecResult.Success;
        }
        /// <summary>
        /// Validates the specified connections.
        /// </summary>
        /// <param name="connections">The connections.</param>
        /// <param name="variableDispenser">The variable dispenser.</param>
        /// <param name="componentEvents">The component events.</param>
        /// <param name="log">The log.</param>
        /// <returns></returns>
        public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
        {
            try
            {
                string _sourceFile = Common.GetVariableValue<string>(this.sourceFile, variableDispenser);
                string _targetFile = Common.GetVariableValue<string>(this.targetFile, variableDispenser);

                string errorMsg = String.Empty;
                if (String.IsNullOrEmpty(_sourceFile))
                    errorMsg += " Source,";

                if (String.IsNullOrEmpty(_targetFile))
                    errorMsg += " Target,";

                if (errorMsg.Trim().Length > 0)
                {
                    componentEvents.FireError(0, "", "Missing:" + errorMsg.Remove(errorMsg.Length - 1) + ".", "", 0);
                    return DTSExecResult.Failure;
                }
                
                return base.Validate(connections, variableDispenser, componentEvents, log);
            }
            catch (Exception ex)
            {
                componentEvents.FireError(0, "Validate: ", ex.Message + Environment.NewLine + ex.StackTrace, "", 0);
                return DTSExecResult.Failure;
            }
        }
Exemple #9
0
        /// <summary>
        /// Overrides Execute logic
        /// Core Logic: It Fires a Custom Event, with the given ComponentType and Message
        /// <see cref="Microsoft.SqlServer.Dts.Runtime.Task.Execute"/>
        /// </summary>
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            bool refFire = false;
            componentEvents.FireInformation(ComponentType, "", GetMessageText(variableDispenser, componentEvents, MessageText), "", 0, ref refFire);

            return base.Execute(connections, variableDispenser, componentEvents, log, transaction);
        }
        public override async Task<Connections> GetConnections()
        {
            if (isPrePairedDevice)
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            }

            try
            {
                var devices = RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort);
                var peers = await DeviceInformation.FindAllAsync(devices);

                var connections = new Connections();
                foreach (var peer in peers)
                {
                    connections.Add(new Connection(peer.Name, peer));
                }

                return connections;
            }
            catch (Exception e)
            {
                return null;
            }
        }
            public void Add(string key, Guid connectionId, ConnectionType connectionType)
            {
                lock (_connections)
                {
                    Connections connection;
                    if (!_connections.TryGetValue(key, out connection))
                    {
                        connection = new Connections();
                        if (connectionType == ConnectionType.Device)
                        {
                            connection.DeviceConnectionId = connectionId;
                        }
                        else
                        {
                            connection.UserConnectionId = connectionId;
                        }
                        _connections.Add(key, connection);
                    }

                    lock (connection)
                    {
                        if (connectionType == ConnectionType.Device)
                        {
                            connection.DeviceConnectionId = connectionId;
                        }
                        else
                        {
                            connection.UserConnectionId = connectionId;
                        }
                    }
                }
            }
Exemple #12
0
 public AddConnection(ConnectionCollection collection, Connections cons)
 {
     this.cons = cons;
     this.connections = collection;
     this.gxml = new Glade.XML(null, "irisim.glade", "addConnectionDialog", null);
     this.gxml.Autoconnect(this);
 }
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) {
            try {
                var connectionManager = connections[ConnectionName];
                var connection = connectionManager.AcquireConnection(transaction) as SqlConnection;

                var dropKeysScript = Resources.DropCreateFKScriptCommon.Replace(SELECT_STATEMENT_PLACEHOLDER, Resources.CreateFKScript);

                var command = new SqlCommand(dropKeysScript, connection);

                var reader = command.ExecuteReader();

                var scriptBuilder = new StringBuilder();

                while (reader.Read())
                {
                    var dropScript = reader.GetString(reader.GetOrdinal("CreateScript"));
                    //var sourceTableName = reader.GetString(reader.GetOrdinal("SourceTableName"));
                    //var targetTableName = reader.GetString(reader.GetOrdinal("TargetTableName"));

                    scriptBuilder.AppendLine(dropScript);
                }

                if (File.Exists(TargetPath))
                {
                    File.Delete(TargetPath);
                }

                File.WriteAllText(TargetPath, scriptBuilder.ToString());

                return DTSExecResult.Success;
            } catch (Exception ex) {
                log.Write(string.Format("{0}.Execute", GetType().FullName), ex.ToString());
                return DTSExecResult.Failure;
            }
        }
Exemple #14
0
 public void Initialize(TaskHost taskHost, IServiceProvider serviceProvider)
 {
     this.taskHost = taskHost;
       this.serviceProvider = serviceProvider;
       IDtsConnectionService connectionService = serviceProvider.GetService(typeof(IDtsConnectionService)) as IDtsConnectionService;
       this.connections = connectionService.GetConnections();
 }
        public override async Task<Connections> GetConnections()
        {
            if (isPrePairedDevice)
            {
                PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
            }

            try
            {
                PeerFinder.AllowBluetooth = true;
                PeerFinder.AllowWiFiDirect = true;
                PeerFinder.DisplayName = "Virtual Shields";
                PeerFinder.Role = PeerRole.Peer;
                if (!isPrePairedDevice)
                {
                    PeerFinder.Start();
                }

                var peers = await PeerFinder.FindAllPeersAsync();
                var connections = new Connections();
                foreach (var peer in peers)
                {
                    connections.Add(new Connection(peer.DisplayName, peer));
                }

                return connections;
            }
            catch (Exception)
            {
                return null;
            }

        }
Exemple #16
0
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            DTSExecResult execResult = DTSExecResult.Success;

            System.Windows.Forms.MessageBox.Show(this.displayText);

            return execResult;
        }
 public SqlEditorProxy(Connections.ConnectionData connData)
 {
   _conn = GetConnection(connData);
   this.ConnData = connData;
   _helper = new InnovatorAdmin.Editor.SqlEditorHelper(_conn);
   _outputHelper = new InnovatorAdmin.Editor.PlainTextEditorHelper();
   _conn.InfoMessage += _conn_InfoMessage;
 }
        public bool New(IWin32Window parentWindow, Connections connections, ConnectionManagerUIArgs connectionUIArg)
        {
            // コピー&ペーストされた場合でもNewメソッドが呼ばれるため、Fromを表示しないよう制御する必要がある。
            var clipboardService = (IDtsClipboardService)ServiceProvider.GetService(typeof(IDtsClipboardService));
            if (clipboardService != null && clipboardService.IsPasteActive) return true;

            return OpenEditor(parentWindow);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //load url arguments in variables
            string INSTANCE_NAME = @Request.QueryString["instance"];
            string CATALOG_NAME = Request.QueryString["catalog"];
            string CUBE_NAME = Request.QueryString["cube"];

            //Create Excel file name
            string ConnectionName = INSTANCE_NAME.Replace("\\","_") + "_" + CATALOG_NAME + "_" + CUBE_NAME;
            Response.Write(ConnectionName);

            //Create Workbook
            string filename = Server.MapPath(@"tmp/" + ConnectionName + ".xlsx");
            // Create a spreadsheet document by supplying the filepath.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());

            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);

            //Add a connectionPart to the workbookpart
            ConnectionsPart connectionsPart1 = workbookpart.AddNewPart<ConnectionsPart>();
            Connections connections1 = new Connections();
            Connection connection1 = new Connection() { Id = (UInt32Value)1U, KeepAlive = true, Name = ConnectionName, Type = (UInt32Value)5U, RefreshedVersion = 5, Background = true };
            DatabaseProperties databaseProperties1 = new DatabaseProperties() { Connection = "Provider=MSOLAP.4;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=" + CATALOG_NAME + ";Data Source=" + @INSTANCE_NAME + ";MDX Compatibility=1;Safety Options=2;MDX Missing Member Mode=Error", Command = CUBE_NAME, CommandType = (UInt32Value)1U };
            OlapProperties olapProperties1 = new OlapProperties() { SendLocale = true, RowDrillCount = (UInt32Value)1000U };
            connection1.Append(databaseProperties1);
            connection1.Append(olapProperties1);
            connections1.Append(connection1);
            connectionsPart1.Connections = connections1;

            //Add a PivottableCache part
            PivotTableCacheDefinitionPart pivotTableCacheDefinitionPart1 = workbookpart.AddNewPart<PivotTableCacheDefinitionPart>();
            PivotCacheDefinition pivotCacheDefinition1 = new PivotCacheDefinition() { SaveData = false, BackgroundQuery = true, SupportSubquery = true, SupportAdvancedDrill = true };
            pivotTableCacheDefinitionPart1.PivotCacheDefinition = pivotCacheDefinition1;

            workbookpart.Workbook.Save();
            // Close the document.
            spreadsheetDocument.Close();

            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=" + @"D:\MyBI\SSAS\SSAS2012_MyBI\tmp\test.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.WriteFile(Server.MapPath(@"tmp/" + ConnectionName + ".xlsx"));
            Response.End();
        }
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            ConnectionManager cSSH = getConnectionManager(connections, _SSHconnMgrName);
            List<KeyValuePair<string, string>> connParams = (List<KeyValuePair<string, string>>)cSSH.AcquireConnection(transaction);

            string host = connParams.Find(t => t.Key == "Host").Value;
            string username = connParams.Find(t => t.Key == "Username").Value;
            string password = connParams.Find(t => t.Key == "Password").Value;
            int port = Convert.ToInt32(connParams.Find(t => t.Key == "Port").Value);

            if (_operation == SSHFTPOperation.SendFiles)
            {
                ConnectionManager cSend = getConnectionManager(connections, _sendFilesSourceConnectionManagerName);
                string sourceFile = cSend.AcquireConnection(transaction).ToString();
                SshTransferProtocolBase sshCp;
                sshCp = new Sftp(host, username);
                sshCp.Password = password;
                string localFile = sourceFile;
                string remoteFile = getRemotePathAndFile(_sendFilesDestinationDirectory, Path.GetFileName(sourceFile));
                try
                {
                    sshCp.Connect();
                    sshCp.Put(localFile, remoteFile);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    sshCp.Close();
                }
            }
            if (_operation == SSHFTPOperation.ReceiveFiles)
            {
                ConnectionManager cReceive = getConnectionManager(connections, _receiveFilesDestinationConnectionManagerName);
                string destinationDirectory = cReceive.AcquireConnection(transaction).ToString();
                SshTransferProtocolBase sshCp;
                sshCp = new Sftp(host, username);
                sshCp.Password = password;
                try
                {
                    sshCp.Connect();
                    sshCp.Get(_receiveFilesSourceFile, destinationDirectory);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    sshCp.Close();
                }
            }

            return DTSExecResult.Success;
        }
Exemple #21
0
        public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
        {
            if (this._interval <= 0)
            {
                componentEvents.FireError(0, "", "Pause length must be greater than 0.", "", 0);
                return DTSExecResult.Failure;
            }

            return DTSExecResult.Success;
        }
 public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log) {
     return (
         !string.IsNullOrWhiteSpace(Host)
         && Port > 0
         && !string.IsNullOrWhiteSpace(Username)
         && !string.IsNullOrWhiteSpace(Password)
         && !string.IsNullOrWhiteSpace(SourcePath)
         && !string.IsNullOrWhiteSpace(TargetPath)
         ) ? DTSExecResult.Success : DTSExecResult.Failure;
 }
        public override async Task<Connections> GetConnections()
        {
            var remoteHostName = new HostName(remoteHost);
            var endpointList = await DatagramSocket.GetEndpointPairsAsync(remoteHostName, remoteService);
            var epair = endpointList.First();

            var connections = new Connections {new Connection("Server", epair)};

            return connections;
        }
 protected void WriteBadMessage(Connections.Connection conn)
 {
     //Write a bad message to the socket to force mongo to shut down our connection.
     BinaryWriter writer = new BinaryWriter(conn.GetStream());
     System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
     Byte[] msg = encoding.GetBytes("Goodbye MongoDB!");
     writer.Write(16 + msg.Length + 1);
     writer.Write(1);
     writer.Write(1);
     writer.Write(1001);
     writer.Write(msg);
     writer.Write((byte)0);
 }
        bool IDtsConnectionManagerUI.New(IWin32Window parentWindow, Connections connections, ConnectionManagerUIArgs connectionUIArg)
        {
            // If the user is pasting a new connection manager into this window, we can just return true.
            // We don't need to bring up the edit dialog ourselves
            IDtsClipboardService clipboardService = _serviceProvider.GetService(typeof(IDtsClipboardService)) as IDtsClipboardService;

            if ((clipboardService != null) && (clipboardService.IsPasteActive))
            {
                return true;
            }

            return EditSharePointCredentialConnection(parentWindow, connections);
        }
    public SharepointEditorProxy(Connections.ConnectionData connData)
    {
      _connData = connData;

      switch (_connData.Authentication)
      {
        case Connections.Authentication.Windows:
          _cred = CredentialCache.DefaultNetworkCredentials;
          break;
        case Connections.Authentication.Explicit:
          _cred = new NetworkCredential(_connData.UserName, _connData.Password);
          break;
      }
    }
Exemple #27
0
        public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
        {
            DTSExecResult execResult = base.Validate(connections, variableDispenser, componentEvents, log);
            if (execResult == DTSExecResult.Success)
            {
                // Validate task properties
                if (string.IsNullOrEmpty(displayText))
                {
                    componentEvents.FireWarning(1, this.GetType().Name, "Value required for DisplayText", string.Empty, 0);
                }
            }

            return execResult;
        }
        public bool New(IWin32Window parentWindow, 
            Connections connections, ConnectionManagerUIArgs connectionUIArg)
        {
            IDtsClipboardService clipboardService;
            clipboardService =
                (IDtsClipboardService)this._serviceProvider.GetService(typeof(IDtsClipboardService));

            // If connection manager has been copied and pasted, take no action.
            if (clipboardService != null)
            {
                if (clipboardService.IsPasteActive) { return true; }
            }
            return editSSHConnection(parentWindow);
        }
Exemple #29
0
        public bool Edit(IWin32Window parentWindow, Variables variables, Connections connections)
        {
            DialogResult dialogResult;

            try
            {
                MessageBox.Show(parentWindow, "The custom user interface is under construction in the release." + Environment.NewLine + "Please use the advanced editor for now.", NopConstants.COMPONENT_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(parentWindow, ex.ToString(), NopConstants.COMPONENT_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return false;
        }
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            ConnectionManager conn = getCurrentConnectionManager(connections);
            List<KeyValuePair<string, string>> connParams = (List<KeyValuePair<string, string>>)conn.AcquireConnection(transaction);

            string host = connParams.Find(t => t.Key == "Host").Value;
            string username = connParams.Find(t => t.Key == "Username").Value;
            string password = connParams.Find(t => t.Key == "Password").Value;
            int port = Convert.ToInt32(connParams.Find(t => t.Key == "Port").Value);

            SshExec exec = new SshExec(host, username);
            exec.Password = password;

            try
            {
                string stdOut = string.Empty;
                string stdErr = string.Empty;
                exec.Connect();
                StringReader sr = new StringReader(_commandText);
                while (true)
                {
                    string s = sr.ReadLine();
                    if (s != null && stdErr.Trim().Length == 0)
                    {
                        int res = exec.RunCommand(s, ref stdOut, ref stdErr);
                    }
                    else
                    {
                        if (stdErr.Trim().Length > 0)
                        {
                            fireError(componentEvents, stdErr);
                            return DTSExecResult.Failure;
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                fireError(componentEvents, ex.Message);
                return DTSExecResult.Failure;
            }
            finally
            {
                exec.Close();
            }
            return DTSExecResult.Success;
        }
        public string generateUniqNuo()
        {
            Connections con           = new Connections();
            string      strConnString = con.GetConnString();

            using (SqlConnection SqlCon = new SqlConnection(strConnString))
            {
                string uid = string.Empty;
                int    i   = 0;

                zzz : { }
                {
                    i = i + 1;
                    if (Label2.Text == "Two Wheeler Loan")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "TW" + uid;
                    }
                    else if (Label2.Text == "Gold Loan")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "G" + uid;
                    }
                    else if (Label2.Text == "Health Raksha")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "HR" + uid;
                    }
                    else if (Label2.Text == "Auto Loan")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "A" + uid;
                    }
                    else if (Label2.Text == "Personal Loan")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "PL" + uid;
                    }
                    else if (Label2.Text == "Home Loan")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "H" + uid;
                    }
                    else if (Label2.Text == "Life Insurance")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "LI" + uid;
                    }

                    else if (Label2.Text == "Card")
                    {
                        if (i < 10)
                        {
                            uid = "0000" + Convert.ToString(i);
                        }
                        else if (i < 100)
                        {
                            uid = "000" + Convert.ToString(i);
                        }
                        else if (i < 1000)
                        {
                            uid = "00" + Convert.ToString(i);
                        }
                        else if (i < 10000)
                        {
                            uid = "0" + Convert.ToString(i);
                        }
                        uid = "C" + uid;
                    }
                    ulong check;
                    using (SqlCommand cmd = new SqlCommand("SELECT COUNT(Product_id) FROM Product WHERE Product_id= '" + uid + "'", SqlCon))
                    {
                        SqlCon.Close();
                        SqlCon.Open();

                        check = Convert.ToUInt64(cmd.ExecuteScalar());

                        if (check > 0)
                        {
                            goto zzz;
                        }
                        return(uid);
                    }
                }
            }
        }
Exemple #32
0
 public void Load(MainWindow Owner)
 {
     this.connections = new Connections(Owner);
 }
Exemple #33
0
 public override Task OnReconnected()
 {
     Log.InfoFormat("Reconnected {0}", this.Context.ConnectionId);
     Connections.Push(this.Context.ConnectionId);
     return(base.OnReconnected());
 }
Exemple #34
0
 public int GetConnectionIndex(IWeightedGraphNode <T> connection)
 {
     return(Connections.IndexOf((GraphNode)connection));
 }
Exemple #35
0
        public void RunPowerPredictionExperiment()
        {
            const int inputBits = 300; /* without datetime component */ // 13420; /* with 4096 scalar bits */ // 10404 /* with 1024 bits */;

            Parameters p = Parameters.getAllDefaultParameters();

            p.Set(KEY.RANDOM, new ThreadSafeRandom(42));
            p.Set(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
            p.Set(KEY.INPUT_DIMENSIONS, new int[] { inputBits });
            p.Set(KEY.CELLS_PER_COLUMN, 10 /* 50 */);
            p.Set(KEY.GLOBAL_INHIBITION, true);
            p.Set(KEY.CONNECTED_PERMANENCE, 0.1);
            // N of 40 (40= 0.02*2048 columns) active cells required to activate the segment.
            p.setNumActiveColumnsPerInhArea(0.02 * 2048);
            // Activation threshold is 10 active cells of 40 cells in inhibition area.
            p.setActivationThreshold(10 /*15*/);
            p.setInhibitionRadius(15);
            p.Set(KEY.MAX_BOOST, 0.0);
            p.Set(KEY.DUTY_CYCLE_PERIOD, 100000);
            p.setActivationThreshold(10);
            p.setMaxNewSynapsesPerSegmentCount((int)(0.02 * 2048));
            p.setPermanenceIncrement(0.17);

            //p.Set(KEY.MAX_SYNAPSES_PER_SEGMENT, 32);
            //p.Set(KEY.MAX_SEGMENTS_PER_CELL, 128);
            //p.Set(KEY.MAX_NEW_SYNAPSE_COUNT, 200);

            //p.Set(KEY.POTENTIAL_RADIUS, 700);
            //p.Set(KEY.POTENTIAL_PCT, 0.5);
            //p.Set(KEY.NUM_ACTIVE_COLUMNS_PER_INH_AREA, 42);

            //p.Set(KEY.LOCAL_AREA_DENSITY, -1);

            CortexRegion region0 = new CortexRegion("1st Region");

            SpatialPoolerMT sp1 = new SpatialPoolerMT();
            TemporalMemory  tm1 = new TemporalMemory();
            var             mem = new Connections();

            p.apply(mem);
            sp1.Init(mem, UnitTestHelpers.GetMemory());
            tm1.Init(mem);

            Dictionary <string, object> settings = new Dictionary <string, object>();

            CortexLayer <object, object> layer1 = new CortexLayer <object, object>("L1");

            region0.AddLayer(layer1);
            layer1.HtmModules.Add("sp", sp1);

            HtmClassifier <double, ComputeCycle> cls = new HtmClassifier <double, ComputeCycle>();

            Stopwatch sw = new Stopwatch();

            sw.Start();
            Train(inputBits, layer1, cls, true); // New born mode.
            sw.Stop();

            Debug.WriteLine($"NewBorn stage duration: {sw.ElapsedMilliseconds / 1000} s");

            layer1.AddModule("tm", tm1);

            sw.Start();

            int hunderdAccCnt = 0;

            for (int i = 0; i < 1000; i++)
            {
                float acc = Train(inputBits, layer1, cls, false);

                Debug.WriteLine($"Accuracy = {acc}, Cycle = {i}");

                if (acc == 100.0)
                {
                    hunderdAccCnt++;
                }

                if (hunderdAccCnt >= 10)
                {
                    break;
                }
                //tm1.reset(mem);
            }

            if (hunderdAccCnt >= 10)
            {
                Debug.WriteLine($"EXPERIMENT SUCCESS. Accurracy 100% reached.");
            }
            else
            {
                Debug.WriteLine($"Experiment FAILED!. Accurracy 100% was not reached.");
            }

            cls.TraceState();

            sw.Stop();

            Debug.WriteLine($"Training duration: {sw.ElapsedMilliseconds / 1000} s");
        }
Exemple #36
0
        private void RefreshDeviceList()
        {
            //invoke the listAvailableDevicesAsync method of the correct Serial class. Since it is Async, we will wrap it in a Task and add a llambda to execute when finished
            Task <DeviceInformationCollection> task = null;

            if (ConnectionMethodComboBox.SelectedItem == null)
            {
                ConnectMessage.Text = "Select a connection method to continue.";
                return;
            }

            switch (ConnectionMethodComboBox.SelectedItem as String)
            {
            default:
            case "Bluetooth":
                ConnectionList.Visibility        = Visibility.Visible;
                NetworkConnectionGrid.Visibility = Visibility.Collapsed;

                //create a cancellation token which can be used to cancel a task
                cancelTokenSource = new CancellationTokenSource();
                cancelTokenSource.Token.Register(() => OnConnectionCancelled());

                task = BluetoothSerial.listAvailableDevicesAsync().AsTask <DeviceInformationCollection>(cancelTokenSource.Token);
                break;

            case "USB":
                ConnectionList.Visibility        = Visibility.Visible;
                NetworkConnectionGrid.Visibility = Visibility.Collapsed;

                //create a cancellation token which can be used to cancel a task
                cancelTokenSource = new CancellationTokenSource();
                cancelTokenSource.Token.Register(() => OnConnectionCancelled());

                task = UsbSerial.listAvailableDevicesAsync().AsTask <DeviceInformationCollection>(cancelTokenSource.Token);
                break;

            case "Network":
                ConnectionList.Visibility        = Visibility.Collapsed;
                NetworkConnectionGrid.Visibility = Visibility.Visible;
                ConnectMessage.Text = "Enter a host and port to connect";
                task = null;
                break;
            }

            if (task != null)
            {
                //store the returned DeviceInformation items when the task completes
                task.ContinueWith(listTask =>
                {
                    //store the result and populate the device list on the UI thread
                    var action = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(() =>
                    {
                        Connections connections = new Connections();

                        var result = listTask.Result;
                        if (result == null || result.Count == 0)
                        {
                            ConnectMessage.Text = "No items found.";
                        }
                        else
                        {
                            foreach (DeviceInformation device in result)
                            {
                                connections.Add(new Connection(device.Name, device));
                            }
                            ConnectMessage.Text = "Select an item and press \"Connect\" to connect.";
                        }

                        ConnectionList.ItemsSource = connections;
                    }));
                });
            }
        }
 public ICollection <TConnection> FindConnections <TConnection>() where TConnection : class, IConnection
 {
     return(Connections.OfType <TConnection>().ToList());
 }
Exemple #38
0
 /// <summary>
 /// Broadcast a message to all connected nodes, namely <see cref="Connections"/>.
 /// </summary>
 /// <param name="message">The message to be broadcasted.</param>
 private void BroadcastMessage(Message message)
 {
     Connections.Tell(message);
 }
        private void AddConnection()
        {
            var cn = new ConnectionString().Default();

            Connections.Add(new ConnectionStringViewModel(cn));
        }
    private static void ThrowsBecauseSecondIDNegative()
    {
        Connections c = new Connections();

        c.AddConnection(-1, 0);
    }
Exemple #41
0
 private void OnRelayDirectly(IInventory inventory)
 {
     Connections.Tell(new RemoteNode.Relay {
         Inventory = inventory
     });
 }
Exemple #42
0
        /// <summary>
        /// Load the available MetaSources defined in the repository
        /// </summary>
        public void LoadRepositoryMetaSources(Repository repository)
        {
            if (Loaded)
            {
                return;
            }

            foreach (var connection in Connections)
            {
                connection.IsEditable = true;
            }
            foreach (var table in MetaData.Tables)
            {
                table.IsEditable = true;
            }
            foreach (var link in MetaData.TableLinks)
            {
                link.IsEditable = true;
            }
            foreach (var join in MetaData.Joins)
            {
                join.IsEditable = true;
            }
            foreach (var itemEnum in MetaData.Enums)
            {
                itemEnum.IsEditable = true;
            }

            if (!string.IsNullOrEmpty(MetaSourceGUID))
            {
                MetaSource source = repository.Sources.FirstOrDefault(i => i.GUID == MetaSourceGUID);
                if (source != null)
                {
                    IsDefault      = source.IsDefault;
                    IsNoSQL        = source.IsNoSQL;
                    InitScript     = source.InitScript;
                    MetaSourceName = source.Name;
                    foreach (var item in source.Connections)
                    {
                        item.IsEditable = false;
                        Connections.Add(item);
                    }
                    foreach (var item in source.MetaData.Tables)
                    {
                        item.IsEditable = false;
                        MetaData.Tables.Add(item);
                    }
                    foreach (var item in source.MetaData.TableLinks)
                    {
                        item.IsEditable = false;
                        MetaData.TableLinks.Add(item);
                    }
                    foreach (var item in source.MetaData.Joins)
                    {
                        item.IsEditable = false;
                        MetaData.Joins.Add(item);
                    }
                    foreach (var item in source.MetaData.Enums)
                    {
                        item.IsEditable = false;
                        MetaData.Enums.Add(item);
                    }

                    PreSQL  = source.PreSQL;
                    PostSQL = source.PostSQL;

                    IgnorePrePostError = source.IgnorePrePostError;
                }
                else
                {
                    Report.LoadErrors += string.Format("Unable to find repository source for '{0}' (GUID {1}). Check the data source files in the repository folder.\r\n", Name, MetaSourceGUID);
                }
            }

            if (Connections.Count == 0)
            {
                Connections.Add(MetaConnection.Create(this));
                ConnectionGUID = Connections[0].GUID;
            }

            Loaded = true;
        }
 public override void InitializeTask(Connections connections, VariableDispenser variableDispenser, IDTSInfoEvents events, IDTSLogging log, EventInfos eventInfos, LogEntryInfos logEntryInfos, ObjectReferenceTracker refTracker)
 {
     _connections = connections;
     base.InitializeTask(connections, variableDispenser, events, log, eventInfos, logEntryInfos, refTracker);
 }
        private void RunSpStabilityExperiment(double maxBoost, double minOverlapCycles, int inputBits, Parameters p, EncoderBase encoder, List <double> inputValues)
        {
            string path = nameof(RunSpStabilityExperiment);

            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
            }

            Directory.CreateDirectory(path);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            bool learn = true;

            CortexNetwork       net     = new CortexNetwork("my cortex");
            List <CortexRegion> regions = new List <CortexRegion>();
            CortexRegion        region0 = new CortexRegion("1st Region");

            regions.Add(region0);

            var mem = new Connections();

            bool isInStableState = false;

            HomeostaticPlasticityController hpa = new HomeostaticPlasticityController(mem, inputValues.Count * 30, (isStable, numPatterns, actColAvg, seenInputs) =>
            {
                Assert.IsTrue(numPatterns == inputValues.Count);

                // Event should only be fired when entering the stable state.
                // Ideal SP should never enter unstable state after stable state.
                if (isStable == false)
                {
                    isInStableState = false;
                    Debug.WriteLine($"INSTABLE!: Patterns: {numPatterns}, Inputs: {seenInputs}, iteration: {seenInputs / numPatterns}");
                }
                else
                {
                    //Assert.IsTrue(isStable);

                    isInStableState = true;
                    Debug.WriteLine($"STABLE: Patterns: {numPatterns}, Inputs: {seenInputs}, iteration: {seenInputs / numPatterns}");
                }
            }, numOfCyclesToWaitOnChange: 50, requiredSimilarityThreshold: 0.975);

            SpatialPooler sp = new SpatialPooler(hpa);

            p.apply(mem);
            sp.Init(mem, UnitTestHelpers.GetMemory());

            CortexLayer <object, object> layer1 = new CortexLayer <object, object>("L1");

            region0.AddLayer(layer1);
            layer1.HtmModules.Add("encoder", encoder);
            layer1.HtmModules.Add("sp", sp);

            HtmClassifier <double, ComputeCycle> cls = new HtmClassifier <double, ComputeCycle>();

            double[] inputs = inputValues.ToArray();
            Dictionary <double, List <string[]> > boostedOverlaps = new Dictionary <double, List <string[]> >();
            Dictionary <double, int[]>            prevActiveCols  = new Dictionary <double, int[]>();
            Dictionary <double, double>           prevSimilarity  = new Dictionary <double, double>();

            foreach (var input in inputs)
            {
                prevSimilarity.Add(input, 0.0);
                prevActiveCols.Add(input, new int[0]);
            }

            int maxSPLearningCycles = 2000;

            List <(double Element, (int Cycle, double Similarity)[] Oscilations)> oscilationResult = new List <(double Element, (int Cycle, double Similarity)[] Oscilations)>();
Exemple #45
0
 public void Save()
 {
     Connections.Sort((x, y) => x.Key.CompareTo(y.Key));
     CodeFileHelper.CheckoutAndWrite(GeneratorConfig.GetConfigurationFilePath(),
                                     JSON.StringifyIndented(this), false);
 }
 public void AddConnection(Location location) => Connections.Add(location);
Exemple #47
0
 public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
 {
     return((
                connections.Contains(ConnectionName)
                ) ? DTSExecResult.Success : DTSExecResult.Failure);
 }
 public void RemoveConnection(Location location) => Connections.Remove(location);
Exemple #49
0
 public override Task <WebSocketConnection> GetConnectionByIdAsync(string connId)
 {
     return(Task.FromResult <WebSocketConnection>(Connections.FirstOrDefault(m => ((ServerConnection)m).ConnectionId == connId)));
 }
Exemple #50
0
        /// <summary>
        /// Shuts down the server.
        /// </summary>
        internal static void Exit()
        {
            var method = MethodBase.GetCurrentMethod();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Shutting down...");

            Debugger.Info("Server is shutting down...");

            Task task = Task.Run(() =>
            {
                if (Connections.Count > 0)
                {
                    Connections.ForEach(connection =>
                    {
                        if (connection != null && connection.State >= State.LoggedIn)
                        {
                            new MaintenanceInboundMessage(connection).Send();
                            new DisconnectedMessage(connection).Send();
                        }
                    });

                    Debugger.Info("Warned every player about the maintenance.", method);
                }
            });

            int timeout = 1000;

            bool saveAvatars   = false;
            bool saveAlliances = false;

            if (Avatars.Count > 0)
            {
                saveAvatars = true;
                timeout    += 500;
            }

            if (Alliances.Count > 0)
            {
                saveAlliances = true;
                timeout      += 500;
            }

            if (saveAvatars || saveAlliances)
            {
                Task pTask = new Task(() => Avatars.Save());
                Task cTask = new Task(() => Alliances.Save());

                if (saveAvatars)
                {
                    pTask.Start();
                }
                if (saveAlliances)
                {
                    cTask.Start();
                }

                if (saveAvatars)
                {
                    pTask.Wait();
                }
                if (saveAlliances)
                {
                    cTask.Wait();
                }
            }
            else
            {
                Debugger.Info("Server has nothing to save, shutting down immediately.");
            }

            task.Wait(5000);

            Thread.Sleep(timeout);
            Environment.Exit(0);
        }
Exemple #51
0
 public override void Add(GraphNode item)
 {
     Connections.Add(item);
     Weights.Add(InfinityWeight);
 }
Exemple #52
0
 /// <summary>
 /// 注销
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public bool UnRegister(ConnectionContext context)
 {
     return(Connections.TryRemove(context.Id, out _));
 }
        //submit payment
        protected void btnSubmitPrivatePayment_Click(object sender, EventArgs e)
        {
            decimal outstandingFees = Convert.ToDecimal(lblOutstandingFees.Text);
            decimal payingFees      = Convert.ToInt32(txtAmountToPay.Text);


            using (SqlConnection conn = Connections.ApplicationConnection())
            {
                //new value to update db outstand fees

                if (txtCardNumber.Text.Length == 16 && txtExpiryMonth.Text.Length == 2 && txtExpiryYear.Text.Length == 2 & txtCvCode.Text.Length == 3)
                {
                    decimal newOutstandingValue = Convert.ToDecimal(lblOutstandingFees.Text) - Convert.ToDecimal(txtAmountToPay.Text);
                    lblPaymentError.Text = "";

                    if (newOutstandingValue < 0)
                    {
                        lblPaymentError.Text = "Please Enter A Payment Amout Greater Than The Students Outstanding Fees";
                    }

                    try
                    {
                        //compare dates for expired cards
                        int    currentMonth = DateTime.Now.Month;
                        string year         = DateTime.Now.ToString("yy");
                        int    currentyear  = Convert.ToInt32(year);

                        if (Convert.ToInt32(txtExpiryMonth.Text) < currentMonth || Convert.ToInt32(txtExpiryYear.Text) < currentyear)
                        {
                            lblPaymentError.Text = "It Apperas The Card Details You Have Entered Are Expired";
                        }
                        else
                        {
                            if (newOutstandingValue == Convert.ToDecimal(0.00))
                            {
                                //sets fully paid

                                //update outstanding fees
                                SqlCommand cmdUpdateOutstandigFees = new SqlCommand("UPDATE tbl_outstandingFees SET OutstandingFees = @fees WHERE StudentId = @studentId", conn);
                                cmdUpdateOutstandigFees.Parameters.AddWithValue("@fees", Convert.ToDecimal(0));
                                cmdUpdateOutstandigFees.Parameters.AddWithValue("@studentId", Convert.ToInt32(Session["s_studentId"]));
                                cmdUpdateOutstandigFees.ExecuteNonQuery();

                                SqlCommand cmdSubmitPrivateFinancePayment = new SqlCommand("UPDATE tbl_studentUser SET FeesPaid = @feesPaid WHERE StudentId = @studentId", conn);
                                cmdSubmitPrivateFinancePayment.Parameters.AddWithValue("@feesPaid", Convert.ToInt32(1));
                                cmdSubmitPrivateFinancePayment.Parameters.AddWithValue("@studentId", Convert.ToInt32(Session["s_studentId"]));
                                cmdSubmitPrivateFinancePayment.ExecuteNonQuery();
                            }
                            else
                            {
                                //updates outstandg fees to new value
                                SqlCommand cmdUpdateOutstandigFees = new SqlCommand("UPDATE tbl_outstandingFees SET OutstandingFees = @fees WHERE StudentId = @studentId", conn);
                                cmdUpdateOutstandigFees.Parameters.AddWithValue("@fees", Convert.ToDecimal(newOutstandingValue));
                                cmdUpdateOutstandigFees.Parameters.AddWithValue("@studentId", Convert.ToInt32(Session["s_studentId"]));
                                cmdUpdateOutstandigFees.ExecuteNonQuery();

                                SqlCommand cmdSubmitPrivateFinancePayment = new SqlCommand("UPDATE tbl_studentUser SET FeesPaid = @feesPaid WHERE StudentId = @studentId", conn);
                                cmdSubmitPrivateFinancePayment.Parameters.AddWithValue("@feesPaid", Convert.ToInt32(2));
                                cmdSubmitPrivateFinancePayment.Parameters.AddWithValue("@studentId", Convert.ToInt32(Session["s_studentId"]));
                                cmdSubmitPrivateFinancePayment.ExecuteNonQuery();
                            }

                            //insert into payment records
                            SqlCommand cmdSubmitPaymentRecord = new SqlCommand("INSERT INTO tbl_paymentRecord (Date,Amount) Values(@date,@amount)");
                            cmdSubmitPaymentRecord.Parameters.AddWithValue("@date", Convert.ToDateTime(DateTime.Now.ToShortDateString()));
                            cmdSubmitPaymentRecord.Parameters.AddWithValue("@amount", Convert.ToDecimal(newOutstandingValue));
                            cmdSubmitPaymentRecord.ExecuteNonQuery();

                            lblSuccess.Text = "Success, Student Fee Details Have Been Updated";

                            HideAllPanels();
                            pnlStudentList.Visible = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
                else
                {
                    lblPaymentError.Text = "Please Enter Valid Credit Card Information";
                }
            }
        }
 /// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
 public scg::IEnumerator <Connection> GetEnumerator() => Connections.GetEnumerator();
 public dynamic this[string name] => Connections.Group(name);
Exemple #56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SQLHelper"/> class.
 /// </summary>
 /// <param name="configuration">The configuration object.</param>
 /// <param name="factory">The factory.</param>
 /// <param name="database">The database.</param>
 public SQLHelper(IConfiguration configuration, DbProviderFactory?factory = null, string database = "Default")
     : this(Connections.ContainsKey(database) ? Connections[database] : new Connection(configuration, factory ?? SqlClientFactory.Instance, database))
 {
 }
        public virtual async Task <TSearchResult> SearchAsync(TSearchParameters parameters)
        {
            // TODO:: Check
            //var connectionPool = new SniffingConnectionPool(Connections);
            //var settings = new ConnectionSettings(connectionPool)
            //    .DefaultIndex(IndexName)
            //    .DefaultFieldNameInferrer(x => x.ToLower())
            //    .DisableDirectStreaming();
            //var client = new ElasticClient(settings);

            var uri      = Connections.FirstOrDefault();
            var settings = new ConnectionSettings(uri)
                           .DefaultIndex(IndexName)
                           .DefaultFieldNameInferrer(x => x.ToLower())
                           .DisableDirectStreaming();
            var client = new ElasticClient(settings);

            var result = await client.SearchAsync <TEntity>(s => SearchProvider.BuildRequest(s, parameters));

            if (result?.CallDetails?.RequestBodyInBytes != null)
            {
                var rawRequest = Encoding.UTF8.GetString(result.CallDetails.RequestBodyInBytes, 0, result.CallDetails.RequestBodyInBytes.Length);
                // TODO:: Log request
            }

            if (!result.IsValid)
            {
                throw new Exception(result.ToString());
                return(null);
            }

            var searchResult = new TSearchResult {
                Total      = result.Total,
                PageNumber = SearchProvider.GetPageNumber(parameters),
                PageSize   = SearchProvider.GetPageSize(parameters),
                Entities   = result.Documents.ToList(),
                Filters    = new List <IFilter>()
            };

            foreach (var item in result.Aggregations)
            {
                var filter = SearchProvider.SelectFilter(item.Key);
                if (filter is IElasticFilter)
                {
                    var bucket = item.Value as BucketAggregate;
                    if (bucket == null)
                    {
                        filter = null;
                    }
                    else
                    {
                        ((IElasticFilter)filter).BuildOptions(bucket);
                    }
                }
                if (filter != null)
                {
                    filter.ParameterNames = SearchProvider.MapParameterNames(item.Key);
                    filter.DisplayText    = item.Key;
                    SearchProvider.ActivateFilterOption(filter, parameters);
                    searchResult.Filters.Add(filter);
                }
            }

            return(searchResult);
        }
Exemple #58
0
        public RepositoryPublishViewModel(
            IRepositoryPublishService repositoryPublishService,
            INotificationService notificationService,
            IConnectionManager connectionManager,
            IModelServiceFactory modelServiceFactory,
            IUsageTracker usageTracker)
        {
            Guard.ArgumentNotNull(repositoryPublishService, nameof(repositoryPublishService));
            Guard.ArgumentNotNull(notificationService, nameof(notificationService));
            Guard.ArgumentNotNull(connectionManager, nameof(connectionManager));
            Guard.ArgumentNotNull(usageTracker, nameof(usageTracker));
            Guard.ArgumentNotNull(modelServiceFactory, nameof(modelServiceFactory));

            this.notificationService = notificationService;
            this.usageTracker        = usageTracker;
            this.modelServiceFactory = modelServiceFactory;

            title = this.WhenAny(
                x => x.SelectedConnection,
                x => x.Value != null ?
                string.Format(CultureInfo.CurrentCulture, Resources.PublishToTitle, x.Value.HostAddress.Title) :
                Resources.PublishTitle
                )
                    .ToProperty(this, x => x.Title);

            Connections = connectionManager.Connections;
            this.repositoryPublishService = repositoryPublishService;

            if (Connections.Any())
            {
                SelectedConnection = Connections.FirstOrDefault(x => x.HostAddress.IsGitHubDotCom()) ?? Connections[0];
            }

            accounts = this.WhenAnyValue(x => x.SelectedConnection)
                       .Where(x => x != null)
                       .SelectMany(async c => (await modelServiceFactory.CreateAsync(c)).GetAccounts())
                       .Switch()
                       .ObserveOn(RxApp.MainThreadScheduler)
                       .ToProperty(this, x => x.Accounts, initialValue: new ReadOnlyCollection <IAccount>(Array.Empty <IAccount>()));

            this.WhenAny(x => x.Accounts, x => x.Value)
            .WhereNotNull()
            .Where(accts => accts.Any())
            .Subscribe(accts => {
                var selectedAccount = accts.FirstOrDefault();
                if (selectedAccount != null)
                {
                    SelectedAccount = accts.FirstOrDefault();
                }
            });

            isHostComboBoxVisible = this.WhenAny(x => x.Connections, x => x.Value)
                                    .WhereNotNull()
                                    .Select(h => h.Count > 1)
                                    .ToProperty(this, x => x.IsHostComboBoxVisible);

            InitializeValidation();

            PublishRepository = InitializePublishRepositoryCommand();
            PublishRepository.IsExecuting.Subscribe(x => IsBusy = x);

            var defaultRepositoryName = repositoryPublishService.LocalRepositoryName;

            if (!string.IsNullOrEmpty(defaultRepositoryName))
            {
                RepositoryName = defaultRepositoryName;
            }

            this.WhenAny(x => x.SelectedConnection, x => x.SelectedAccount,
                         (a, b) => true)
            .Where(x => RepositoryNameValidator.ValidationResult != null && SafeRepositoryNameWarningValidator.ValidationResult != null)
            .Subscribe(async _ =>
            {
                var name       = RepositoryName;
                RepositoryName = null;
                await RepositoryNameValidator.ResetAsync();
                await SafeRepositoryNameWarningValidator.ResetAsync();
                RepositoryName = name;
            });
        }
        private void DefineRegisters()
        {
            Registers.Output.Define(this)
            .WithValueField(0, 32, out output,
                            writeCallback: (_, val) => RefreshConnectionsState(),
                            valueProviderCallback: _ => BitHelper.GetValueFromBitsArray(Connections.Where(x => x.Key >= 0).OrderBy(x => x.Key).Select(x => x.Value.IsSet)))
            ;

            Registers.OutputEnable.Define(this)
            .WithValueField(0, 32, out outputEnable,
                            writeCallback: (_, val) => RefreshConnectionsState())
            ;
        }
Exemple #60
0
 private void OnSendDirectly(IInventory inventory)
 {
     Connections.Tell(inventory);
 }