Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks></remarks>
        /// <seealso cref=""/>
        /// <param name="forceReset"></param>
        /// <return></return>
        private void load(bool forceReset = false)
        {
            if (forceReset == true)
            {
                SearchConfig.Reset();
            }
            SearchConfig.LoadConfig();

            this.DefaultSearchModel = initDefault();
            this.WorkingSearchModel = initWorking(); //init(WorkingSearchModel); // its better to make a clone form DefualtSearchModel than calling the function twice
            //this.DefaultSearchModel = Get(this.WorkingSearchModel.CriteriaComponent);
            this.WorkingSearchModel = Get(this.WorkingSearchModel.CriteriaComponent);
        }
Пример #2
0
        /// <summary>
        /// 写入XML
        /// </summary>
        /// <param name="path"></param>
        private void InsertXml(VersionTrack ver)
        {
            XmlConfigInfo xml = new XmlConfigInfo();
            //xml.VersionName = ver.VersionName;
            //xml.PluginInfo = BoFactory.GetVersionTrackBo.GetPluginInfo(ver.PluginCode.ToString());//获取插件信息

            SearchConfig serach = new SearchConfig();

            serach.PluginCode = ver.PluginCode.ToString();
            //xml.configList = BoFactory.GetVersionTrackBo.GetConfigList(serach);//获取配置信息

            CommonMethods.WritePluginfoConfigXml(xml, ver.FilePath.Trim() + @"\" + Constants.pluginName);
        }
    public void Setup()
    {
        TestHelper.CheckEnvironmentVariable();
        SearchClient = new SearchClient(TestHelper.ApplicationId1, TestHelper.AdminKey1);
        SearchConfig configClient2 = new SearchConfig(TestHelper.ApplicationId2, TestHelper.AdminKey2)
        {
            Compression = CompressionType.NONE
        };

        SearchClient2   = new SearchClient(configClient2);
        McmClient       = new SearchClient(TestHelper.McmApplicationId, TestHelper.McmAdminKey);
        AnalyticsClient = new AnalyticsClient(TestHelper.ApplicationId1, TestHelper.AdminKey1);
    }
Пример #4
0
        public static bool RunSearch(string img, ref SearchResult[] res)
        {
            /*
             * Run
             */

            string auth     = SearchConfig.Config.ImgurAuth;
            bool   useImgur = !String.IsNullOrWhiteSpace(auth);

            var engines  = SearchConfig.Config.Engines;
            var priority = SearchConfig.Config.PriorityEngines;

            if (engines == SearchEngines.None)
            {
                //todo
                //CliOutput.WriteError("Please configure search engine preferences!");
                engines = SearchEngines.All;
            }


            // Exit
            if (!IsFileValid(img))
            {
                SearchConfig.Cleanup();

                return(false);
            }

            // Display config
            CliOutput.WriteInfo(SearchConfig.Config);

            string imgUrl = Upload(img, useImgur);

            CliOutput.WriteInfo("Temporary image url: {0}", imgUrl);

            Console.WriteLine();

            //Console.ReadLine();

            //
            // Search
            //


            // Where the actual searching occurs

            var t = StartSearches(imgUrl, engines, ref res);


            return(true);
        }
        public void TestRetryStrategyFailureDecision(CallType callType, int httpErrorCode)
        {
            var           searchConfig  = new SearchConfig("appId", "apiKey");
            RetryStrategy retryStrategy = new RetryStrategy(searchConfig);

            var hosts = retryStrategy.GetTryableHost(callType);

            var decision = retryStrategy.Decide(hosts.ElementAt(0),
                                                new AlgoliaHttpResponse {
                HttpStatusCode = httpErrorCode
            });

            Assert.True(decision.HasFlag(RetryOutcomeType.Failure));
        }
Пример #6
0
        public ActionResult UpdatePluginInfo(string verid)
        {
            ViewData["actionCode"] = "";
            ViewData["summary"]    = "";
            ViewData["IsAction"]   = "";
            SearchVersionTrack search = new SearchVersionTrack();

            search.VID = verid;
            VersionTrack version = BoFactory.GetVersionTrackBo.GetVersionTrack(search)[0];               //获取插件ID

            PluginInfo pinfo = BoFactory.GetVersionTrackBo.GetPluginInfo(version.PluginCode.ToString()); //获取插件信息

            if (pinfo.PluginCateCode.Equals(Constants.ActionCateCode))
            {
                ViewData["IsAction"] = "1";
            }

            IList <PluginCategory> list = BoFactory.GetVersionTrackBo.GetPluginCategoryInfo();//获取非web插件的分类信息

            if (list != null)
            {
                if (list.Count > 0)
                {
                    IResourceData[] datas = new IResourceData[list.Count];
                    for (int i = 0; i < list.Count; i++)
                    {
                        datas[i]      = ResourceDataFactory.GetResourceDataInstance();
                        datas[i].Code = list[i].PluginCateCode;
                        datas[i].Name = list[i].DisplayName;
                    }
                    ViewData["list"] = datas;
                }
            }

            SearchConfig searchconfig = new SearchConfig();

            searchconfig.PluginCode = version.PluginCode.ToString();
            IList <ActionExtend> listAction = BoFactory.GetVersionTrackBo.QueryActionExtend(searchconfig);//获取扩展信息

            if (listAction.Count > 0)
            {
                ViewData["actionCode"] = listAction[0].ActionCode;
                ViewData["summary"]    = listAction[0].Summary;
            }

            ViewData["versionId"] = verid;
            ViewData["vername"]   = version.VersionName;

            return(View(pinfo));
        }
        private static SearchConfig GetAppConfig(string filePath)
        {
            SearchConfig config = new SearchConfig();

            try
            {
                using (StreamReader sr = new StreamReader(filePath))
                {
                    String json = sr.ReadToEnd();
                    config = JsonConvert.DeserializeObject <SearchConfig>(json);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }

            if (string.IsNullOrEmpty(config.CustomerCollectionId))
            {
                throw new ArgumentNullException("CustomerCollectionId is missing from /SearchConfigFile file");
            }

            if (string.IsNullOrEmpty(config.CustomerSearchDataSourceName))
            {
                throw new ArgumentNullException("CustomerSearchDataSourceName is missing from /SearchConfigFile file");
            }

            if (string.IsNullOrEmpty(config.CustomerSearchDataSourceQuery))
            {
                throw new ArgumentNullException("CustomerSearchDataSourceQuery is missing from /SearchConfigFile file");
            }

            if (string.IsNullOrEmpty(config.CustomerSearchIndexName))
            {
                throw new ArgumentNullException("CustomerSearchIndexName is missing from /SearchConfigFile file");
            }

            if (string.IsNullOrEmpty(config.CustomerSearchIndexerName))
            {
                throw new ArgumentNullException("CustomerSearchIndexerName is missing from /SearchConfigFile file");
            }

            if (string.IsNullOrEmpty(config.SearchServiceName))
            {
                throw new ArgumentNullException("SearchServiceName is missing from /SearchConfigFile file");
            }

            return(config);
        }
        /// <param name="args"> Command line arguments: /SearchAdminKey:blah /CosmosConnString:"AccounEndpoint=https://proj-env-shared-cdb.documents.azure.com:443/;AccountKey=secretblah;Database=customers;"  /SearchConfigFile:pathtoblah</param>
        public static void Main(string[] args)
        {
            var    searchAdminKey         = string.Empty;
            string cosmosConnectionString = string.Empty;
            string searchConfigFile       = string.Empty;

            if (args.Length == 0)
            {
                throw (new NotSupportedException("Missing arguments"));
            }

            foreach (var arg in args)
            {
                if (arg.StartsWith("/SearchAdminKey:"))
                {
                    searchAdminKey = arg.Split(':')[1];
                }
                else if (arg.StartsWith("/CosmosConnString:"))
                {
                    cosmosConnectionString = arg.Split(new char[] { ':' }, 2)[1];
                }
                else if (arg.StartsWith("/SearchConfigFile:"))
                {
                    searchConfigFile = arg.Split(':')[1];
                }
                else
                {
                    throw (new NotSupportedException(String.Format("Argument: {0} is invalid", arg)));
                }
            }

            if (String.IsNullOrEmpty(searchAdminKey))
            {
                throw new ArgumentNullException("Check /SearchAdminKey: has a valid value");
            }

            if (String.IsNullOrEmpty(cosmosConnectionString))
            {
                throw new ArgumentNullException("Check /CosmosConnString: has a valid value");
            }

            if (String.IsNullOrEmpty(searchConfigFile))
            {
                throw new ArgumentNullException("Check /SearchConfigFile: is a valid path");
            }

            SearchConfig searchConfig = RunIndex.GetAppConfig(searchConfigFile);

            new CreateCustomerSearchIndex().CreateIndex(searchAdminKey, cosmosConnectionString, searchConfig).GetAwaiter().GetResult();
        }
Пример #9
0
        private string GetQueryCondition(SearchConfig search)
        {
            StringBuilder strsql = new StringBuilder();

            if (!string.IsNullOrEmpty(search.PluginCode))
            {
                strsql.Append(" and PluginCode='" + search.PluginCode + "'");
            }
            if (!string.IsNullOrEmpty(search.status))
            {
                strsql.Append(" and Status ='" + search.status + "'");
            }
            return(strsql.ToString());
        }
Пример #10
0
        public void InitClientsWithoutHttpClient()
        {
            var config = new SearchConfig("AppID", "APIKey");

            Assert.Throws <ArgumentNullException>(() => new SearchClient(config, null));

            var analyticsConfig = new AnalyticsConfig("AppID", "APIKey");

            Assert.Throws <ArgumentNullException>(() => new AnalyticsClient(analyticsConfig, null));

            var insightConfig = new InsightsConfig("AppID", "APIKey");

            Assert.Throws <ArgumentNullException>(() => new InsightsClient(insightConfig, null));
        }
Пример #11
0
        public static async Task <Indexer> GetIndexerFromFile(SearchConfig config)
        {
            using (var reader = new StreamReader($"PipelineJson/{config.IndexerName}.json"))
            {
                var json = await reader.ReadToEndAsync();

                var indexer = JsonConvert.DeserializeObject <Indexer>(json);
                indexer.Name            = config.IndexerName;
                indexer.DataSourceName  = config.DataSourceName;
                indexer.SkillsetName    = config.SkillsetName;
                indexer.TargetIndexName = config.IndexName;
                indexer.Description     = "Search Indexer";

                return(indexer);
            }
        }
Пример #12
0
        private string GetQueryCondition(SearchConfig search, IDictionary dic)
        {
            StringBuilder strsql = new StringBuilder();

            if (!string.IsNullOrEmpty(search.PluginCode))
            {
                strsql.Append(" and PluginCode=@PluginCode");
                dic.Add("PluginCode", search.PluginCode);
            }
            if (!string.IsNullOrEmpty(search.code))
            {
                strsql.Append(" and ActionCode=@ActionCode");
                dic.Add("ActionCode", search.code);
            }
            return(strsql.ToString());
        }
Пример #13
0
        public JsonFlexiGridData QueryUserInfoByPId(SearchConfig search, PageView view)
        {
            string Selectcolumns = "Status,UserUId,UserName,LastLoginIP,LastLoginTime,LastLogoutTime";
            string sqlorder;
            string table = " (select *  from  V_USER_INFO where 1=1  " + GetQueryCondition(search) + ") as temp ";

            if (string.IsNullOrEmpty(view.OrderBy.ToString()))
            {
                sqlorder = " Order by  LastLoginTime asc ";
            }
            else
            {
                sqlorder = view.OrderBy.ToString();
            }
            return(base.QueryDataForFlexGridByPager(Selectcolumns, table, sqlorder, "UserUId", "", view));
        }
Пример #14
0
        public JsonFlexiGridData QueryConfigInfo(PageView view, SearchConfig search)
        {
            string Selectcolumns = "[Key],Value,Summary";
            string sqlorder;

            if (string.IsNullOrEmpty(view.OrderBy.ToString()))
            {
                sqlorder = " Order by  ConfigId asc ";
            }
            else
            {
                sqlorder = view.OrderBy.ToString();
            }
            string parm = GetQueryCondition(search);

            return(base.QueryDataForFlexGridByPager(Selectcolumns, "ConfigInfoPC", sqlorder, "ConfigId", parm, view));
        }
        public void TestRetryStrategyRetriableFailure(CallType callType, int httpErrorCode)
        {
            var           searchConfig  = new SearchConfig("appId", "apiKey");
            RetryStrategy retryStrategy = new RetryStrategy(searchConfig);

            var hosts = retryStrategy.GetTryableHost(callType);

            Assert.True(hosts.Count(h => h.Up) == 4);

            var decision = retryStrategy.Decide(hosts.ElementAt(0), httpErrorCode, false);

            Assert.True(decision.HasFlag(RetryOutcomeType.Retry));

            var updatedHosts = retryStrategy.GetTryableHost(callType);

            Assert.True(updatedHosts.Count(h => h.Up) == 3);
        }
 public static async Task <Indexer> GetBaseIndexer(SearchConfig config) => new Indexer
 {
     Name                = config.IndexerName,
     Description         = "Tweet indexer",
     DataSourceName      = config.DataSourceName,
     SkillsetName        = config.SkillsetName,
     TargetIndexName     = config.IndexName,
     Schedule            = new IndexingSchedule(new TimeSpan(0, 5, 0)),
     OutputFieldMappings = new List <FieldMapping>
     {
         await CognitiveSearchHelper.CreateFieldMapping("/document/people", "people"),
         await CognitiveSearchHelper.CreateFieldMapping("/document/organizations", "organizations"),
         await CognitiveSearchHelper.CreateFieldMapping("/document/locations", "locations"),
         await CognitiveSearchHelper.CreateFieldMapping("/document/keyphrases", "keyphrases"),
         await CognitiveSearchHelper.CreateFieldMapping("/document/language", "language")
     }
 };
Пример #17
0
        public static async Task Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;

            var q  = new ImageQuery(@"C:\Users\Deci\Pictures\fucking_epic.jpg");
            var q2 = new ImageQuery("https://i.imgur.com/QtCausw.jpg");
            var q3 = new ImageQuery(@"C:\Users\Deci\RiderProjects\SmartImage\SmartImage\Test4.png");


            var cfg = new SearchConfig()
            {
                Query = q, SearchEngines = SearchEngineOptions.All
            };

            var cl = new SearchClient(cfg);

            Console.WriteLine("Search 1");

            var   r = cl.RunSearchAsync();
            await r;

            foreach (var result in cl.Results)
            {
                Console.WriteLine(result);
            }

            Console.WriteLine("--");

            var i  = new IqdbEngine();
            var i2 = i.GetResultAsync(q2);
            var r2 = await i2;

            Console.WriteLine(r2);

            cl.Reset();

            Console.WriteLine("Search 2");

            r = cl.RunSearchAsync();
            await r;

            foreach (var result in cl.Results)
            {
                Console.WriteLine(result);
            }
        }
Пример #18
0
        public SearchClient(SearchConfig config)
        {
            //

            EngineOptions = config.SearchEngines;

            SearchEngines = GetAllEngines()
                            .Where(e => EngineOptions.HasFlag(e.Engine))
                            .ToArray();


            UploadEngine = config.UseImgur ? new ImgurClient() : new ImgOpsEngine();

            /*
             *
             */


            var imageInfo = ResolveUploadUrl(config.ImageInput);


            ImageInfo = imageInfo ?? throw new SmartImageException("Image invalid or upload failed");

            OriginalImageResult = FullSearchResult.GetOriginalImageResult(ImageInfo);


            /*
             *
             */

            config.EnsureConfig();

            //

            Results = CreateSearchResults();


            //

            SearchTasks = CreateSearchTasks();

            IsComplete = false;

            //
        }
Пример #19
0
        /// <summary>
        /// 写入XML
        /// </summary>
        /// <param name="path"></param>
        private XmlMainConfigInfo InsertConfigXml(string Vid)
        {
            XmlMainConfigInfo  xml     = new XmlMainConfigInfo();
            SearchVersionTrack searchv = new SearchVersionTrack();
            SearchConfig       serach  = new SearchConfig();

            searchv.VID = Vid;
            VersionTrack v = BoFactory.GetVersionTrackBo.GetVersionTrack(searchv)[0];

            serach.PluginCode = v.PluginCode.ToString();
            IList <ConfigInfoPC> listc = BoFactory.GetVersionTrackBo.GetConfigPCList(serach);//获取配置信息

            xml.configList = listc;

            CommonMethods.WriteMaininfoConfigXml(listc, Path.Combine(v.FilePath.Trim(), Constants.UpdaterName));

            return(xml);
        }
Пример #20
0
        public static async Task Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;
            Console.InputEncoding  = Encoding.Unicode;


            var q  = new ImageQuery(@"C:\Users\Deci\Pictures\Test Images\Test4.png");
            var q2 = new ImageQuery("https://i.imgur.com/QtCausw.jpg");


            var cfg = new SearchConfig()
            {
                Query = q, SearchEngines = SearchEngineOptions.All
            };

            var cl = new SearchClient(cfg);

            cl.ResultCompleted += OnResult;
            var   r = cl.RunSearchAsync();
            await r;

            /*foreach (var result in cl.Results) {
             *      Console.WriteLine(result);
             * }
             *
             * Console.WriteLine("--");
             *
             * var i  = new IqdbEngine();
             * var i2 = i.GetResultAsync(q2);
             * var r2 = await i2;
             *
             * Console.WriteLine(">> {0}",r2);
             *
             * cl.Reset();
             *
             * Console.WriteLine("Search 2");
             *
             * r = cl.RunSearchAsync();
             * await r;
             * foreach (var result in cl.Results)
             * {
             *      Console.WriteLine(result);
             * }*/
        }
Пример #21
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks></remarks>
        /// <seealso cref=""/>
        /// <param>NA</param>
        /// <returns></returns>
        private SearchModel initDefault()
        {
            SearchModel model = new SearchModel();

            //facets
            model.SearchComponent.Facets = SearchConfig.getFacets().ToList();

            //properties
            model.SearchComponent.Properties = new List <Property>(SearchConfig.getProperties());

            //categories
            model.SearchComponent.Categories = new List <Category>(SearchConfig.getCategories());

            //Textvalues
            model.SearchComponent.TextBoxSearchValues = new List <TextValue>();

            return(model);
            //throw new NotImplementedException();
        }
Пример #22
0
        public ViewResult ViewDeviceBind()
        {
            string       mode   = "white";
            SearchConfig search = new SearchConfig();

            search.PluginCode         = Constants.MianName;
            search.ConfigCategoryCode = Constants.SystemConfig;
            search.key = "DeviceBindMode";

            IList <ConfigInfo> listconfigs = BoFactory.GetVersionTrackBo.GetConfigList(search);

            if (listconfigs.Count > 0)
            {
                mode = listconfigs[0].Value1;
            }
            ViewData["Mode"] = mode;

            return(View());
        }
Пример #23
0
        public async Task TestRetryStrategyEndToEnd()
        {
            // Create a index with a valid client
            var indexName = TestHelper.GetTestIndexName("test_retry_e2e");
            var index     = BaseTest.SearchClient.InitIndex(indexName);
            var res       = await index.SaveObjectAsync(new { title = "title" }, autoGenerateObjectId : true);

            res.Wait();

            // Create a client with a bad host to test that the retry worked as expected
            var hosts = new List <StatefulHost>
            {
                // Bad host, will fail with
                // System.Net.Http.HttpRequestException:
                // The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException:
                new StatefulHost
                {
                    Url     = "expired.badssl.com",
                    Up      = true,
                    LastUse = DateTime.UtcNow,
                    Accept  = CallType.Read | CallType.Write,
                },
                new StatefulHost
                {
                    Url     = $"{TestHelper.ApplicationId1}-dsn.algolia.net",
                    Up      = true,
                    LastUse = DateTime.UtcNow,
                    Accept  = CallType.Read | CallType.Write,
                }
            };

            // Warning /!\ Only use search key here /!\
            SearchConfig config = new SearchConfig(TestHelper.ApplicationId1, TestHelper.SearchKey1)
            {
                CustomHosts = hosts
            };
            var client = new SearchClient(config);
            var idx    = client.InitIndex(indexName);

            var search = await idx.SearchAsync <Object>(new Query(""));

            Assert.AreEqual(1, search.NbHits);
        }
Пример #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(AllowCorsPolicy, builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });

            var appInsightsConfig = new AppInsightsConfig
            {
                InstrumentationKey = Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"]
            };

            services.AddSingleton(appInsightsConfig);
            services.AddApplicationInsightsTelemetry(appInsightsConfig.InstrumentationKey);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var searchConfig = new SearchConfig
            {
                ServiceName = Configuration["SearchServiceName"],
                Key         = Configuration["SearchServiceKey"],
                ApiVersion  = Configuration["SearchServiceApiVersion"],
                IndexName   = Configuration["SearchIndexName"]
            };

            services.AddSingleton(searchConfig);

            var storageConfig = new BlobStorageConfig
            {
                AccountName   = Configuration["StorageAccountName"],
                Key           = Configuration["StorageAccountKey"],
                ContainerName = Configuration["StorageAccountContainerName"],
                //FacetsFilteringContainerName = Configuration["FacetsFilteringContainerName"]
                UploadContainerName = Configuration["UploadStorageContainerName"]
            };

            services.AddSingleton(storageConfig);
        }
Пример #25
0
        public ActionResult UpdateConfigInfo(string id)
        {
            ViewData["vid"] = id;
            ArrayList          vids  = GetArrays(id);
            IList <PluginInfo> plist = new List <PluginInfo>();

            ViewData["configList"] = 0;
            foreach (string vid in vids)
            {
                SearchVersionTrack searchv = new SearchVersionTrack();
                searchv.VID = vid;
                id          = BoFactory.GetVersionTrackBo.GetVersionTrack(searchv)[0].PluginCode.ToString();
                PluginInfo p = BoFactory.GetVersionTrackBo.GetPluginInfo(id);
                p.VersionSummary = BoFactory.GetVersionTrackBo.GetVersionTrack(searchv)[0].VersionSummary;
                SearchConfig search = new SearchConfig();
                if (p.IsIgnoreConfig == false)
                {
                    search.PluginCode         = id;
                    search.ConfigCategoryCode = Constants.configCategory;
                    p.configList = BoFactory.GetVersionTrackBo.GetConfigList(search);
                }
                if (p.PluginCateCode.Equals(Constants.ActionCateCode))
                {
                    search.PluginCode = id;
                    IList <ActionExtend> alist = BoFactory.GetVersionTrackBo.QueryActionExtend(search);
                    if (alist.Count > 0)
                    {
                        ActionExtend a = alist[0];
                        p.ActionCode    = a.ActionCode;
                        p.ActionSummary = a.Summary;
                    }
                }
                SearchPlugin sh = new SearchPlugin();
                sh.PluginCateCode = p.PluginCateCode;
                p.PCname          = BoFactory.GetVersionTrackBo.GetPluginCategoryInfos(sh)[0].DisplayName;

                plist.Add(p);


                ViewData["configList"] = (int)ViewData["configList"] + p.configList.Count;
            }
            return(View(plist));
        }
Пример #26
0
        /*************************************/

        private static void ShowWithConstraint(SearchConfig config)
        {
            if (config != null)
            {
                m_SearchMenu.PossibleItems = m_PossibleItems.Select(x =>
                {
                    SearchItem withWeight = x.ShallowClone() as SearchItem;
                    withWeight.Weight     = withWeight.Weight(config);
                    return(withWeight);
                }).Where(x => x.Weight > 0).ToList();
            }
            else
            {
                m_SearchMenu.PossibleItems = m_PossibleItems;
            }

            m_SearchMenu.HitsOnEmptySearch = config != null;
            m_SearchMenu.ShowResults("");
        }
Пример #27
0
        public JsonFlexiGridData QueryUserInfoNotByPId(SearchConfig search, SearchVersionTrack search1, PageView view)
        {
            string Selectcolumns = "UserUId,Gender,UserName";
            string sqlorder;
            string table = @" (select userinfo.* from userinfo left join (select b.*  from userpluginref as c ,userinfo as b 
                            where  c.useruid=b.useruid " + GetQueryCondition(search) + @") as d
                            on d.useruid=userinfo.useruid  where d.useruid is null " + GetQueryConditions(search1) + ") as temp ";

            if (string.IsNullOrEmpty(view.OrderBy.ToString()))
            {
                sqlorder = " Order by  CreateTime asc ";
            }
            else
            {
                sqlorder = view.OrderBy.ToString();
            }

            return(base.QueryDataForFlexGridByPager(Selectcolumns, table, sqlorder, "UserUId", "", view));
        }
Пример #28
0
        public ViewResult ViewDeviceBind2(string pageIndex, string uid, string desc, string mode, string state)
        {
            //string mode = "white";
            SearchConfig search = new SearchConfig();

            search.PluginCode         = Constants.MianName;
            search.ConfigCategoryCode = Constants.SystemConfig;
            search.key = "DeviceBindMode";

            IList <ConfigInfo> listconfigs = BoFactory.GetVersionTrackBo.GetConfigList(search);

            if (listconfigs.Count > 0)
            {
                mode = listconfigs[0].Value1;
            }
            ViewData["Mode"] = mode;

            int page = 1;

            if (!String.IsNullOrEmpty(pageIndex))
            {
                page = Convert.ToInt32(pageIndex) + 1;
            }
            var fc = new FormCollection();

            fc.Add("page", page.ToString());
            fc.Add("rp", "10");
            fc.Add("sortname", "UserUid");
            fc.Add("query", "");
            fc.Add("qtype", "");

            JsonFlexiGridData    r          = (JsonFlexiGridData)SearchDeviceBind(fc, uid, desc, state).Data;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonStr = serializer.Serialize(r);

            ViewData["data"] = jsonStr;


            return(View());
        }
Пример #29
0
        private static async Task CreateAnomalyDetectionPipeline(SearchServiceClient searchClient, AppConfig appConfig)
        {
            var searchConfig = new SearchConfig
            {
                DataSourceName = "telemetry-datasource",
                IndexName      = "telemetry-index",
                IndexerName    = "telemetry-indexer",
                SkillsetName   = "telemetry-skillset"
            };

            var dataSource = await CognitiveSearchHelper.GetOrCreateCosmosDataSource(searchClient, searchConfig.DataSourceName, DataSourceType.CosmosDb, appConfig.CosmosDb);

            Console.WriteLine($"Successfully created data source {searchConfig.DataSourceName}");

            var index = await CognitiveSearchHelper.GetIndexFromFile(searchConfig.IndexName);

            var indexer = await CognitiveSearchHelper.GetIndexerFromFile(searchConfig);

            var skillset = new Skillset
            {
                Name              = searchConfig.SkillsetName,
                Description       = "Anomaly detection skills",
                CognitiveServices = new CognitiveServicesByKey(appConfig.CognitiveServices.Key, appConfig.CognitiveServices.ResourceId),
                Skills            = new List <Skill>()
            };

            Console.WriteLine("Adding Custom Anomaly Detector skill to pipeline");
            AddCustomAnomalyDetectorSkill(ref index, ref indexer, ref skillset, appConfig);

            await CognitiveSearchHelper.CreateCognitiveSearchPipeline(searchClient, appConfig.Search, index, indexer, skillset)
            .ContinueWith(t =>
            {
                Console.WriteLine(t.IsFaulted
                        ? t.Exception.Message
                        : "Your anomaly detection pipeline was successfully created.");
            });

            Console.WriteLine("");
            Console.WriteLine("");
        }
        public ActionResult Search(SearchConfig searchConfig)
        {
            User      user    = (User)Session["User"];
            VkService service = new VKServiseImpl();

            if (searchConfig.GroupDomain != null)
            {
                List <VKPost> posts = service.GetVkPostByDomain(searchConfig.GroupDomain, searchConfig.Size, user);
                ViewBag.VKposts = posts;
                log.Info("User gets posts  by GroupDomain.");
                return(View("SearchResults"));
            }
            else if (searchConfig.GroupId != 0)
            {
                List <VKPost> posts = service.GetVkPostById(searchConfig.GroupId, searchConfig.Size, user);
                ViewBag.VKposts = posts;
                log.Info("User gets posts  by GroupId.");
                return(View("SearchResults"));
            }
            log.Error("Not valid SearchResults.");
            return(View("NotValidSearch"));
        }
Пример #31
0
        /// <summary>
        /// Do unit selection.
        /// </summary>
        /// <param name="searchConfig">Search configuration.</param>
        /// <returns>The best path.</returns>
        public List<PathNodeInfo> UnitSelecting(SearchConfig searchConfig)
        {
            ILatticeProvider latticeProvider = searchConfig.LatticeProvider;
            ITargetCostCalculator targetCostCalculator = searchConfig.TargetCostCalculator;
            IJoinCalculator joinCostCalculator = searchConfig.JoinCostCalculator;

            int targetCount = latticeProvider.GetColumnCount();
            if (targetCount == 0)
            {
                string message = Helper.NeutralFormat("The ILatticeProvider contains 0 targets!");
                throw new InvalidDataException(message);
            }

            List<PathNodeInfo> bestPath = new List<PathNodeInfo>(targetCount);

            TargetNode[] targets = new TargetNode[targetCount];
            LatticeNode[][] lattice = new LatticeNode[targetCount][];

            for (int i = 0; i < targetCount; i++)
            {
                int candidateCount = latticeProvider.GetRowCount(i);
                if (candidateCount == 0)
                {
                    string message = Helper.NeutralFormat("The ILatticeProvider contains 0 candidates for target {0}!", i);
                    throw new InvalidDataException(message);
                }

                targets[i] = new TargetNode(latticeProvider.GetTarget(i), candidateCount);

                lattice[i] = new LatticeNode[candidateCount];
                for (int j = 0; j < candidateCount; j++)
                {
                    PathNodeInfo pathNodeInfo = new PathNodeInfo(latticeProvider.GetCandidate(i, j), float.PositiveInfinity, float.PositiveInfinity);
                    lattice[i][j] = new LatticeNode(pathNodeInfo, float.PositiveInfinity, -1);
                }
            }

            for (int i = 0; i < targets[0].CandidateCount; i++)
            {
                LatticeNode nodeCur = lattice[0][i];

                float targetCost = targetCostCalculator.GetTargetCost(targets[0].Target, nodeCur.PathNodeInfo.Candidate);
                nodeCur.BestScore = targetCost;

                nodeCur.PathNodeInfo.TargetCost = targetCost;
            }

            for (int col = 1; col < targetCount; col++)
            {
                TargetNode targetCur = targets[col];
                TargetNode targetLeft = targets[col - 1];

                for (int i = 0; i < targetCur.CandidateCount; i++)
                {
                    LatticeNode nodeCur = lattice[col][i];

                    LatticeNode nodeLeft = lattice[col - 1][0];
                    float joinCost = joinCostCalculator.GetJoinCost(targetLeft.Target, targetCur.Target,
                        nodeLeft.PathNodeInfo.Candidate, nodeCur.PathNodeInfo.Candidate);
                    float bestPreScore = nodeLeft.BestScore + joinCost;
                    int bestPreNodeIndex = 0;
                    float bestJoinCost = joinCost;

                    for (int j = 1; j < targets[col - 1].CandidateCount; j++)
                    {
                        nodeLeft = lattice[col - 1][j];
                        joinCost = joinCostCalculator.GetJoinCost(targetLeft.Target, targetCur.Target,
                            nodeLeft.PathNodeInfo.Candidate, nodeCur.PathNodeInfo.Candidate);
                        float preCost = nodeLeft.BestScore + joinCost;
                        if (preCost < bestPreScore)
                        {
                            bestPreScore = preCost;
                            bestPreNodeIndex = j;
                            bestJoinCost = joinCost;
                        }
                    }

                    float targetCost = targetCostCalculator.GetTargetCost(targetCur.Target, nodeCur.PathNodeInfo.Candidate);
                    nodeCur.BestScore = bestPreScore + targetCost;
                    nodeCur.BestPreNodeIndex = bestPreNodeIndex;

                    nodeCur.PathNodeInfo.TargetCost = targetCost;
                    nodeCur.PathNodeInfo.JoinCost = bestJoinCost;
                }
            }

            int columnIndex = targetCount - 1;
            LatticeNode bestNode = lattice[columnIndex][0];
            float bestScore = bestNode.BestScore;
            for (int i = 1; i < targets[columnIndex].CandidateCount; i++)
            {
                LatticeNode curNode = lattice[columnIndex][i];
                if (curNode.BestScore < bestScore)
                {
                    bestNode = curNode;
                    bestScore = bestNode.BestScore;
                }
            }

            while (true)
            {
                bestPath.Add(bestNode.PathNodeInfo);
                columnIndex--;
                if (columnIndex < 0)
                {
                    break;
                }

                bestNode = lattice[columnIndex][bestNode.BestPreNodeIndex];
            }

            bestPath.Reverse();

            return bestPath;
        }
 public void TestPutIdentity()
 {
     string jsonRpcCallId = "2767c2bc-6e83-4cba-9b60-5b874dbadb2a";
     RogerthatSystem.PutIdentityRequest request = new RogerthatSystem.PutIdentityRequest();
     request.AppData = "{\"xmpp_room\": \"chatroom1\"}";
     Beacon beacon = new Beacon();
     beacon.Uuid = "110E8400-E29B-11D4-A716-446655440000";
     beacon.Major = "123";
     beacon.Minor = "987";
     beacon.Tag = "Meeting room 1";
     request.Beacons.Add(beacon);
     request.Description = "This is your personal fully customizable Rogerthat service identity.";
     request.DescriptionBranding = null;
     request.DescriptionBrandingUseDefault = false;
     request.EmailStatistics = false;
     request.EmailStatisticsUseDefault = false;
     request.Identifier = "i1";
     request.MenuBranding = null;
     request.MenuBrandingUseDefault = false;
     request.AdminEmails.Add("*****@*****.**");
     request.AdminEmails.Add("*****@*****.**");
     request.Name = "My cool service identity";
     request.PhoneCallPopup = null;
     request.PhoneCallPopupUseDefault = false;
     request.PhoneNumber = "+32 9 324 25 64";
     request.PhoneNumberUseDefault = false;
     request.QualifiedIdentifier = "*****@*****.**";
     request.RecommendEnabled = true;
     SearchConfig sc = new SearchConfig();
     sc.Enabled = true;
     sc.Keywords = "test example cool new";
     SearchLocation sl = new SearchLocation();
     sl.Address = "Antwerpsesteenweg 19, 9080 Lochristi";
     sl.Latitude = 51092000;
     sl.Longitude = 3820000;
     sc.Locations.Add(sl);
     request.SearchConfig = sc;
     request.SearchUseDefault = false;
     RogerthatSystem.PutIdentityResponse response = this.Api.PutIdentity(request, jsonRpcCallId);
     Assert.IsNotNull(response);
 }
Пример #33
0
        private static IList<ItemInfo> fetchProspects(SearchConfig search)
        {
            // get rarities
            IList<Rarity> rarities = new RarityListRequest().Execute().Results;

            // get types
            IList<ItemType> types = new TypeListRequest().Execute().Results;

            // get all armors that i want to sell
            IList<ItemInfo> items = new FullItemListRequest().Execute()
                    .Results
                    .Where(i =>
                        (search.Types.Count == 0 ?
                                true :
                                types.Where(t => search.Types.Contains(t.Name)).Select(t => t.Id).Contains(i.TypeId)))
                    .Where(i =>
                        (search.Rarities.Count == 0 ?
                                true :
                                rarities.Where(r => search.Rarities.Contains(r.Name)).Select(r => r.Id).Contains(i.Rarity)))
                    .Where(i =>
                        (search.MaximumLevel < 0 ?
                                true :
                                i.RestrictionLevel <= search.MaximumLevel) &&
                        (search.MinimumLevel < 0 ?
                                true :
                                i.RestrictionLevel >= search.MinimumLevel))
                    .Where(i => i.OfferAvailability > 0 && i.SaleAvailability > 0)
                    .Select<ItemData, ItemInfo>(a => ItemInfo.FromItemData(a, rarities, types))
                    .Where(a =>
                        (search.MinimumProfitMargin < 0 ?
                                true :
                                (search.MarginIsPercent ? a.ProfitMargin >= a.BuyPrice * (search.MinimumProfitMargin / 100.0) : a.ProfitMargin >= search.MinimumProfitMargin)))
                    .OrderBy(a => a.BuyPrice)
                    .ToList();

            return items;
        }
Пример #34
0
        public static void Main(string[] args)
        {
            HotKeyHandler hotKeyHandler = new HotKeyHandler();

            SearchConfig searchConfig;
            SearchConfig defaultSearchConfig = new SearchConfig(
                    ConfigurationManager.AppSettings["Type"],
                    ConfigurationManager.AppSettings["Rarity"],
                    ConfigurationManager.AppSettings["Minimum Level"],
                    ConfigurationManager.AppSettings["Maximum Level"],
                    ConfigurationManager.AppSettings["Minimum Profit Margin"],
                    ConfigurationManager.AppSettings["Copper Value"]);
            string type, rarity, minLevel, maxLevel, minProfitMargin, copperValue;

            Console.WriteLine("Gathering search data:");
            Console.Write("  Type [{0}]: ",
                    (defaultSearchConfig.Types.Count == 0 ? "*" : string.Join(",", defaultSearchConfig.Types)));
            type = Console.ReadLine();
            Console.Write("  Rarity [{0}]: ",
                    (defaultSearchConfig.Rarities.Count == 0 ? "*" : string.Join(",", defaultSearchConfig.Rarities)));
            rarity = Console.ReadLine();
            Console.Write("  Minimum Level [{0}]: ", defaultSearchConfig.MinimumLevel);
            minLevel = Console.ReadLine();
            Console.Write("  Maximum Level [{0}]: ", defaultSearchConfig.MaximumLevel);
            maxLevel = Console.ReadLine();
            Console.Write("  Minimum Profit Margin [{0}]: ",
                    (defaultSearchConfig.MarginIsPercent ?
                            defaultSearchConfig.MinimumProfitMargin + "%" :
                            defaultSearchConfig.MinimumProfitMargin.ToString("#### ## #0").Trim()));
            minProfitMargin = Console.ReadLine().Replace(" ", string.Empty);
            Console.Write("  Copper Value [{0}]: ", defaultSearchConfig.CopperValue);
            copperValue = Console.ReadLine();

            searchConfig = new SearchConfig(type, rarity, minLevel, maxLevel, minProfitMargin, copperValue, defaultSearchConfig);

            // load overlay handler
            OverlayHandler.Initialize();

            Console.WriteLine("Pulling prospects for the following data:");
            Console.WriteLine("  Type: {0}",
                    (searchConfig.Types.Count == 0 ? "*" : string.Join(",", searchConfig.Types)));
            Console.WriteLine("  Rarity: {0}",
                    (searchConfig.Rarities.Count == 0 ? "*" : string.Join(",", searchConfig.Rarities)));
            Console.WriteLine("  Minimum Level: {0}", searchConfig.MinimumLevel);
            Console.WriteLine("  Maximum Level: {0}", searchConfig.MaximumLevel);
            Console.WriteLine("  Minimum Profit Margin: {0}",
                    (searchConfig.MarginIsPercent ?
                            searchConfig.MinimumProfitMargin + "%" :
                            searchConfig.MinimumProfitMargin.ToString("#### ## #0").Trim()));
            Console.WriteLine("  Copper Value: {0}", searchConfig.CopperValue);
            Console.WriteLine("  Order by: Buy price, ascending");

            Console.Write("Grabbing prospects: ");
            IList<ItemInfo> prospects = new List<ItemInfo>();

            try
            {
                prospects = fetchProspects(searchConfig);
                ok();
            }
            catch (Exception)
            {
                error();
                Console.WriteLine("  There was a problem communicating with Gw2Spidy. The website may be offline.");
            }

            if (prospects.Count > 0)
            {
                Console.WriteLine("Found {0} prospects. Press any key to view the next result (Esc to exit):", prospects.Count);
                Console.WriteLine("{0} {1,-10} {2,-10} [{3,-10}] {4}", " ", "Sell", "Buy", "Margin", "Name");

                hotKeyHandler.CopperValue = searchConfig.CopperValue;
                hotKeyHandler.RegisterHotKeys();

                foreach (ItemInfo item in prospects)
                {
                    Console.WriteLine(string.Format("{0} {1,10} {2,10} [{3,10}] {4}",
                            ((searchConfig.CopperValue == (int)(item.BuyPrice % 100) || searchConfig.CopperValue == (int)(item.SellPrice)) ? "*" : " "),
                            item.SellPrice.ToString("#### ## #0").Trim(),
                            item.BuyPrice.ToString("#### ## #0").Trim(),
                            item.ProfitMargin.ToString("#### ## #0").Trim(),
                            item.Name));

                    hotKeyHandler.CurrentItem = item;

                    // load item into overlay
                    OverlayHandler.LoadItem(
                            item,
                            (searchConfig.CopperValue == (int)(item.BuyPrice % 100) ? 1 :
                            (searchConfig.CopperValue == (int)(item.SellPrice % 100) ? 3  : 0)));

                    SpinWait.SpinUntil(() => Console.KeyAvailable || hotKeyHandler.CurrentItem == null);

                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo key = Console.ReadKey(true);
                        if (key.Key == ConsoleKey.Escape)
                            break;
                    }
                }

                hotKeyHandler.UnregisterHotKeys();
            }
            else
            {
                Console.WriteLine("Found 0 prospects. Press any key to exit.");
                Console.ReadKey(true);
            }
        }
Пример #35
0
            public SearchConfig(string types, string rarities, string minLevel, string maxLevel, string minProfitMargin, string copperValue, SearchConfig defaults = null)
            {
                if (string.IsNullOrWhiteSpace(types))
                    this.Types = (defaults == null ? new List<string>() : defaults.Types);
                else
                {
                    this.Types = new List<string>();

                    if (types != "*")
                    {
                        foreach (string type in types.Split(','))
                        {
                            if (!string.IsNullOrWhiteSpace(type))
                                this.Types.Add(type.Trim());
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(rarities))
                    this.Rarities = (defaults == null ? new List<string>() : defaults.Rarities);
                else
                {
                    this.Rarities = new List<string>();

                    if (rarities != "*")
                    {
                        foreach (string rarity in rarities.Split(','))
                        {
                            if (!string.IsNullOrWhiteSpace(rarity))
                                this.Rarities.Add(rarity.Trim());
                        }
                    }
                }

                if (!int.TryParse(minLevel, out this.MinimumLevel))
                    this.MinimumLevel = (defaults == null ? 0 : defaults.MinimumLevel);

                if (!int.TryParse(maxLevel, out this.MaximumLevel))
                    this.MaximumLevel = (defaults == null ? 80 : defaults.MaximumLevel);

                this.MarginIsPercent = false;
                if (!int.TryParse(minProfitMargin, out this.MinimumProfitMargin))
                {
                    this.MinimumProfitMargin = (defaults == null ? -1 : defaults.MinimumProfitMargin);

                    if (minProfitMargin.EndsWith("%"))
                    {
                        this.MarginIsPercent = true;
                        if (!int.TryParse(minProfitMargin.Substring(0, minProfitMargin.Length - 1), out this.MinimumProfitMargin))
                        {
                            this.MinimumProfitMargin = (defaults == null ? -1 : defaults.MinimumProfitMargin);
                        }
                    }
                }

                if (!int.TryParse(copperValue, out this.CopperValue))
                    this.CopperValue = (defaults == null ? -1 : defaults.CopperValue);
            }