Example #1
0
 public DotNetSdkInstance(Version version, string path, DiscoveryType discoveryType)
 {
     Name          = ".NET Core SDK";
     Version       = version;
     DiscoveryType = discoveryType;
     MSBuildPath   = path; // the DLLs, etc, are right in the root of the .NET SDK path
 }
        /// <summary>
        /// Starts a discovery process
        /// </summary>
        public void Find( DiscoveryType type = DiscoveryType.WsDiscovery )
        {
            ActivityServices.Clear();
#if !ANDROID
           

            switch ( type )
            {
                case DiscoveryType.WsDiscovery:
                    using ( var wsBrowser = new DiscoveryClient( new UdpDiscoveryEndpoint() ) )
                    {
                        wsBrowser.FindProgressChanged += WsBrowserFindProgressChanged;
                        wsBrowser.FindCompleted += WsBrowserFindCompleted;
                        wsBrowser.FindAsync( new FindCriteria( typeof( IDiscovery ) ) );
                    }
                    break;
                case DiscoveryType.Zeroconf:
                {
                    var zcBrowser = new ServiceBrowser();
                    zcBrowser.ServiceAdded += zcBrowser_ServiceAdded;
                    zcBrowser.Browse( "_am._tcp", "local" );
                }
                    break;
            }
#else
            Probe();
#endif
        }
 private void ValidateDiscoveredDevice(DiscoveredDevice dv, DiscoveryType foundWith)
 {
     if (foundWith == DiscoveryType.NOTIFY && (string.IsNullOrWhiteSpace(dv.USN) || string.IsNullOrWhiteSpace(dv.Location)))
     {
         throw new Exception("Invalid device details");
     }
 }
Example #4
0
        /// <summary>
        /// Starts a discovery process
        /// </summary>
        public void Find(DiscoveryType type = DiscoveryType.WsDiscovery)
        {
            ActivityServices.Clear();
#if !ANDROID
            switch (type)
            {
            case DiscoveryType.WsDiscovery:
                using (var wsBrowser = new DiscoveryClient(new UdpDiscoveryEndpoint()))
                {
                    wsBrowser.FindProgressChanged += WsBrowserFindProgressChanged;
                    wsBrowser.FindCompleted       += WsBrowserFindCompleted;
                    wsBrowser.FindAsync(new FindCriteria(typeof(IDiscovery)));
                }
                break;

            case DiscoveryType.Zeroconf:
            {
                var zcBrowser = new ServiceBrowser();
                zcBrowser.ServiceAdded += zcBrowser_ServiceAdded;
                zcBrowser.Browse("_am._tcp", "local");
            }
            break;
            }
#else
            Probe();
#endif
        }
Example #5
0
        public DiscoveryEventArgs(DiscoveryType type, MAC mac, MacType macType, byte[] rawAdvertisement, sbyte rssi)
        {
            Type              = type;
            MAC               = mac;
            MacType           = macType;
            RawAdvertisements = rawAdvertisement;
            Advertisements    = new Dictionary <byte, byte[]>();
            var i = 0;

            while (i < rawAdvertisement.Length)
            {
                // Notice that advertisement or scan response data must be formatted in accordance to the Bluetooth Core
                // Specification.See BLUETOOTH SPECIFICATION Version 4.0[Vol 3 - Part C - Chapter 11].
                var length = rawAdvertisement[i++];
                if (length == 0)
                {
                    break;
                }
                var key   = rawAdvertisement[i++];
                var value = new byte[length - 1];
                Array.Copy(rawAdvertisement, i, value, 0, value.Length);
                Advertisements[key] = value;
                i += value.Length;
            }
            Name = Advertisements.TryGetValue(0x08, out var nameValue) || Advertisements.TryGetValue(0x09, out nameValue)
                 ? Encoding.UTF8.GetString(nameValue)
                 : null;
            RSSI = rssi;
        }
        internal VisualStudioInstance(string name, string path, Version version, DiscoveryType discoveryType)
        {
            Name = name;
            VisualStudioRootPath = path;
            Version       = version;
            DiscoveryType = discoveryType;

            switch (discoveryType)
            {
            case DiscoveryType.DeveloperConsole:
            case DiscoveryType.VisualStudioSetup:
                // For VS 16.0 and higher use 'Current' instead of '15.0' in the MSBuild path.
                MSBuildPath = version.Major >= 16
                        ? Path.Combine(VisualStudioRootPath, "MSBuild", "Current", "Bin")
                        : Path.Combine(VisualStudioRootPath, "MSBuild", "15.0", "Bin");
                break;

            case DiscoveryType.DotNetSdk:
                MSBuildPath = VisualStudioRootPath;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(discoveryType), discoveryType, null);
            }
        }
Example #7
0
        private static void CacheItemRemoved(string cacheKey, object o, CacheItemRemovedReason cacheItemRemovedReason)
        {
            DiscoveryType discoveryType = (DiscoveryType)o;

            switch (discoveryType)
            {
            case DiscoveryType.File:
                lock (_fileDiscoveriesLock)
                {
                    FileDiscoveries.Remove(UserId);
                }
                break;

            case DiscoveryType.Image:
                lock (_imageDiscoveriesLock)
                {
                    ImageDiscoveries.Remove(UserId);
                }
                break;

            case DiscoveryType.WebPage:
                lock (_hyperLinkDiscoveriesLock)
                {
                    HyperLinkDiscoveries.Remove(UserId);
                }
                break;
            }
        }
Example #8
0
 internal VisualStudioInstance(string name, string path, Version version, DiscoveryType discoveryType)
 {
     Name = name;
     VisualStudioRootPath = path;
     Version       = version;
     DiscoveryType = discoveryType;
     MSBuildPath   = Path.Combine(VisualStudioRootPath, "MSBuild", "15.0", "Bin");
 }
Example #9
0
 public void Discover(DiscoveryType type)
 {
     //Ask each transport to discover.
     foreach (RdmRouteBinding binding in transports.Values)
     {
         binding.Transport.Discover(type);
     }
 }
Example #10
0
        /// <summary>
        /// Start new broadcast service
        /// </summary>
        /// <param name="type">Type of discovery</param>
        /// <param name="nameToBroadcast">The name of the service that needs to be broadcasted</param>
        /// <param name="physicalLocation">The physical location of the service that needs to be broadcasted</param>
        /// <param name="code">code to be broadcasted (e.g. device id)</param>
        /// <param name="addressToBroadcast">The address of the service that needs to be broadcasted</param>
        public void Start(DiscoveryType type, string nameToBroadcast, string physicalLocation, string code, Uri addressToBroadcast)
        {
            DiscoveryType = type;

            switch (DiscoveryType)
            {
            case DiscoveryType.WsDiscovery:
            {
                Ip      = Net.GetIp(IpType.All);
                Port    = 7985;
                Address = "http://" + Ip + ":" + Port + "/";

                _discoveryHost = new ServiceHost(new DiscoveyService());

                var serviceEndpoint = _discoveryHost.AddServiceEndpoint(typeof(IDiscovery), new WebHttpBinding(),
                                                                        Net.GetUrl(Ip, Port, ""));
                serviceEndpoint.Behaviors.Add(new WebHttpBehavior());

                var broadcaster = new EndpointDiscoveryBehavior();

                broadcaster.Extensions.Add(nameToBroadcast.ToXElement <string>());
                broadcaster.Extensions.Add(physicalLocation.ToXElement <string>());
                broadcaster.Extensions.Add(addressToBroadcast.ToString().ToXElement <string>());
                broadcaster.Extensions.Add(code.ToXElement <string>());

                serviceEndpoint.Behaviors.Add(broadcaster);
                _discoveryHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
                _discoveryHost.Description.Endpoints.Add(new UdpDiscoveryEndpoint());
                _discoveryHost.Open();

                IsRunning = true;
                Debug.WriteLine(DiscoveryType.ToString() + " is started");
            }
            break;

            case DiscoveryType.Zeroconf:
            {
                _service = new RegisterService {
                    Name = nameToBroadcast, RegType = "_am._tcp", ReplyDomain = "local", Port = 3689
                };


                // TxtRecords are optional
                var txtRecord = new TxtRecord
                {
                    { "name", nameToBroadcast },
                    { "addr", addressToBroadcast.ToString() },
                    { "loc", physicalLocation },
                    { "code", code }
                };
                _service.TxtRecord = txtRecord;
                _service.Response += service_Response;
                _service.Register();
                Debug.WriteLine(DiscoveryType.ToString() + " is started");
            }
            break;
            }
        }
Example #11
0
 /// <summary>
 ///     Initializes a new instance of the <see cref = "DataType" /> struct.
 /// </summary>
 /// <param name = "contentType">Type of the content.</param>
 /// <param name = "contentTypeID">The content type ID.</param>
 /// <param name = "discoveryType">Type of the discovery.</param>
 /// <param name = "fullTextIndexType">Full type of the text index.</param>
 /// <param name = "synonyms">The synonyms.</param>
 /// <param name = "overrides">The overrides.</param>
 public DataType(string contentType, int contentTypeID, DiscoveryType discoveryType, string fullTextIndexType, List <string> synonyms, List <string> overrides)
 {
     _contentType       = contentType;
     _contentTypeID     = contentTypeID;
     _discoveryType     = discoveryType;
     _fullTextIndexType = fullTextIndexType;
     _synonyms          = synonyms;
     _overrides         = overrides;
 }
Example #12
0
 public virtual void StartBroadcast(DiscoveryType type, string hostName,string location = "undefined", string code = "-1")
 {
     var t = new Thread(() =>
     {
         StopBroadcast();
         _broadcast.Start(type, hostName, location, code,
                           Net.GetUrl(Ip, Port, ""));
     }) { IsBackground = true };
     t.Start();
 }
Example #13
0
        /// <summary>
        /// Starts a discovery process
        /// </summary>
        public void Find(DiscoveryType type = DiscoveryType.WSDiscovery)
        {
            ActivityServices.Clear();
#if !ANDROID
            switch (type)
            {
                case DiscoveryType.WSDiscovery:
                    using (var wsBrowser = new DiscoveryClient(new UdpDiscoveryEndpoint()))
                    {
                        wsBrowser.FindProgressChanged += WSBrowserFindProgressChanged;
                        wsBrowser.FindCompleted += WSBrowserFindCompleted;
                        wsBrowser.FindAsync(new FindCriteria(typeof(IDiscovery)));
                    }
                    break;
                case DiscoveryType.Zeroconf:
                    {
                        var zcBrowser = new ServiceBrowser();
                        zcBrowser.ServiceAdded += delegate(object o, ServiceBrowseEventArgs args)
                        {
                            args.Service.Resolved += ZcBrowserServiceResolved;
                            args.Service.Resolve();
                        };
                        zcBrowser.Browse("_am._tcp", "local");
                        
                    }
                    break;
            }

            switch (type)
            {
                case DiscoveryType.WSDiscovery:
                    using (var wsBrowser = new DiscoveryClient(new UdpDiscoveryEndpoint()))
                    {
                        wsBrowser.FindProgressChanged += WSBrowserFindProgressChanged;
                        wsBrowser.FindCompleted += WSBrowserFindCompleted;
                        wsBrowser.FindAsync(new FindCriteria(typeof(IDiscovery)));
                    }
                    break;
                case DiscoveryType.Zeroconf:
                    {
                        var zcBrowser = new ServiceBrowser();
                        zcBrowser.ServiceAdded += delegate(object o, ServiceBrowseEventArgs args)
                        {
                            args.Service.Resolved += ZcBrowserServiceResolved;
                            args.Service.Resolve();
                        };
                        zcBrowser.Browse("_am._tcp", "local");

                    }
                    break;
            }
#else
            Probe();
#endif
        }
Example #14
0
        public DiscoveryManager()
        {
            ActivityServices = new List <ServiceInfo>();
            DiscoveryType    = DiscoveryType.WsDiscovery;
#if ANDROID
            _messageId = Guid.NewGuid().ToString();
            _udpClient = new UdpClient(WsDiscoveryPort);
            _udpClient.JoinMulticastGroup(IPAddress.Parse(WsDiscoveryIPAddress));
            _udpClient.BeginReceive(HandleRequest, _udpClient);
        #endif
        }
Example #15
0
 public DiscoveryManager()
 {
     ActivityServices = new List<ServiceInfo>();
     DiscoveryType = DiscoveryType.WSDiscovery;
 #if ANDROID
     _messageId = Guid.NewGuid().ToString();
     _udpClient = new UdpClient(WsDiscoveryPort);
     _udpClient.JoinMulticastGroup(IPAddress.Parse(WsDiscoveryIPAddress));
     _udpClient.BeginReceive(HandleRequest, _udpClient);
 #endif
 }
Example #16
0
 public MSBuildInstance(
     string name, string msbuildPath, Version version, DiscoveryType discoveryType,
     ImmutableDictionary <string, string> propertyOverrides = null,
     bool setMSBuildExePathVariable = false)
 {
     Name                      = name;
     MSBuildPath               = msbuildPath;
     Version                   = version ?? new Version(0, 0);
     DiscoveryType             = discoveryType;
     PropertyOverrides         = propertyOverrides ?? ImmutableDictionary <string, string> .Empty;
     SetMSBuildExePathVariable = setMSBuildExePathVariable;
 }
        internal VisualStudioInstance(string name, string path, Version version, DiscoveryType discoveryType)
        {
            Name = name;
            VisualStudioRootPath = path;
            Version       = version;
            DiscoveryType = discoveryType;

            // For VS 16.0 and higher use 'Current' instead of '15.0' in the MSBuild path.
            MSBuildPath = version.Major >= 16 ?
                          Path.Combine(VisualStudioRootPath, "MSBuild", "Current", "Bin") :
                          Path.Combine(VisualStudioRootPath, "MSBuild", "15.0", "Bin");
        }
 private void OnDeviceStatusUpdate(DiscoveredDevice dv, DiscoveryType type, DiscoveryEvent evt)
 {
     if (DeviceStatusUpdate != null)
     {
         DeviceStatusUpdate(this, new DiscoveredEventArgs()
         {
             Device          = dv,
             Event           = evt,
             DiscoveredUsing = type
         });
     }
 }
Example #19
0
 public void Discover(DiscoveryType type)
 {
     switch (type)
     {
     case DiscoveryType.DeviceDiscovery:
         foreach (RdmEndPoint endpoint in DiscoveredEndpoints)
         {
             StartRdmDiscovery(endpoint);
         }
         break;
     }
 }
Example #20
0
        /// <summary>
        /// Start new broadcast service
        /// </summary>
        /// <param name="type">Type of discovery</param>
        /// <param name="nameToBroadcast">The name of the service that needs to be broadcasted</param>
        /// <param name="physicalLocation">The physical location of the service that needs to be broadcasted</param>
        /// <param name="addressToBroadcast">The address of the service that needs to be broadcasted</param>
        /// <param name="broadcastPort">The port of the broadcast service. Default=56789</param>
        public void Start(DiscoveryType type,string nameToBroadcast,string physicalLocation,string code,Uri addressToBroadcast,int broadcastPort=7892)
        {
            DiscoveryType = type;

            switch (DiscoveryType)
            {
                case DiscoveryType.WSDiscovery:
                    {
                        Ip = Net.GetIp(IPType.All);
                        Port = broadcastPort;
                        Address = "http://" + Ip + ":" + Port + "/";

                        _discoveryHost = new ServiceHost(new DiscoveyService());

                        var serviceEndpoint = _discoveryHost.AddServiceEndpoint(typeof(IDiscovery), new WebHttpBinding(), 
                                                                                Net.GetUrl(Ip, Port, ""));
                        serviceEndpoint.Behaviors.Add(new WebHttpBehavior());

                        var broadcaster = new EndpointDiscoveryBehavior();

                        broadcaster.Extensions.Add(nameToBroadcast.ToXElement<string>());
                        broadcaster.Extensions.Add(physicalLocation.ToXElement<string>());
                        broadcaster.Extensions.Add(addressToBroadcast.ToString().ToXElement<string>());
                        broadcaster.Extensions.Add(code.ToXElement<string>());

                        serviceEndpoint.Behaviors.Add(broadcaster);
                        _discoveryHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
                        _discoveryHost.Description.Endpoints.Add(new UdpDiscoveryEndpoint());
                        _discoveryHost.Open();

                        IsRunning = true;
                    }
                    break;
                case DiscoveryType.Zeroconf:
                    {
                        var service = new RegisterService
                                          {Name = nameToBroadcast, RegType = "_am._tcp", ReplyDomain = "local.", Port = 3689};

                        // TxtRecords are optional
                        var txtRecord = new TxtRecord(){
                                                {"name", nameToBroadcast},
                                                {"addr", addressToBroadcast.ToString()},
                                                {"loc", physicalLocation},
                                                {"code", code}
                                            };
                        service.TxtRecord = txtRecord;

                        service.Register();
                    }
                    break;
            }
        }
Example #21
0
 public void Discover(DiscoveryType type)
 {
     if (type == DiscoveryType.GatewayDiscovery)
     {
         SendArtPoll();
     }
     if (type == DiscoveryType.DeviceDiscovery)
     {
         for (int n = 0; n < byte.MaxValue; n++)
         {
             SendTodControl(n, ArtTodControlCommand.AtcFlush);
         }
     }
 }
Example #22
0
        public virtual void StartBroadcast(DiscoveryType type, string hostName, string location = "undefined", string code = "-1")
        {
            var t = new Thread(() =>
            {
                StopBroadcast();
                _broadcast.Start(type, hostName, location, code,
                                 Net.GetUrl(Ip, Port, ""));
            })
            {
                IsBackground = true
            };

            t.Start();
        }
 private bool FilterDevice(DiscoveredDevice dv, DiscoveryType foundWith)
 {
     if (FilterByService == null || FilterByService.Length == 0)
     {
         return(true);
     }
     else if (Array.IndexOf(FilterByService, dv.Target) > -1)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
        //SSDP process
        private void ProcessSSDPMessage(string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                return;
            }

            DiscoveredDevice ssdpDevice;
            DiscoveryType    foundwith   = DiscoveryType.MSEARCH;
            DiscoveryEvent   discovEvent = DiscoveryEvent.DeviceFound;

            if (message.Contains("M-SEARCH"))
            {
                return;
            }
            else if (message.Contains("NOTIFY"))
            {
                foundwith = DiscoveryType.NOTIFY;

                if (message.Contains("DiscoveryService:alive"))
                {
                    discovEvent = DiscoveryEvent.DeviceFound;
                }
                else if (message.Contains("DiscoveryService:byebye"))
                {
                    discovEvent = DiscoveryEvent.DeviceRemoved;
                }
            }
            else if (message.Contains("HTTP/1.1 200 OK"))
            {
                foundwith = DiscoveryType.MSEARCH;
            }

            if (DiscoveredDevice.TryParse(message, out ssdpDevice))
            {
                try
                {
                    ValidateDiscoveredDevice(ssdpDevice, foundwith);
                    var ok = FilterDevice(ssdpDevice, foundwith);
                    if (ok)
                    {
                        OnDeviceStatusUpdate(ssdpDevice, foundwith, discovEvent);
                    }
                }
                catch (Exception) { }
            }
        }
        /// <summary>
        /// 查看发现页分类的全部或部分内容
        /// </summary>
        /// <param name="type">发现页的分类类型</param>
        /// <param name="categoryId">书籍分类号</param>
        /// <param name="pageNum">请求第几页的数据,pageNum最小值为1</param>
        /// <param name="pageSize">请求每页多少条的数据</param>
        /// <returns></returns>
        public async Task <Response <BookListPageResponse> > GetDiscoveryDetailAsync(DiscoveryType type, int pageNum = 1, int pageSize = 20, int categoryId = 0)
        {
            if (pageNum < 1 || pageSize < 1 || (type == DiscoveryType.Category && categoryId < 1))
            {
                throw new ArgumentException("请输入有效的参数");
            }

            var dict = new Dictionary <string, string>();

            dict.Add("type", GetEnumMemberValue(type));
            dict.Add("categoryId", categoryId.ToString());
            dict.Add("pageNum", pageNum.ToString());
            dict.Add("pageSize", pageSize.ToString());

            var result = await GetAsync <Response <BookListPageResponse> >(API_DISCOVERY_DETAIL, dict);

            return(result);
        }
        protected override void CreateDocument(Document document, long discoveryID, DiscoveryType discoveryType, string absoluteUri, string contentToIndex, int codePage, string fullTextIndexType, float strength, string discoveryPath, int threadNumber)
        {
            //a bare bones example of what you could do to add a new field to the index...
            //if (discoveryType == DiscoveryType.WebPage)
            //{
            //    HtmlDocument htmlDocument = new HtmlDocument();

            //    htmlDocument.LoadHtml(contentToIndex);

            //    HtmlNode htmlNode = htmlDocument.DocumentNode.SelectSingleNode("/html/body");

            //    string body = htmlNode.InnerText;

            //    document.Add(new Field("body", "Mike", Field.Store.NO, Field.Index.UN_TOKENIZED));
            //}

            document.Add(new Field("indexkey", discoveryType.ToString().ToLower().Substring(0, 1) + discoveryID, Field.Store.YES, Field.Index.NOT_ANALYZED));

            document.Add(new Field("discoveryid", discoveryID.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("discoverytype", discoveryType.ToString().ToLower(), Field.Store.YES, Field.Index.NOT_ANALYZED));

            //Discovery
            document.Add(new Field("absoluteuri", absoluteUri, Field.Store.YES, Field.Index.ANALYZED));

            //core fields
            document.Add(new Field("text", contentToIndex, Field.Store.NO, Field.Index.ANALYZED));
            document.Add(new Field("codepage", codePage.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("title", _title.Match(contentToIndex).Groups["Title"].Value.Trim(), Field.Store.YES, Field.Index.ANALYZED));

            //DiscoveryPath
            document.Add(new Field("discoverypath", discoveryPath, Field.Store.YES, Field.Index.NO));

            //AbsoluteUri Classification
            document.Add(new Field("domain", UserDefinedFunctions.ExtractDomain(absoluteUri).Value, Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("extension", UserDefinedFunctions.ExtractExtension(absoluteUri, false).Value, Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("host", UserDefinedFunctions.ExtractHost(absoluteUri).Value, Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.Add(new Field("scheme", UserDefinedFunctions.ExtractScheme(absoluteUri, false).Value, Field.Store.YES, Field.Index.NOT_ANALYZED));

            //FullTextIndexType - used to store the extension that can be used with the default IIS MIME types configuration... (.pl images cannot be served without MIME type modification...)
            document.Add(new Field("fulltextindextype", fullTextIndexType, Field.Store.YES, Field.Index.NOT_ANALYZED));

            AddDocument(document, absoluteUri, strength);
        }
        private void VerifyQueryResults(IEnumerable <VisualStudioInstance> instances, DiscoveryType discoveryTypes, params string[] expectedInstanceNames)
        {
            IEnumerable <VisualStudioInstance> actual = MSBuildLocator.QueryVisualStudioInstances(instances, new VisualStudioInstanceQueryOptions
            {
                DiscoveryTypes = discoveryTypes
            });

            if (expectedInstanceNames != null && expectedInstanceNames.Any())
            {
                List <string> names = actual
                                      .Select(i => i.Name)
                                      .ToList();

                names.ShouldBe(expectedInstanceNames, ignoreOrder: true);
            }
            else
            {
                actual.ShouldBeEmpty();
            }
        }
Example #28
0
 public ServiceRegistrySettings(DiscoveryType discoveryType)
 {
     this.discoveryType = discoveryType;
 }
 /// <summary>
 /// Returns the <paramref name="value"/> as a <see cref="Microsoft.Build.Locator.DiscoveryType"/>.
 /// </summary>
 /// <param name="value"></param>
 /// <returns></returns>
 /// <see cref="DiscoveryType"/>
 /// <see cref="Microsoft.Build.Locator.DiscoveryType"/>
 public static Microsoft.Build.Locator.DiscoveryType ToDiscoveryType(this DiscoveryType value)
 => (Microsoft.Build.Locator.DiscoveryType)(int) value;
Example #30
0
 private static extern MFPCOMM_ERROR MFPComm_SetDiscoveryType(IntPtr handle, DiscoveryType discoveryType);
Example #31
0
#pragma warning disable 612,618
        public static Value.SearchResults <Document> GetDocuments(QueryParser defaultQueryParser, QueryParser customQueryParser, IndexSearcher indexSearcher, string query, DiscoveryType discoveryType, int pageNumber, int pageSize, bool shouldDocumentsBeClustered, string sort, int maximumNumberOfDocumentsToScore)
        {
            Query query2;
            Query wildcardSafeQuery2;

            if (!query.Contains(":"))
            {
                query2             = defaultQueryParser.Parse(query + " AND discoverytype:" + Enum.GetName(typeof(DiscoveryType), discoveryType));
                wildcardSafeQuery2 = defaultQueryParser.Parse(query.Replace("*", " ").Replace("?", " ") + " AND discoverytype:" + Enum.GetName(typeof(DiscoveryType), discoveryType));
            }
            else
            {
                query2             = customQueryParser.Parse(query);
                wildcardSafeQuery2 = customQueryParser.Parse(query.Replace("*", " ").Replace("?", " "));
            }

            TopDocs topDocs = null;

            if (!string.IsNullOrEmpty(sort))
            {
                string[] sorts = sort.ToLower().Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                List <SortField> sortFields = new List <SortField>(sorts.Length / 2);

                for (int i = 0; i < sorts.Length; i++)
                {
                    if (sorts[i].Split(' ')[1] == "asc")
                    {
                        sortFields.Add(new SortField(sorts[i].Split(' ')[0], false));
                    }
                    else
                    {
                        sortFields.Add(new SortField(sorts[i].Split(' ')[0], true));
                    }
                }

                topDocs = indexSearcher.Search(query2, null, maximumNumberOfDocumentsToScore, new Sort(sortFields.ToArray()));
            }
            else
            {
                topDocs = indexSearcher.Search(query2, null, maximumNumberOfDocumentsToScore);
            }

            Value.SearchResults <Document> searchResults = new Value.SearchResults <Document>();

            searchResults.Documents         = new List <Document>();
            searchResults.Query             = query2;
            searchResults.WildcardSafeQuery = wildcardSafeQuery2;

            if (topDocs.scoreDocs.Length != 0)
            {
                Dictionary <string, string> domains = new Dictionary <string, string>();

                PriorityQueue <Document> priorityQueue = new PriorityQueue <Document>();

                //Get the Hits!!!
                //ANODET: Optimize this!!! (Version 2.5+)
                for (int j = 0; j < topDocs.scoreDocs.Length && searchResults.Documents.Count < maximumNumberOfDocumentsToScore && priorityQueue.Count < maximumNumberOfDocumentsToScore; j++)
                {
                    Document document = indexSearcher.Doc(topDocs.scoreDocs[j].doc);

                    float score = topDocs.scoreDocs[j].score;

                    document.Add(new Field("documentid", j.ToString(), Field.Store.YES, Field.Index.NO));
                    document.Add(new Field("relevancyscore", score.ToString(), Field.Store.YES, Field.Index.NO));

                    if (!string.IsNullOrEmpty(sort))
                    {
                        if (shouldDocumentsBeClustered)
                        {
                            if (document.GetField("domain") != null)
                            {
                                string domain = document.GetField("domain").StringValue();

                                if (!domains.ContainsKey(domain))
                                {
                                    domains.Add(domain, null);

                                    if (searchResults.Documents.Count < pageSize && j >= (pageNumber * pageSize) - pageSize)
                                    {
                                        searchResults.Documents.Add(document);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (searchResults.Documents.Count < pageSize && j >= (pageNumber * pageSize) - pageSize)
                            {
                                searchResults.Documents.Add(document);
                            }
                        }
                    }
                    else
                    {
                        priorityQueue.Enqueue(document, score * (double.Parse(document.GetField("strength").StringValue()) + 1));
                    }
                }

                if (string.IsNullOrEmpty(sort))
                {
                    for (int i = 0; i < topDocs.scoreDocs.Length && priorityQueue.Count != 0; i++)
                    {
                        Document document = priorityQueue.Dequeue();

                        if (shouldDocumentsBeClustered)
                        {
                            if (document.GetField("domain") != null)
                            {
                                string domain = document.GetField("domain").StringValue();

                                if (!domains.ContainsKey(domain))
                                {
                                    domains.Add(domain, null);

                                    if (searchResults.Documents.Count < pageSize && i >= (pageNumber * pageSize) - pageSize)
                                    {
                                        searchResults.Documents.Add(document);
                                    }
                                }
                                else
                                {
                                    i--;
                                }
                            }
                        }
                        else
                        {
                            if (searchResults.Documents.Count < pageSize && i >= (pageNumber * pageSize) - pageSize)
                            {
                                searchResults.Documents.Add(document);
                            }
                        }
                    }
                }

                if (shouldDocumentsBeClustered)
                {
                    searchResults.TotalNumberOfHits = domains.Count;
                }
                else
                {
                    searchResults.TotalNumberOfHits = topDocs.totalHits;
                }
            }

            return(searchResults);
        }
Example #32
0
 public ServiceRegistrySettings()
 {
     this.discoveryType = DiscoveryType.Private;
 }