Example #1
0
        /// <summary>
        /// BeginSearcherAsync will kickoff the async search.
        /// </summary>
        /// <param name="startPath">Folder Path where we want to start search</param>
        /// <param name="extension">filetype to search</param>
        /// <param name="includeTempFiles">Include Temporary files or not</param>
        /// <param name="Log">Logger to log the issue</param>
        /// <param name="callbackFunc">function to call once done</param>
        /// <returns> return the handle</returns>
        private IAsyncResult localBeginSearcherAsync(string startPath, string extension, bool includeTempFiles, Logger Log, AsyncCallback callbackFunc)
        {
            AsyncSearcher searcher = SearchDuplicate;

            quitNow = false;
            IAsyncResult ar = searcher.BeginInvoke(startPath, extension, includeTempFiles, Log, localCallbackMethod, null);

            return(ar);
        }
Example #2
0
 /// <summary>
 /// Creates a new instance of the <see cref="Measurements"/> class.
 /// </summary>
 /// <param name="autosave">Determines whether the current item is saved automatically when a new item is selected.</param>
 public Measurements(bool autosave = true)
     : base(0, autosave)
 {
     m_historianLookupList      = Historian.GetLookupList(null, isOptional: true);
     m_signalTypeLookupList     = SignalType.GetLookupList(null);
     m_searcher                 = new AsyncSearcher <DataModels.Measurement>();
     m_searcher.MatchesFound   += Searcher_MatchesFound;
     m_searcher.SearchComplete += Searcher_SearchComplete;
 }
Example #3
0
        static AsyncSearcher CreateSearcher(LdapConnection connection)
        {
            AsyncSearcher searcher = new AsyncSearcher(connection);

            //assign some handlers for our events
            searcher.PageCompleted   += new EventHandler <AsyncEventArgs>(searcher_PageCompleted);
            searcher.SearchCompleted += new EventHandler <AsyncEventArgs>(searcher_SearchCompleted);

            return(searcher);
        }
Example #4
0
        /// <summary>
        /// Creates a new instance of the <see cref="Measurements"/> class.
        /// </summary>
        /// <param name="deviceID">The ID of the device that the current measurement is associated with..</param>
        /// <param name="itemsPerPage">The number of measurements to display on each page of the data grid.</param>
        /// <param name="autosave">Determines whether the current item is saved automatically when a new item is selected.</param>
        public Measurements(int deviceID, int itemsPerPage, bool autosave = true)
            : base(0, autosave)     // Set ItemsPerPage to zero to avoid load() in the base class.
        {
            m_deviceID   = deviceID;
            ItemsPerPage = itemsPerPage;

            m_historianLookupList      = Historian.GetLookupList(null, isOptional: true);
            m_signalTypeLookupList     = SignalType.GetLookupList(null);
            m_searcher                 = new AsyncSearcher <DataModels.Measurement>();
            m_searcher.MatchesFound   += Searcher_MatchesFound;
            m_searcher.SearchComplete += Searcher_SearchComplete;

            Load();
        }
Example #5
0
        public static int Main(string[] args)
        {
            try     {
                Version v = Assembly.GetExecutingAssembly().GetName().Version;
                //fill list of arguments
                _arguments = new List <string>();

                foreach (string arg in args)
                {
                    _arguments.Add(arg.Replace("\"", string.Empty));
                }

                // some fancy window title
                Console.Title = string.Format("LDAP2CSV v{0}.{1}.{2}", v.Major, v.Minor, v.Build);

                //want to create a lcv file? exit after job is done
                if (_arguments.Contains("-c"))
                {
                    Crypto.Protect(_arguments[_arguments.IndexOf("-c") + 1]);
                    return(0);
                }

                //messing around with parameters? dont try
                if (_arguments.Contains("-u") && !_arguments.Contains("-p"))
                {
                    throw new ArgumentException("-u and -p parameter must be specified in conjuction");
                }

                // check existance of desirend amount of parameters at least: server:port/rootdn
                if (_arguments.Count < 1)
                {
                    Console.WriteLine(
                        "LDAP2CSV usage:\n" +
                        "\n" +
                        "ldap2csv.exe LDAP://10.0.0.4:389/ou=people,dc=example,dc=de \n -u username -p password -f (&(ou=people)) -a sn,givenName,ou " +
                        "\n -o \"D:\\Path\\To\\Destination.csv -e UTF8 -s ;\"\n" +
                        "\n" +
                        "optional parmeter -a: ldap attributes\n" +
                        "supported attributes are: comma seperated list of attributes\n" +
                        "Hint: If omitted, attribute will be set to wildcard \"*\"\n" +
                        "usage: -a sn,givenName\n" +
                        "\n" +
                        "optional parmeter -f: ldap search filter\n" +
                        "supported attributes are: standard ldap query\n" +
                        "Hint: If omitted, filter is set to \"objectClass=*\"\n" +
                        "usage: -f ou=people\n" +
                        "\n" +
                        "optional parmeter -u: username\n" +
                        "supported attributes are: ldap username\n" +
                        "Hint: refer -c and -C parameter for encrypted credentials\n" +
                        "Hint: Anonymous Login is used if -u, -p and -C are omitted\n" +
                        "usage: -u cn=admin,dc=example,dc=de\n" +
                        "\n" +
                        "optional parmeter -p: plain password\n" +
                        "supported attributes are: ldap userpassword\n" +
                        "Hint: -u parameter is mandatory if -p should be used \n" +
                        "Hint: refer -c and -C parameter for encrypted credentials\n" +
                        "usage: -p password\n" +
                        "\n" +
                        "optional parmeter -e: encoding\n" +
                        "supported attributes are: UTF8, ASCII(=ANSI) and Unicode\n" +
                        "Hint: If omitted, encoding remain system default\n" +
                        "usage: -e UTF8\n" +
                        "\n" +
                        "optional parmeter -s: csv seperator char\n" +
                        "supported attributes: maybe all ASCII characters" +
                        "Hint: If omitted, comma will be used as seperator\n" +
                        "usage: -s ;\n" +
                        "\n" +
                        "optional parmeter -v: ldap protocol version\n" +
                        "supported attributes: 2, 3\n" +
                        "Hint: If omitted, version 3 is assumed\n" +
                        "usage: -v 2\n" +
                        "\n" +
                        "optional parmeter -ssl: use ssl encryption\n" +
                        "supported attributes: none\n" +
                        "Hint: If omitted, basic authentication will be used\n" +
                        "usage: -ssl\n" +
                        "\n" +
                        "optional parmeter -tls: use tls encryption\n" +
                        "supported attributes: none\n" +
                        "Hint: If omitted, basic authentication will be used\n" +
                        "usage: -tls\n" +
                        "\n" +
                        "optional parmeter -k: use kerberos encryption\n" +
                        "supported attributes: none\n" +
                        "Hint: If omitted, basic authentication will be used\n" +
                        "usage: -k\n" +
                        "\n" +
                        "optional parmeter -t: timeout in minutes before a connection\n" +
                        "or a ldap query will raise a timeout exception\n" +
                        "supported attributes: 1 - n\n" +
                        "Hint: If omitted, timeout will be set to 10 minutes\n" +
                        "usage: -t 5\n" +
                        "\n" +
                        "optional parameter -c: encryption of credentials\n" +
                        "this will create an encrypted \"cred.lcv\" in\n" +
                        "the root directory of ldap2csv.exe where the credentials\n" +
                        "will be stored safely. May need elevated privileges \"Run As Administrator\"\n" +
                        "supported attributes: \"username|password\"\n" +
                        "Hint: Be aware to use the | character (pipe) to seperate user and password.\n" +
                        "Hint: Be aware to set the attribute in quotes.\n" +
                        "Hint: To use the created credential file see \"-C\" parameter.\n" +
                        "usage: ldap2csv.exe -c \"username|password\"\n" +
                        "\n" +
                        "optional paremeter -C: use encrypted credential file\n" +
                        "this will tell ldap2csv.exe to search for the \"cred.lcv\" file\n" +
                        "created with the -c parameter above.\n" +
                        "supported attributes: none\n" +
                        "usage: ldap2csv.exe LDAP://10.0.0.4:389/ou=people,dc=example,dc=de -C -f (&(ou=people))\n" +
                        "-a sn,givenName,ou -o D:\\Path\\To\\Destination.csv\\\n" +
                        "\nImportant: cred.lcv file is bound to the environment where it was created and could not be transferred between different machines"
                        );

                    Console.Write(
                        "\n" +
                        "Press any key to exit . . . "
                        );

                    Console.ReadKey(true);

                    return(0);
                }

                else
                {
                    try     {
                        //extract server and dn from ldap path attribute
                        string dn = _arguments[0].ToUpper().Replace("LDAP://", string.Empty)
                                    .Replace("LDAPS://", string.Empty)
                                    .Remove(0, _arguments[0].ToUpper()
                                            .Replace("LDAP://", string.Empty).Replace("LDAPS://", string.Empty)
                                            .IndexOf('/') + 1)
                                    .ToLower();

                        string server = _arguments[0].ToUpper().Replace("LDAP://", string.Empty)
                                        .Replace("LDAPS://", string.Empty)
                                        .Remove(_arguments[0].ToUpper()
                                                .Replace("LDAP://", string.Empty).Replace("LDAPS://", string.Empty)
                                                .IndexOf('/'), dn.Length + 1)
                                        .ToLower();

                        LdapDirectoryIdentifier ldapDir = new LdapDirectoryIdentifier(server);

                        //prepare output directory if -o parameter was supplied
                        if (_arguments.Contains("-o"))
                        {
                            // the argument right after the "-o" argument should be an existing directory as this will be used for the output file. create if not exists
                            if (!Directory.GetParent(_arguments[_arguments.IndexOf("-o") + 1]).Exists)
                            {
                                Directory.CreateDirectory(Directory.GetParent(_arguments[_arguments.IndexOf("-o") + 1]).ToString());
                            }

                            // try to remove previous csv file if it exists
                            if (File.Exists(_arguments[_arguments.IndexOf("-o") + 1]))
                            {
                                try     {
                                    File.Delete(_arguments[_arguments.IndexOf("-o") + 1]);
                                }
                                catch (Exception ex) {
                                    LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", ex.Message, (ex.InnerException != null) ? ex.InnerException.Message : string.Empty));
                                }
                            }
                        }

                        using (LdapConnection ldapConnection = CreateConnection(ldapDir))
                        {
                            //use ssl?
                            ldapConnection.SessionOptions.SecureSocketLayer = _arguments.Contains("-ssl") ? true : false;

                            //use tls?
                            if (_arguments.Contains("-tls") && !_arguments.Contains("-ssl"))
                            {
                                ldapConnection.SessionOptions.StartTransportLayerSecurity(null);
                            }

                            //protocol version specified? use version 3 if not
                            ldapConnection.SessionOptions.ProtocolVersion = _arguments.Contains("-v") ? int.Parse(_arguments[_arguments.IndexOf("-v") + 1]) : 3;

                            //do not chase referral
                            ldapConnection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;

                            //You may need to try different types of Authentication depending on the setup
                            ldapConnection.AuthType = (_arguments.Contains("-u") || _arguments.Contains("-C")) ? AuthType.Basic : AuthType.Anonymous;

                            //use kerberos?
                            if (_arguments.Contains("-k"))
                            {
                                ldapConnection.AuthType = AuthType.Kerberos;
                                ldapConnection.SessionOptions.Sealing = true;
                                ldapConnection.SessionOptions.Signing = true;
                            }

                            //set or get timeout setting
                            ldapConnection.Timeout = new TimeSpan(0, _arguments.Contains("-t") ? int.Parse(_arguments[_arguments.IndexOf("-t") + 1]) : 10, 0);

                            //use credentials from encrypted credential file?
                            if (_arguments.Contains("-C"))
                            {
                                try{
                                    //split back to user|pwd
                                    string[] credentials = Crypto.Unprotect().Split('|');

                                    NetworkCredential cred =
                                        new NetworkCredential(credentials[0], credentials[1]);

                                    //ldap connect
                                    ldapConnection.Bind(cred);
                                }
                                catch (Exception e) {
                                    LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", e.Message, (e.InnerException != null) ? e.InnerException.Message : string.Empty));
                                    ldapConnection.Dispose();
                                    return(1);
                                }
                            }

                            //use plain authentication?
                            else if (_arguments.Contains("-u") && _arguments.Contains("-p"))
                            {
                                NetworkCredential cred =
                                    new NetworkCredential(_arguments[_arguments.IndexOf("-u") + 1], _arguments[_arguments.IndexOf("-p") + 1]);

                                ldapConnection.Bind(cred);
                            }

                            //or try anonymously?
                            else
                            {
                                NetworkCredential cred =
                                    new NetworkCredential();
                                cred.Password = null;
                                cred.UserName = null;

                                ldapConnection.Bind(cred);
                            }

                            AsyncSearcher searcher = CreateSearcher(ldapConnection);

                            //this call is asynch, so we need to keep this main
                            //thread alive in order to see anything
                            //we can use the same searcher for multiple requests - we just have to track which one
                            //is which, so we can interpret the results later in our events.
                            attr = _arguments.Contains("-a") ? _arguments[_arguments.IndexOf("-a") + 1].Split(new char[] { ',', ';' }) : new string[] { "*" };

                            _guid = searcher.BeginPagedSearch(
                                //set searchbase
                                string.IsNullOrWhiteSpace(dn) ? "*" : dn,
                                //set filter
                                _arguments.Contains("-f") ? _arguments[_arguments.IndexOf("-f") + 1] : "(objectClass=*)",
                                //set attributes
                                attr,
                                150);

                            //we will use a reset event to signal when we are done (using Sleep() on
                            //current thread would work too...)
                            _resetEvent.WaitOne();                             //wait for signal;
                        }
                    }
                    catch (Exception e)     {
                        LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", e.Message, (e.InnerException != null) ? e.InnerException.Message : string.Empty));
                        return(1);
                    }
                }
                return(0);
            }

            catch (Exception e)     {
                LogWriter.CreateLogEntry(string.Format("ERROR:{0} {1}", e.Message, (e.InnerException != null) ? e.InnerException.Message : string.Empty));
                return(1);
            }
        }
Example #6
0
		Task<HexBufferSpan?> StartSearchAsync(AsyncSearcher asyncSearcher) =>
			Task.Run(() => asyncSearcher.Find(), asyncSearcher.CancellationToken);
Example #7
0
		IAsyncSearcher FindAsync(SearchOptions searchOptions, Action<FindAsyncResult, HexBufferSpan?> onCompleted) {
			var hexSearchService = hexSearchServiceFactory.TryCreateHexSearchService(searchOptions.DataKind, searchOptions.SearchString, (searchOptions.FindOptions & OurFindOptions.MatchCase) != 0, searchOptions.IsBigEndian);
			if (hexSearchService == null) {
				onCompleted(FindAsyncResult.InvalidSearchOptions, null);
				return null;
			}
			var searcher = new AsyncSearcher(hexSearchService, searchOptions);
			searcher.OnCompleted += onCompleted;
			asyncSearchers.Add(searcher);
			Searching = asyncSearchers.Count != 0;
			StartSearchAsync(searcher).ContinueWith(t => {
				var searcherWasCanceled = searcher.Canceled;
				searcher.CancelAndDispose();
				bool wasInList = asyncSearchers.Remove(searcher);
				Searching = asyncSearchers.Count != 0;
				var ex = t.Exception;
				Debug.Assert(ex == null);
				if (wasInList && !searcherWasCanceled && !t.IsCanceled && !t.IsFaulted)
					searcher.RaiseCompleted(FindAsyncResult.HasResult, t.Result);
				else
					searcher.RaiseCompleted(FindAsyncResult.Other, null);
			}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
			return searcher;
		}