示例#1
0
        /// <inheritdoc/>
        public override string ToString()
        {
            var builder = new List <string>();

            var substring = ResourceTypeFilter?.GetFilterString();

            if (!string.IsNullOrWhiteSpace(substring))
            {
                builder.Add(substring);
            }

            substring = SubstringFilter?.GetFilterString();
            if (!string.IsNullOrWhiteSpace(substring))
            {
                builder.Add(substring);
            }

            substring = TagFilter?.GetFilterString();
            if (!string.IsNullOrWhiteSpace(substring))
            {
                builder.Add(substring);
            }

            return($"{string.Join(" and ", builder)}");
        }
示例#2
0
        public void TestGetLineNumbersBySection()
        {
            var filter = new SubstringFilter("B", true);
            var source = new InMemoryLogFile();

            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "A"
            });
            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "B"
            });
            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "A"
            });
            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "B"
            });
            var filteredLogFile = new FilteredLogFile(_taskScheduler, TimeSpan.Zero, source, filter, null);

            _taskScheduler.RunOnce();

            filteredLogFile.Count.Should().Be(2);
            var lineNumbers = filteredLogFile.GetColumn(new LogFileSection(0, 2), LogFileColumns.LineNumber);

            lineNumbers[0].Should().Be(1);
            lineNumbers[1].Should().Be(2);
        }
示例#3
0
        private SubstringFilter DecodeSubstringFilter(AsnReader reader)
        {
            AsnReader subReader = reader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 4));

            string attributeDescription = System.Text.Encoding.ASCII.GetString(subReader.ReadOctetString());

            SubstringFilter filter = new SubstringFilter
            {
                AttributeDesc = attributeDescription,
            };

            AsnReader substringSequenceReader = subReader.ReadSequence();

            while (substringSequenceReader.HasData)
            {
                switch (substringSequenceReader.PeekTag().TagValue)
                {
                case 0:
                    filter.Initial = System.Text.Encoding.ASCII.GetString(substringSequenceReader.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 0)));
                    break;

                case 1:
                    filter.Any.Add(System.Text.Encoding.ASCII.GetString(substringSequenceReader.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 1))));
                    break;

                case 2:
                    filter.Final = System.Text.Encoding.ASCII.GetString(substringSequenceReader.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 2)));
                    break;
                }
            }

            return(filter);
        }
示例#4
0
        public void TestGetOriginalLineNumbersByIndices()
        {
            var filter = new SubstringFilter("B", true);
            var source = new InMemoryLogFile();

            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "A"
            });
            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "B"
            });
            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "A"
            });
            source.Add(new LogEntry2(LogFileColumns.Minimum)
            {
                RawContent = "B"
            });
            var filteredLogFile = new FilteredLogFile(_taskScheduler, TimeSpan.Zero, source, filter, null);

            _taskScheduler.RunOnce();

            filteredLogFile.Count.Should().Be(2);
            var lineNumbers = filteredLogFile.GetColumn(new LogLineIndex[] { 1, 0 }, LogFileColumns.OriginalLineNumber);

            lineNumbers[0].Should().Be(4);
            lineNumbers[1].Should().Be(2);

            lineNumbers = filteredLogFile.GetColumn(new LogLineIndex[] { 1 }, LogFileColumns.OriginalLineNumber);
            lineNumbers[0].Should().Be(4);
        }
示例#5
0
        public LogSourceSearch(ITaskScheduler taskScheduler, ILogSource logSource, string searchTerm, TimeSpan maximumWaitTime)
        {
            if (taskScheduler == null)
            {
                throw new ArgumentNullException(nameof(taskScheduler));
            }
            if (logSource == null)
            {
                throw new ArgumentNullException(nameof(logSource));
            }
            if (string.IsNullOrEmpty(searchTerm))
            {
                throw new ArgumentException("searchTerm may not be empty");
            }

            _logSource            = logSource;
            _filter               = new SubstringFilter(searchTerm, true);
            _matches              = new List <LogMatch>();
            _syncRoot             = new object();
            _listeners            = new LogFileSearchListenerCollection(this);
            _pendingModifications = new ConcurrentQueue <LogSourceModification>();
            _scheduler            = taskScheduler;

            const int maximumLineCount = 1000;

            _maximumWaitTime = maximumWaitTime;
            _logLinesArray   = new LogBufferArray(maximumLineCount, Columns.Index, Columns.RawContent);
            _matchesBuffer   = new List <LogLineMatch>();
            _logSource.AddListener(this, _maximumWaitTime, maximumLineCount);

            _task = _scheduler.StartPeriodic(FilterAllPending,
                                             TimeSpan.FromMilliseconds(100),
                                             string.Format("Search {0}", logSource));
        }
示例#6
0
        public void TestMatch1()
        {
            var filter  = new SubstringFilter("Foobar", true);
            var matches = new List <LogLineMatch>();

            new Action(() => filter.Match(new LogLine(0, 0, null, LevelFlags.All), matches)).Should().NotThrow();
            matches.Should().BeEmpty();
        }
示例#7
0
        public void TestToString()
        {
            var filter = new SubstringFilter("a", true);

            filter.ToString().Should().Be("message.Contains(a, InvariantCultureIgnoreCase)");

            filter = new SubstringFilter("a", false);
            filter.ToString().Should().Be("message.Contains(a, InvariantCulture)");
        }
        public void TestPassesFilter()
        {
            var filter = new SubstringFilter("a", true);

            filter.PassesFilter(new LogEntry(Core.Columns.Minimum)
            {
                RawContent = null
            }).Should().BeFalse();
        }
示例#9
0
        public void TestMatch2()
        {
            var filter  = new SubstringFilter("a", true);
            var matches = new List <LogLineMatch>();

            filter.Match(new LogLine(0, 0, "Foobar", LevelFlags.All), matches);
            matches.Count.Should().Be(1);
            matches[0].Index.Should().Be(4);
            matches[0].Count.Should().Be(1);
        }
示例#10
0
        public void TestMatch1()
        {
            var filter  = new SubstringFilter("Foobar", true);
            var matches = new List <LogLineMatch>();

            new Action(() => filter.Match(new LogEntry(Core.Columns.Minimum)
            {
                RawContent = null
            }, matches)).Should().NotThrow();
            matches.Should().BeEmpty();
        }
示例#11
0
        private Expression BuildSubstringFilter(SubstringFilter filter, Expression itemExpression)
        {
            string suppliedLikeString = "";

            if (filter.Initial != null)
            {
                suppliedLikeString = EscapeLikeString(filter.Initial);
            }
            else
            {
                suppliedLikeString = "%";
            }

            foreach (string anyString in filter.Any)
            {
                suppliedLikeString = suppliedLikeString + "%" + EscapeLikeString(anyString) + "%";
            }

            if (filter.Final != null)
            {
                suppliedLikeString = suppliedLikeString + EscapeLikeString(filter.Final);
            }
            else
            {
                suppliedLikeString = suppliedLikeString + "%";
            }

            ConstantExpression searchExpr = Expression.Constant(suppliedLikeString);

            if (filter.AttributeDesc == "cn")
            {
                MemberExpression emailProperty = GetMemberExpressionForAttribute(itemExpression, MemberExpressionAttributes.CN);
                return(BuildLikeForPropertyAndString(itemExpression, emailProperty, searchExpr));
            }
            else if (filter.AttributeDesc == "email")
            {
                MemberExpression emailProperty = GetMemberExpressionForAttribute(itemExpression, MemberExpressionAttributes.Email);
                return(BuildLikeForPropertyAndString(itemExpression, emailProperty, searchExpr));
            }
            else if (filter.AttributeDesc == "displayname")
            {
                MemberExpression emailProperty = GetMemberExpressionForAttribute(itemExpression, MemberExpressionAttributes.Email);
                return(BuildLikeForPropertyAndString(itemExpression, emailProperty, searchExpr));
            }
            else if (filter.AttributeDesc == "entryuuid")
            {
                MemberExpression emailProperty = GetMemberExpressionForAttribute(itemExpression, MemberExpressionAttributes.EntryUUID);
                return(BuildLikeForPropertyAndString(itemExpression, emailProperty, searchExpr));
            }

            return(GetAlwaysFalseExpression());
        }
示例#12
0
        public void TestMatch2()
        {
            var filter  = new SubstringFilter("a", true);
            var matches = new List <LogLineMatch>();

            filter.Match(new LogEntry(Core.Columns.Minimum)
            {
                RawContent = "Foobar"
            }, matches);
            matches.Count.Should().Be(1);
            matches[0].Index.Should().Be(4);
            matches[0].Count.Should().Be(1);
        }
 public void Test()
 {
     using (var source1 = new TextLogFile(_scheduler, TextLogFileAcceptanceTest.File2Entries))
         using (var source2 = new TextLogFile(_scheduler, TextLogFileAcceptanceTest.File2Lines))
         {
             var sources = new List <ILogFile> {
                 source1, source2
             };
             using (var merged = new MergedLogFile(_scheduler, TimeSpan.FromMilliseconds(10), sources))
             {
                 var filter = new SubstringFilter("foo", true);
                 using (var filtered = new FilteredLogFile(_scheduler, TimeSpan.FromMilliseconds(10), merged, null, filter))
                 {
                     filtered.Property(x => x.Count).ShouldEventually().Be(1, TimeSpan.FromSeconds(5));
                 }
             }
         }
 }
 public void Test()
 {
     using (var source1 = Create(AbstractTextLogSourceAcceptanceTest.File2Entries))
         using (var source2 = Create(AbstractTextLogSourceAcceptanceTest.File2Lines))
         {
             var sources = new List <ILogSource> {
                 source1, source2
             };
             using (var merged = new MergedLogSource(_taskScheduler, TimeSpan.FromMilliseconds(10), sources))
             {
                 var filter = new SubstringFilter("foo", true);
                 using (var filtered = new FilteredLogSource(_taskScheduler, TimeSpan.FromMilliseconds(10), merged, null, filter))
                 {
                     filtered.Property(x => x.GetProperty(Properties.LogEntryCount)).ShouldAfter(TimeSpan.FromSeconds(5)).Be(1);
                 }
             }
         }
 }
            private IFilter CreateFilter(OperatorType operators, string propertyName, string propertyValue)
            {
                IFilter filter = null;

                switch (operators)
                {
                case OperatorType.eq:
                    filter = new EqualToFilter(propertyName, propertyValue);
                    break;

                case OperatorType.ne:
                    filter = new NotEqualToFilter(propertyName, propertyValue);
                    break;

                case OperatorType.startswith:
                    filter = new StartsWithFilter(propertyName, propertyValue);
                    break;

                case OperatorType.endswith:
                    filter = new EndsWithFilter(propertyName, propertyValue);
                    break;

                case OperatorType.substringof:
                    filter = new SubstringFilter(propertyName, propertyValue);
                    break;

                    /* currently not supported
                     * case OperatorType.lt:
                     *  filter = new LessThanFilter(propertyName, propertyValue);
                     *  break;
                     * case OperatorType.le:
                     *  filter = new LessThanOrEqualFilter(propertyName, propertyValue);
                     *  break;
                     * case OperatorType.gt:
                     *  filter = new GreaterThanFilter(propertyName, propertyValue);
                     *  break;
                     * case OperatorType.ge:
                     *  filter = new GreaterThanOrEqualFilter(propertyName, propertyValue);
                     *  break;
                     */
                }

                return(filter);
            }
示例#16
0
        private Expression BuildSubstringFilter(SubstringFilter filter, Expression itemExpression)
        {
            string suppliedRegex = "";

            if (filter.Initial != null)
            {
                suppliedRegex = Regex.Escape(filter.Initial);
            }
            else
            {
                suppliedRegex = ".*";
            }

            foreach (string anyString in filter.Any)
            {
                suppliedRegex = suppliedRegex + ".*" + Regex.Escape(anyString) + ".*";
            }

            if (filter.Final != null)
            {
                suppliedRegex = suppliedRegex + Regex.Escape(filter.Final);
            }
            else
            {
                suppliedRegex = suppliedRegex + ".*";
            }

            if (filter.AttributeDesc == "cn")
            {
                MemberExpression dnProperty = Expression.Property(itemExpression, "Dn");
                string           baseObj    = (_searchEvent.SearchRequest.BaseObject == "") ? "" : "," + _searchEvent.SearchRequest.BaseObject;

                Regex regex = new Regex("^cn=" + suppliedRegex + Regex.Escape(baseObj) + "$", RegexOptions.Compiled);
                ConstantExpression regexConst = Expression.Constant(regex);

                MethodInfo   methodInfo = typeof(Regex).GetMethod("IsMatch", new Type[] { typeof(string) });
                Expression[] callExprs  = new Expression[] { dnProperty };

                return(Expression.Call(regexConst, methodInfo, callExprs));
            }
            else
            {
                Expression attributeExpr = Expression.Property(itemExpression, "Attributes");

                // Pair to search for
                ParameterExpression keyValuePair = Expression.Parameter(typeof(KeyValuePair <string, List <string> >), "a");

                // rsl
                ParameterExpression regexStringList = Expression.Parameter(typeof(string), "rsl");

                // regex.IsMatch(rsl)
                Regex regex = new Regex("^" + suppliedRegex + "$", RegexOptions.Compiled);
                ConstantExpression   regexConst     = Expression.Constant(regex);
                MethodInfo           methodInfo     = typeof(Regex).GetMethod("IsMatch", new Type[] { typeof(string) });
                Expression[]         callExprs      = new Expression[] { regexStringList };
                MethodCallExpression regexMatchExpr = Expression.Call(regexConst, methodInfo, callExprs);

                // {rsl => regex.IsMatch(rsl)}
                var regexLambda = Expression.Lambda <Func <string, bool> >(regexMatchExpr, regexStringList);

                // a.Value.Any(rsl => regex.IsMatch(rsl))
                Expression           subExprValue       = Expression.Property(keyValuePair, "Value");
                MethodInfo           regexAnyMethodInfo = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).First(m => m.Name == "Any" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(string));
                MethodCallExpression regexAnyCallExpr   = Expression.Call(regexAnyMethodInfo, subExprValue, regexLambda);

                // (a.Key == attributeName)
                Expression subExprLeftAttributeName  = Expression.Property(keyValuePair, "Key");
                Expression subExprRightAttributeName = Expression.Constant(filter.AttributeDesc.ToLower());
                Expression subExprAttributeName      = Expression.Equal(subExprLeftAttributeName, subExprRightAttributeName);

                // ((a.Key == attributeName) && a.Value.Any(rsl => regex.IsMatch(rsl)))
                Expression attributeExprMatch = Expression.And(subExprAttributeName, regexAnyCallExpr);

                // {a => ((a.Key == attributeName) And a.Value.Any(rsl => regex.IsMatch(rsl)))}
                var lambda = Expression.Lambda <Func <KeyValuePair <string, List <string> >, bool> >(attributeExprMatch, keyValuePair);

                MethodInfo anyMethod = typeof(Enumerable).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public).First(m => m.Name == "Any" && m.GetParameters().Count() == 2).MakeGenericMethod(typeof(KeyValuePair <string, List <string> >));
                return(Expression.Call(anyMethod, attributeExpr, lambda));
            }
        }
示例#17
0
        /// <summary>
        /// Get those users and just return what the proxy gave us
        /// </summary>
        /// <returns></returns>
        public directoryRequestResponse GetUsers()
        {
            directoryRequestResponse returnThis = null;

            System.Diagnostics.Debug.WriteLine("Going to get users with the service reference proxy");
            //fiddler
            //GlobalProxySelection.Select = new WebProxy("127.0.0.1", 8888);

            dsmlSoapClient client        = new dsmlSoapClient();
            BatchRequest   batchRequest  = new BatchRequest();
            SearchRequest  searchRequest = new SearchRequest();

            client.ClientCredentials.UserName.UserName = "******";
            client.ClientCredentials.UserName.Password = "******";
            //client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerOrChainTrust;
            //batchRequest.processing = BatchRequestProcessing.sequential;
            //DsmlMessage[] messages = new DsmlMessage[1];
            //Control[] cntrls = new Control[1];
            //Control control = new Control();
            //control.controlValue = searchRequest;
            //cntrls[0] = control;
            //DsmlMessage message = new DsmlMessage();
            //message.control = cntrls;
            //messages[0] = message;
            //batchRequest.Items = messages;
            //added these dsml message types and when i tried to send them thru directory request method got exception about
            //communication exception
            //{"The type DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.DsmlMessage was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."}

            //figured out that search request extends dsml message and so does the other request types, did this by looking at the generated code then right clicking on service ref and configuring.
            //next window i unselected reuse types and it made new types in the auto gen object

            //had to change the web config bindings to pick up the credentials for WCF

            /*
             * <basicHttpBinding>
             *  <binding name="BasicHttpBinding_IService1">
             *    <security mode="TransportCredentialOnly">
             *      <transport clientCredentialType="Basic"/>
             *    </security>
             *  </binding>
             * </basicHttpBinding>
             *
             */

            batchRequest.Items = new SearchRequest[] { searchRequest };
            directoryRequestRequest request = new directoryRequestRequest();

            request.batchRequest = batchRequest;
            //basic set up till now.  This just gets us talking to the daws server with connectivity that is ok.  now business logic about the correct dn and necessary search filters
            searchRequest.dn = "ou=People,ou=NYS Department of Taxation and Finance Business Partners,ou=Business,o=ny,c=us";
            Filter filter = new Filter();


            //there can only be one substring in WCF but you can send in multiple in a direct soap envelope
            SubstringFilter[] substrings = new SubstringFilter[2];
            //SubstringFilter substring = new SubstringFilter();
            //substring.name = "nyacctgovernment";
            //substring.initial = "Y";
            //substrings[0] = substring;
            //SubstringFilter substring1 = new SubstringFilter();
            //substring1.name = "nyacctlevel1";
            //substring1.initial = "Y";
            //substrings[1] = substring1;
            SubstringFilter substring2 = new SubstringFilter();

            substring2.name    = "sn";
            substring2.initial = "smith";
            substrings[0]      = substring2;
            //SubstringFilter substring3 = new SubstringFilter();
            //substring3.name = "ou";
            //substring3.initial = "Department of General Services";
            //substrings[3] = substring3;
            SubstringFilter substring4 = new SubstringFilter();

            substring4.name    = "mail";
            substring4.initial = "*****@*****.**";
            substrings[1]      = substring4;

            SubstringFilter anyFilter = new SubstringFilter();

            anyFilter.any = new String[] { "nyacctgovernment=Y", "nyacctlevel1=Y", "sn=smith" };
            //this any filter produced this soap env

            /*
             * <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
             * <batchRequest xmlns="urn:oasis:names:tc:DSML:2:0:core">
             * <searchRequest dn="ou=People,ou=NYS Department of Taxation and Finance Business Partners,ou=Business,o=ny,c=us" scope="wholeSubtree" derefAliases="neverDerefAliases">
             *  <filter>
             *      <substrings>
             *          <any>nyacctgovernment=Y</any>
             *          <any>nyacctlevel1=Y</any>
             *          <any>sn=smith</any>
             *      </substrings></filter></searchRequest></batchRequest></s:Body></s:Envelope>
             *
             */
            //so going to make a fitlerset instead ..or atleast try
            //first attempt yielded this result
            //System.InvalidOperationException: There was an error generating the XML document. --->
            //System.InvalidOperationException: Invalid or missing value of the choice identifier 'ItemsElementName' of type 'DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.ItemsChoiceType1[]'.
            //second attempt after adding items element names to the andFilterSet got this
            //There was an error generating the XML document. ---> System.InvalidOperationException:
            //Invalid or missing value of the choice identifier 'ItemsElementName' of type 'DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.ItemsChoiceType1[]'.
            //using andFilterSet.ItemsElementName = new ItemsChoiceType1[]{ ItemsChoiceType1.substrings, ItemsChoiceType1.substrings, ItemsChoiceType1.substrings};
            //i initialized the substringfilter array to 4 elements and took one out so i had to even them up to match each other.  itemchoices to filter objects
            //then got this soap env

            /*
             * <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
             * <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><batchRequest xmlns="urn:oasis:names:tc:DSML:2:0:core"><searchRequest dn="ou=People,ou=NYS Department of Taxation and Finance Business Partners,ou=Business,o=ny,c=us" scope="wholeSubtree" derefAliases="neverDerefAliases">
             * <filter>
             * <and>
             *  <substrings name="nyacctgovernment"><initial>Y</initial></substrings>
             *  <substrings name="nyacctlevel1"><initial>Y</initial></substrings>
             *  <substrings name="sn"><initial>smith</initial></substrings>
             * </and>
             * </filter></searchRequest></batchRequest></s:Body></s:Envelope>
             */
            //message is weird b/c if I remove two substring elements I no longer get the msg:
            //[LDAP: error code 50 - Search filter not permitted (substring too short)]

            //just used this in postman and it worked after some messing around with the results to find a possible list of people as a result

            /*
             * <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
             * <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><batchRequest xmlns="urn:oasis:names:tc:DSML:2:0:core"><searchRequest dn="ou=People,ou=NYS Department of Taxation and Finance Business Partners,ou=Business,o=ny,c=us" scope="wholeSubtree" derefAliases="neverDerefAliases">
             * <filter>
             * <and>
             *  <substrings name="sn"><initial>smith</initial></substrings>
             *  <substrings name="mail"><initial>[email protected]</initial></substrings>
             * </and>
             * </filter>
             * <attributes>
             * <attribute name="nyacctgovernment"/>
             * <attribute name="sn"/>
             * <attribute name="givenname"/>
             * <attribute name="mail"/>
             * <attribute name="uid"/>
             * <attribute name="nyacctpersonal"/>
             * <attribute name="nyacctbusiness"/>
             * </attributes>
             * </searchRequest></batchRequest></s:Body></s:Envelope>
             */
            //now and requests work but got this message
            //ommunicationException: The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element. --->
            //System.ServiceModel.QuotaExceededException: The maximum message size quota for incoming messages (65536) has been exceeded.
            //To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.  so I'm going to not take so many attributes back


            FilterSet andFilterSet = new FilterSet();

            andFilterSet.Items            = substrings;
            andFilterSet.ItemsElementName = new ItemsChoiceType1[] { ItemsChoiceType1.substrings, ItemsChoiceType1.substrings };

            filter.Item            = andFilterSet;
            filter.ItemElementName = ItemChoiceType.and;
            searchRequest.filter   = filter;
            searchRequest.scope    = SearchRequestScope.wholeSubtree;
            //{"Value of ItemElementName mismatches the type of
            //DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.SubstringFilter; you need to set it to DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.ItemChoiceType.@substrings."}
            //System.InvalidOperationException: Value of ItemElementName mismatches the type of DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.SubstringFilter; you need to set it to DirectorySearchBusinessLogicLayer.gov.ny.ds.daws.ItemChoiceType.@substrings.



            //THE CALL
            try
            {
                directoryRequestResponse response = client.directoryRequest(request);
                System.Diagnostics.Debug.WriteLine("Response: " + response);
                //The error handling changed from a web reference to a service reference.  guess the wsdl is more generic than i thought.
                ErrorResponse[] eResponses    = null;
                BatchResponse   bResponse     = response.batchResponse;
                Object[]        responseItems = bResponse.Items;
                if (responseItems != null)
                {
                    if (responseItems[0] is ErrorResponse)
                    {
                        ErrorResponse eResponse = (ErrorResponse)responseItems[0];
                        System.Diagnostics.Debug.WriteLine(eResponse.message);
                        System.Diagnostics.Debug.WriteLine(eResponse.detail);
                        System.Diagnostics.Debug.WriteLine(eResponse.type);
                    }
                    else
                    {
                        returnThis = response;
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Dang it: " + e);
            }



            //if (eResponses != null)
            //{
            //    System.Diagnostics.Debug.WriteLine("Checking out errors from the batch response");
            //    System.Diagnostics.Debug.WriteLine("Errors Count: " + eResponses.Length);
            //    //After adding a attribute value assertion and fitler to the search the error response ends up null so make a check for that
            //    if (eResponses != null)
            //    {
            //        if (eResponses.Length > 0)
            //        {
            //            System.Diagnostics.Debug.WriteLine("Error Response");
            //            for (int i = 0; i < eResponses.Length; i++)
            //            {
            //                ErrorResponse error = eResponses[i];
            //                System.Diagnostics.Debug.WriteLine(error.message);
            //                System.Diagnostics.Debug.WriteLine(error.detail);
            //                System.Diagnostics.Debug.WriteLine(error.type);
            //            }
            //        }
            //    }
            //}
            //else
            //{
            //    System.Diagnostics.Debug.WriteLine("No errors from the response");
            //}



            System.Diagnostics.Debug.WriteLine("Finished getting users with the service reference proxy");
            return(returnThis);
        }
示例#18
0
        public void SubstringFilterReturnsSubstringOfExtractedValue()
        {
            var filter = new SubstringFilter(3, 3);

            Assert.Equal("llo", filter.Apply("Hello, World"));
        }
        /*
         * first time running this by just changing the filter a little i got this message.
         * There was an error generating the XML document. ---> System.InvalidOperationException:
         * Value of ItemElementName mismatches the type of DirectorySearchBusinessLogicLayer.gov.ny.svc.daws.SubstringFilter;
         * you need to set it to DirectorySearchBusinessLogicLayer.gov.ny.svc.daws.ItemChoiceType.@substrings.
         *
         *
         * System.InvalidOperationException: There was an error generating the XML document. --->
         * System.InvalidOperationException: Value of ItemElementName mismatches the type of DirectorySearchBusinessLogicLayer.gov.ny.svc.daws.SubstringFilter;
         * you need to set it to DirectorySearchBusinessLogicLayer.gov.ny.svc.daws.ItemChoiceType.@substrings.
         *
         *
         * The next time I changed out the ava filter for a substring type and got this message
         * Error Response
         * [LDAP: error code 50 - Search filter not permitted (substring too short)]
         */
        public IEnumerable <NyGovUser> GetUsers(String ou)
        {
            GlobalProxySelection.Select = new WebProxy("127.0.0.1", 8888);
            List <NyGovUser> returnList = new List <NyGovUser>();
            //example OU ||||   dn =”ou = Department of General Services,ou = Government,o = ny,c = us
            BatchRequest     batch  = new BatchRequest();
            SearchRequest    search = new SearchRequest();
            Filter           filter = new Filter();
            dsmlQueryService client = new dsmlQueryService();

            client.Url          = "https://qadaws.svc.ny.gov/daws/services/dsmlSoapQuery";
            batch.searchRequest = new SearchRequest[1] {
                search
            };
            client.Credentials = new NetworkCredential("prxwsTL1HESC", "sfvwRMnB7N");
            search.dn          = "'ou = Department of General Services,ou = Government,o = ny,c = us'";
            //search.dn = ou;

            //can't use attribute value assertion for substring choice.  instead make substring filter
            //AttributeValueAssertion ava = new AttributeValueAssertion();
            //ava.name = "nyacctgovernment";
            //ava.value = "Y";
            SubstringFilter[] substrings = new SubstringFilter[4];
            SubstringFilter   substring  = new SubstringFilter();

            substring.name    = "nyacctgovernment";
            substring.initial = "Y";
            substrings[0]     = substring;
            SubstringFilter substring1 = new SubstringFilter();

            substring1.name    = "nyacctlevel1";
            substring1.initial = "Y";
            substrings[1]      = substring1;
            SubstringFilter substring2 = new SubstringFilter();

            substring2.name    = "sn";
            substring2.initial = "smith";
            substrings[2]      = substring2;
            SubstringFilter substring3 = new SubstringFilter();

            substring3.name    = "ou";
            substring3.initial = "Department of General Services";
            substrings[3]      = substring3;
            //FilterSet fSet = new FilterSet();
            //ItemsChoiceType[] chioceTypes = new ItemsChoiceType[4];
            //fSet.ItemsElementName = chioceTypes;



            filter.ItemElementName = ItemChoiceType.substrings;
            filter.Item            = substring2;
            search.filter          = filter;
            search.scope           = SearchRequestScope.wholeSubtree;

            AttributeDescriptions attrBucket = new AttributeDescriptions();

            AttributeDescription[] attributeDescriptionList = new AttributeDescription[7];
            attributeDescriptionList[0] = new AttributeDescription()
            {
                name = "nyacctgovernment"
            };
            attributeDescriptionList[1] = new AttributeDescription()
            {
                name = "sn"
            };
            attributeDescriptionList[2] = new AttributeDescription()
            {
                name = "givenname"
            };
            attributeDescriptionList[3] = new AttributeDescription()
            {
                name = "mail"
            };
            attributeDescriptionList[4] = new AttributeDescription()
            {
                name = "uid"
            };
            attributeDescriptionList[5] = new AttributeDescription()
            {
                name = "nyacctpersonal"
            };
            attributeDescriptionList[6] = new AttributeDescription()
            {
                name = "nyacctbusiness"
            };
            attrBucket.attribute = attributeDescriptionList;

            search.attributes = attrBucket;
            //client.PreAuthenticate = true;
            //client.AllowAutoRedirect = true;



            BatchResponse response = null;

            try
            {
                //WebProxy myproxy = new WebProxy("proxy-internet.cio.state.nyenet", 80);
                //myproxy.BypassProxyOnLocal = false;
                //myproxy.Credentials = new NetworkCredential("mjordan", "fuckU023$6");
                //client.Proxy = myproxy;
                response = client.directoryRequest(batch);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Dang it.  probably a 502 from the server and even more probable about async.  " + e);
            }
            System.Diagnostics.Debug.WriteLine("just sent the request for a batch seach to directory request");
            System.Diagnostics.Debug.WriteLine("Response: " + response);

            if (response != null)
            {
                SearchResponse[] sResponses = response.searchResponse;
                System.Diagnostics.Debug.WriteLine("Search Response: " + sResponses);
                if (sResponses != null)
                {
                    System.Diagnostics.Debug.WriteLine("Got " + sResponses.Length + " responses");
                    for (int i = 0; i < sResponses.Length; i++)
                    {
                        System.Diagnostics.Debug.WriteLine("Search Response #" + i + " requestID: " + sResponses[i].requestID);
                        SearchResultEntry[] srEntries = sResponses[i].searchResultEntry;
                        LDAPResult          srd       = sResponses[i].searchResultDone;
                        if (srd != null)
                        {
                            System.Diagnostics.Debug.WriteLine("LDAP Result AKA search result done");
                            System.Diagnostics.Debug.WriteLine(srd.resultCode.descr);
                        }
                        if (srEntries != null)
                        {
                            System.Diagnostics.Debug.WriteLine("Search Result Entries Cycle");
                            for (int r = 0; r < srEntries.Length; r++)
                            {
                                NyGovUser user = new NyGovUser();
                                user.NysSogUid = srEntries[r].dn;
                                System.Diagnostics.Debug.WriteLine(srEntries[r].dn);
                                System.Diagnostics.Debug.WriteLine(srEntries[r].attr);
                                DsmlAttr[] attributeList = srEntries[r].attr;
                                if (attributeList != null)
                                {
                                    for (int a = 0; a < attributeList.Length; a++)
                                    {
                                        System.Diagnostics.Debug.WriteLine("name: " + attributeList[a].name);
                                        String        attName      = attributeList[a].name;
                                        StringBuilder valueBuilder = new StringBuilder();
                                        if (attributeList[a].value != null)
                                        {
                                            for (int x = 0; x < attributeList[a].value.Length; x++)
                                            {
                                                System.Diagnostics.Debug.WriteLine("value: " + attributeList[a].value[x]);
                                                valueBuilder.Append(attributeList[a].value[x]);
                                            }
                                        }

                                        if (attName.Equals("uid"))
                                        {
                                            user.Uid = valueBuilder.ToString();
                                        }
                                        else if (attName.Equals("cn"))
                                        {
                                            user.CommonName = valueBuilder.ToString();
                                        }
                                        else if (attName.Equals("nyacctgovernment"))
                                        {
                                            user.IsGovernmentAccount = Convert.ToBoolean(valueBuilder.ToString());
                                        }
                                        else if (attName.Equals("sn"))
                                        {
                                            user.Surname = valueBuilder.ToString();
                                        }
                                        else if (attName.Equals("givenname"))
                                        {
                                            user.Firstname = valueBuilder.ToString();
                                        }
                                        else if (attName.Equals("mail"))
                                        {
                                            user.EmailAddress = valueBuilder.ToString();
                                        }
                                        else if (attName.Equals("nyacctbusiness"))
                                        {
                                            user.IsBusinessPartnerAccount = Convert.ToBoolean(valueBuilder.ToString());
                                        }
                                        else if (attName.Equals("nyacctpersonal"))
                                        {
                                            user.IsCitizenAccount = Convert.ToBoolean(valueBuilder.ToString());
                                        }
                                    }
                                }
                                returnList.Add(user);
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("Search results list is null for some reason");
                        }
                    }
                }



                ErrorResponse[] eResponses = response.errorResponse;

                if (eResponses != null)
                {
                    System.Diagnostics.Debug.WriteLine("Checking out errors from the batch response");
                    System.Diagnostics.Debug.WriteLine("Errors Count: " + eResponses.Length);
                    //After adding a attribute value assertion and fitler to the search the error response ends up null so make a check for that
                    if (eResponses != null)
                    {
                        if (eResponses.Length > 0)
                        {
                            System.Diagnostics.Debug.WriteLine("Error Response");
                            for (int i = 0; i < eResponses.Length; i++)
                            {
                                ErrorResponse error = eResponses[i];
                                System.Diagnostics.Debug.WriteLine(error.message);
                                System.Diagnostics.Debug.WriteLine(error.detail);
                                System.Diagnostics.Debug.WriteLine(error.type);
                            }
                        }
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("No errors from the response");
                }
            }

            return(returnList);
        }
示例#20
0
        public void SubstringFilter(bool isEqual)
        {
            var filter = new SubstringFilter("Name", "ShareFile", isEqual);

            filter.ToString().Should().Be("substringof('ShareFile', Name) eq " + isEqual.ToLowerString());
        }