public static Boolean exportResults(ResultList resultList,String filePath){ if (resultList == null) { Console.WriteLine("result list is null"); return false; } try { System.IO.StreamWriter tsvFile = new System.IO.StreamWriter(filePath); //tsvFile.WriteLine(resultList.getType()) foreach (Result result in resultList) { foreach (Paper paper in result.getResults()){ tsvFile.WriteLine(paper.toString('\t')); } } tsvFile.Close(); return true; } catch { } return false; }
public static Boolean exportResults(ResultList resultList) { StringBuilder filePath = new StringBuilder("Export_"); filePath.Append(getTimestamp(DateTime.Now)); filePath.Append(".tsv"); return exportResults(resultList, filePath.ToString()); }
public ResultList GSsearch(Query query) { //String queryURL = querybuilder.getURL //Result = parser.getResult //Dummy Results ResultList resultList = new ResultList(); GSParser parser = new GSParser(); resultList = parser.GSbuildQuery(query); /* Paper paper = new Paper(); paper.settitle("A hybrid feature set based maximum entropy Hindi named entity recognition"); paper.setdescription("hsjkasdhkjshjsak"); paper.seturl(new Uri("http://google.co.in")); paper.setauthors("S Dandapat, S Sarkar, A Basu - Proceedings of the International …, 2004 - pdf.aminer.org"); paper.setcitationsUrl("skhadkjshadksjdhkj"); result.addPaper(paper); result.addPaper(paper); result.addPaper(paper); result.addPaper(paper); * */ return resultList; // // return null; //TODO }
public ResultList MSASsearch(Query query) { ResultList resultList = new ResultList(); MSASParser parser = new MSASParser(); resultList = parser.MSASbuildQuery(query); return resultList; }
public ResultList MSASsearchCitationUrl(String url) { ResultList resultList = new ResultList(); MSASParser parser = new MSASParser(); Console.WriteLine(url); Uri URL = new Uri(url); resultList = parser.MSASConnectFetch(URL); return resultList; }
public void ResultList_Constructor_Default_HasErrorsIsFalse() { //------------Setup for test-------------------------- //------------Execute Test--------------------------- var resultList = new ResultList<string>(); //------------Assert Results------------------------- Assert.IsNotNull(resultList.Items); Assert.IsFalse(resultList.HasErrors); Assert.IsNull(resultList.Errors); }
public void ResultList_Constructor_ExceptionIsNull_HasErrorsIsTrue() { //------------Setup for test-------------------------- //------------Execute Test--------------------------- var resultList = new ResultList<string>((Exception)null); //------------Assert Results------------------------- Assert.IsNotNull(resultList.Items); Assert.IsTrue(resultList.HasErrors); Assert.AreEqual("", resultList.Errors); }
public void ResultList_Constructor_ErrorFormatWithArgs_HasErrorsIsTrue() { //------------Setup for test-------------------------- //------------Execute Test--------------------------- var resultList = new ResultList<string>("Hello {0}", "world"); //------------Assert Results------------------------- Assert.IsNotNull(resultList.Items); Assert.IsTrue(resultList.HasErrors); Assert.AreEqual("Hello world", resultList.Errors); }
public ResultList GSsearchCitationUrl(String url) { ResultList resultList = new ResultList(); GSParser parser = new GSParser(); url = "http://scholar.google.co.in" + url; var citationUrl = new Uri(url); int i; for (i = 0; i < 10; i += 10) { Result result = new Result(); String newURL; newURL = citationUrl + "&start=" + i.ToString(); var newUrl = new Uri(newURL); Console.WriteLine(newUrl); resultList.Add(parser.GSConnect(newUrl)); } return resultList; }
public async Task Should_return_multiple_assets_with_total_when_querying_assets_with_total() { const string query = @" query { queryAssetsWithTotal(filter: ""my-query"", top: 30, skip: 5) { total items { id version created createdBy lastModified lastModifiedBy url thumbnailUrl sourceUrl mimeType fileName fileHash fileSize fileVersion isImage isProtected pixelWidth pixelHeight type metadataText metadataPixelWidth: metadata(path: ""pixelWidth"") metadataUnknown: metadata(path: ""unknown"") metadata tags slug } } }"; var asset = CreateAsset(Guid.NewGuid()); A.CallTo(() => assetQuery.QueryAsync(MatchsAssetContext(), null, A <Q> .That.Matches(x => x.ODataQuery == "?$top=30&$skip=5&$filter=my-query"))) .Returns(ResultList.CreateFrom(10, asset)); var result = await sut.QueryAsync(requestContext, new GraphQLQuery { Query = query }); var expected = new { data = new { queryAssetsWithTotal = new { total = 10, items = new dynamic[] { new { id = asset.Id, version = 1, created = asset.Created, createdBy = "subject:user1", lastModified = asset.LastModified, lastModifiedBy = "subject:user2", url = $"assets/{asset.Id}", thumbnailUrl = $"assets/{asset.Id}?width=100", sourceUrl = $"assets/source/{asset.Id}", mimeType = "image/png", fileName = "MyFile.png", fileHash = "ABC123", fileSize = 1024, fileVersion = 123, isImage = true, isProtected = false, pixelWidth = 800, pixelHeight = 600, type = "IMAGE", metadataText = "metadata-text", metadataPixelWidth = 800, metadataUnknown = (string?)null, metadata = new { pixelWidth = 800, pixelHeight = 600 }, tags = new[] { "tag1", "tag2" }, slug = "myfile.png" } } } } }; AssertResult(expected, result); }
private void _worker_DoWork(object sender, DoWorkEventArgs e) { try { var eventArgs = e.Argument as ApiEventArgs; if (eventArgs != null) { var apiHandler = new ApiHandler(); if (!String.IsNullOrWhiteSpace(eventArgs.ProduktId)) { var produkt = apiHandler.SucheEinzelnenArtikel(eventArgs.Datenbank, eventArgs.ApiToken, eventArgs.ProduktId); ResultProduktString += produkt.Data.Produkt.Kategorie.Title.Trim() + Environment.NewLine; ResultProduktString += produkt.Data.Produkt.Manufacturer.Name.Trim() + Environment.NewLine; ResultProduktString += produkt.Data.Produkt.Name.Trim() + Environment.NewLine; if (!string.IsNullOrWhiteSpace(produkt.Data.Produkt.Groesse)) { ResultProduktString += produkt.Data.Produkt.Groesse.Trim() + Environment.NewLine; } else { ResultProduktString += Environment.NewLine; } if (!string.IsNullOrWhiteSpace(produkt.Data.Produkt.Jahr)) { ResultProduktString += produkt.Data.Produkt.Jahr.Trim() + Environment.NewLine; } else { ResultProduktString += Environment.NewLine; } var converter = new Converter.IntToWeightConverter(); ResultProduktString += converter.Convert((int)produkt.Data.Produkt.Gewicht, null, null, null); ResultProduktLink = produkt.Data.Produkt.Url.Trim(); e.Result = true; } else if (string.IsNullOrWhiteSpace(eventArgs.HerstellerId) && string.IsNullOrWhiteSpace(eventArgs.KategorieId)) { ResultHerstellerDto = apiHandler.GetHerstellerListe(eventArgs.Datenbank, eventArgs.ApiToken); var resultDto = apiHandler.GetKategorienListe(eventArgs.Datenbank, eventArgs.ApiToken); KonvertiereKategorien(resultDto); e.Result = true; } else { bool herstellerMitnehmen = !string.IsNullOrWhiteSpace(eventArgs.HerstellerId); bool kategorienMitnehmen = !string.IsNullOrWhiteSpace(eventArgs.KategorieId); var produkteHersteller = new ResponseProduktListeDto(); var produkteKategorie = new ResponseProduktListeDto(); if (herstellerMitnehmen) { produkteHersteller = apiHandler.SucheArtikel(eventArgs.Datenbank, eventArgs.ApiToken, eventArgs.HerstellerId, true); } if (kategorienMitnehmen && !herstellerMitnehmen) { produkteKategorie = apiHandler.SucheArtikel(eventArgs.Datenbank, eventArgs.ApiToken, eventArgs.KategorieId, false); } if (herstellerMitnehmen && kategorienMitnehmen) { foreach (var item in produkteHersteller.Data.Produkte) { if (item.Produkt.Kategorie.Id == eventArgs.KategorieId) { var viewModel = new DatenbankteilAuswahlViewModel { Komponente = item.Produkt.Kategorie.Title, Hersteller = item.Produkt.Manufacturer.Name, DatenbankLink = item.Produkt.Url, DatenbankId = eventArgs.Datenbank + ":" + item.Produkt.Id, Beschreibung = item.Produkt.Name, Gewicht = (int)item.Produkt.Gewicht, Groesse = item.Produkt.Groesse, Jahr = item.Produkt.Jahr }; ResultList.Add(viewModel); } } } else if (herstellerMitnehmen) { foreach (var item in produkteHersteller.Data.Produkte) { var viewModel = new DatenbankteilAuswahlViewModel { Komponente = item.Produkt.Kategorie.Title, Hersteller = item.Produkt.Manufacturer.Name, DatenbankLink = item.Produkt.Url, DatenbankId = eventArgs.Datenbank + ":" + item.Produkt.Id, Beschreibung = item.Produkt.Name, Gewicht = (int)item.Produkt.Gewicht, Groesse = item.Produkt.Groesse, Jahr = item.Produkt.Jahr }; ResultList.Add(viewModel); } } else { foreach (var item in produkteKategorie.Data.Produkte) { var viewModel = new DatenbankteilAuswahlViewModel { Komponente = item.Produkt.Kategorie.Title, Hersteller = item.Produkt.Manufacturer.Name, DatenbankLink = item.Produkt.Url, DatenbankId = eventArgs.Datenbank + ":" + item.Produkt.Id, Beschreibung = item.Produkt.Name, Gewicht = (int)item.Produkt.Gewicht, Groesse = item.Produkt.Groesse, Jahr = item.Produkt.Jahr }; ResultList.Add(viewModel); } } e.Result = true; } } } catch (Exception ex) { e.Result = false; ErrorText = ex.Message; } }
public async Task Should_return_multiple_assets_when_querying_assets() { const string query = @" query { queryAssets(filter: ""my-query"", top: 30, skip: 5) { id version created createdBy lastModified lastModifiedBy url thumbnailUrl sourceUrl mimeType fileName fileHash fileSize fileVersion isImage pixelWidth pixelHeight tags slug } }"; var asset = CreateAsset(Guid.NewGuid()); A.CallTo(() => assetQuery.QueryAsync(MatchsAssetContext(), A <Q> .That.Matches(x => x.ODataQuery == "?$top=30&$skip=5&$filter=my-query"))) .Returns(ResultList.Create(0, asset)); var result = await sut.QueryAsync(context, new GraphQLQuery { Query = query }); var expected = new { data = new { queryAssets = new dynamic[] { new { id = asset.Id, version = 1, created = asset.Created, createdBy = "subject:user1", lastModified = asset.LastModified, lastModifiedBy = "subject:user2", url = $"assets/{asset.Id}", thumbnailUrl = $"assets/{asset.Id}?width=100", sourceUrl = $"assets/source/{asset.Id}", mimeType = "image/png", fileName = "MyFile.png", fileHash = "ABC123", fileSize = 1024, fileVersion = 123, isImage = true, pixelWidth = 800, pixelHeight = 600, tags = new string[] { "tag1", "tag2" }, slug = "myfile.png" } } } }; AssertResult(expected, result); }
public JsonResult SearchList() { #region 权限控制 int[] iRangePage = { ListPageNodeId, ListPageFNodeId }; int iCurrentPageNodeId = RequestParameters.Pint("NodeId"); var tempAuth = Utits.IsNodePageAuth(iRangePage, iCurrentPageNodeId); if (tempAuth.ErrorType != 1) { return(Json(tempAuth)); } #endregion //当前页 int iCurrentPage = RequestParameters.Pint("currentPage"); iCurrentPage = iCurrentPage <= 0 ? 1 : iCurrentPage; //索引页 int iPageIndex = iCurrentPage - 1; //一页的数量 int iPageSize = RequestParameters.Pint("pageSize"); iPageSize = iPageSize <= 0 ? 5 : iPageSize; iPageSize = iPageSize > 100 ? 100 : iPageSize; //总记录数量 int iTotalRecord = 0; #region 查询条件 var searchCondition = new ConditionModel(); var WhereList = new List <WhereCondition>(); var UserName = RequestParameters.Pstring("UserName"); if (UserName.Length > 0) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "UserName"; whereCondition.FieldValue = UserName; whereCondition.FieldOperator = EnumOper.Contains; WhereList.Add(whereCondition); } var RealName = RequestParameters.Pstring("RealName"); if (RealName.Length > 0) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "RealName"; whereCondition.FieldValue = RealName; whereCondition.FieldOperator = EnumOper.Contains; WhereList.Add(whereCondition); } var RoleID = RequestParameters.PGuidNull("RoleID"); if (RoleID != null) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "RoleID"; whereCondition.FieldValue = RoleID.Value; whereCondition.FieldOperator = EnumOper.Equal; WhereList.Add(whereCondition); } var DeptID = RequestParameters.PGuidNull("DeptID"); if (DeptID != null) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "DeptID"; whereCondition.FieldValue = DeptID; whereCondition.FieldOperator = EnumOper.Equal; WhereList.Add(whereCondition); } var UserType = RequestParameters.PintNull("UserType"); if (UserType != null) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "UserType"; whereCondition.FieldValue = UserType; whereCondition.FieldOperator = EnumOper.Equal; WhereList.Add(whereCondition); } var super = Config.UserNameSuper; if (super.Length > 0) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "UserName"; whereCondition.FieldValue = super; whereCondition.FieldOperator = EnumOper.ExclamationEqual; WhereList.Add(whereCondition); } var welfareCentreId = Utits.WelfareCentreID; if (welfareCentreId != null) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "WelfareCentreID"; whereCondition.FieldValue = welfareCentreId; whereCondition.FieldOperator = EnumOper.Equal; WhereList.Add(whereCondition); } var IsValid = RequestParameters.PintNull("IsValid"); if (IsValid != null) { if (IsValid == 1) { var whereCondition = new WhereCondition(); whereCondition.FieldName = "IsValid"; whereCondition.FieldValue = IsValid; whereCondition.FieldOperator = EnumOper.Equal; WhereList.Add(whereCondition); } else { var whereCondition = new WhereCondition(); whereCondition.FieldName = "IsValid"; whereCondition.FieldValue = 1; whereCondition.FieldOperator = EnumOper.ExclamationEqual; WhereList.Add(whereCondition); } } searchCondition.WhereList = WhereList; var OrderList = new List <OrderCondition>(); var sortfield = RequestParameters.Pstring("sortfield"); if (sortfield.Length <= 0) { sortfield = "OperateDate"; } var orderCondition = new OrderCondition(); orderCondition.FiledOrder = sortfield; orderCondition.Ascending = RequestParameters.Pstring("sorttype") == "asc" ? true : false; OrderList.Add(orderCondition); searchCondition.OrderList = OrderList; #endregion var cBll = new UsersBll(); var list = cBll.SearchVByPageCondition(iPageIndex, iPageSize, ref iTotalRecord, searchCondition); iPageSize = iPageSize == 0 ? iTotalRecord : iPageSize; int pageCount = iTotalRecord % iPageSize == 0 ? iTotalRecord / iPageSize : iTotalRecord / iPageSize + 1; var sReturnModel = new ResultList(); sReturnModel.ErrorType = 1; sReturnModel.CurrentPage = iCurrentPage; sReturnModel.PageSize = iPageSize; sReturnModel.TotalRecord = iTotalRecord; sReturnModel.PageCount = pageCount; sReturnModel.Data = list; return(Json(sReturnModel, JsonRequestBehavior.AllowGet)); }
private void Citation_DoWork(object sender, DoWorkEventArgs e) { Console.WriteLine("Thread started"); /* data d = (data)e.Argument; BackgroundWorker b = sender as BackgroundWorker; test = new Controller(this); resultList = test.initiateSearch(d); Console.WriteLine("why dis kolaveri"); //TabPage tab = new TabPage(mw); */ soid s = (soid)e.Argument; int id = s.i; SortOrder so = s.sOrder; int start = s.start; resultList = test.getMSASCitations(s); if (s.c.CancellationPending) e.Cancel = true; }
public void ResultList_ToString_Json() { //------------Setup for test-------------------------- var resultList = new ResultList<string>("Hello"); var expected = JsonConvert.SerializeObject(resultList); //------------Execute Test--------------------------- var actual = resultList.ToString(); //------------Assert Results------------------------- Assert.AreEqual(expected, actual); }
public async Task Should_return_multiple_assets_with_total_when_querying_assets_with_total() { const string query = @" query { queryAssetsWithTotal(search: ""my-query"", take: 30, skip: 5) { total items { id version created createdBy lastModified lastModifiedBy url thumbnailUrl sourceUrl mimeType fileName fileSize fileVersion isImage pixelWidth pixelHeight } } }"; var asset = CreateAsset(Guid.NewGuid()); A.CallTo(() => assetQuery.QueryAsync(MatchsAssetContext(), A <Q> .That.Matches(x => x.ODataQuery == "?$take=30&$skip=5&$search=my-query"))) .Returns(ResultList.Create(10, asset)); var result = await sut.QueryAsync(context, new GraphQLQuery { Query = query }); var expected = new { data = new { queryAssetsWithTotal = new { total = 10, items = new dynamic[] { new { id = asset.Id, version = 1, created = asset.Created.ToDateTimeUtc(), createdBy = "subject:user1", lastModified = asset.LastModified.ToDateTimeUtc(), lastModifiedBy = "subject:user2", url = $"assets/{asset.Id}", thumbnailUrl = $"assets/{asset.Id}?width=100", sourceUrl = $"assets/source/{asset.Id}", mimeType = "image/png", fileName = "MyFile.png", fileSize = 1024, fileVersion = 123, isImage = true, pixelWidth = 800, pixelHeight = 600 } } } } }; AssertResult(expected, result); }
private async Task <IResultList <IEnrichedContentEntity> > TransformAsync(Context context, IResultList <IContentEntity> contents) { var transformed = await TransformCoreAsync(context, contents); return(ResultList.Create(contents.Total, transformed)); }
public async Task <ResultList <NotificationRespone> > ImportExcelFile(string ID, IFormFile formFile, string messageParagraph, string userLoggedInID, string totalVarible) { ResultList <NotificationRespone> result = new ResultList <NotificationRespone> (); if (formFile == null || formFile.Length <= 0) { result.Status = 3; result.Message = "No data found"; return(result); } if (!Path.GetExtension(formFile.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) { result.Status = 1; result.Message = "No data found"; return(result); } HttpResponseMessage res = new HttpResponseMessage(); if (res.IsSuccessStatusCode) { Req.ClientId = "7001044523"; } Req.ClientAuthorization = "kGB4B72DBmAvulfzTFQkbvmHvZlEXYY91wuFBU3v4jE="; Req.SubmitId = ID; ParamType param1 = new ParamType(); ParamType param2 = new ParamType(); ParamType param3 = new ParamType(); var list = new List <MessageVaribles> (); var list = new List <NotificationRespone> (); var ErrorMsgList = new List <NotificationFault> (); using (var stream = new MemoryStream()) { await formFile.CopyToAsync(stream, cancellationToken); await formFile.CopyToAsync(stream); using (var package = new ExcelPackage(stream)) { var ErrorMsg = new NotificationFault(); try { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; int rowCount = worksheet.Dimension.Rows; int ColCount = worksheet.Dimension.Columns; var RecipientsList = new List <RecipientType> (); for (int row = 2; row <= rowCount; row++) { Recipients = new RecipientType(); Recipients.Language = "AR"; Recipients.NationalOrIqamaId = Convert.ToString(worksheet.Cells[row, 1].Value); string rowValue = Convert.ToString(worksheet.Cells[row, 1].Value); if (rowValue.Length < 10) { result.Status = 1; result.Message = "الرجاء التأكد من البيانات حيث أنه أقل من 10 أرقام " + rowValue; break; } else { Recipients.NationalOrIqamaId = rowValue; List <ParamType> ParamList = new List <ParamType> (); var allColwithoutFirstCol = ColCount - 1; if (totalVarible == allColwithoutFirstCol.ToString()) { if (totalVarible == "0") { RecipientsList.Add(Recipients); Req.Recipients = RecipientsList.ToArray(); var sys_result = _ SmsNotificationService.SubmitRequest(Req); } else { int i = 1; ParamType param = new ParamType(); for (int col = 2; col <= ColCount; col++) { string h = Convert.ToString(worksheet.Cells[1, col].Value); param = new ParamType(); param.Name = "VAR0" + i.ToString(); string str = Convert.ToString(worksheet.Cells[row, col].Value); Match match = Regex.Match(str, @"[~`!#$%^&*+=|{}';<>?[\]""]", RegexOptions.IgnoreCase); if (!match.Success) { param.Value = str; ParamList.Add(param); i++; } else { result.Message = "الرجاء التأكد من المحتوى حيث يوجد رمز لايمكن ارساله ( " + match + " )"; result.Status = 1; return(result); } } Recipients.Params = ParamList.ToArray(); RecipientsList.Add(Recipients); } } else { result.Message = allColwithoutFirstCol + "لابد أن يكون عدد المتغييرات"; result.Message = "توجد مشكلة لايمكن الارسال عدد متغييرات الرسالة غير متناسب مع عدد الأعمدة بالملف المرفق. الرجاء التأكد من أن عدد المتغييرات لابد أن يساوي عدد الأعمدة بالملف المرفق ليتناسب مع قالب الارسال"; result.Status = 1; return(result); } } Req.Recipients = RecipientsList.ToArray(); var sys_result = _ SmsNotificationService.SubmitRequest(Req); if (sys_result != null) { ResponceSubmitReq resEnity = new ResponceSubmitReq(); resEnity.BatchStatus = sys_result.Status.ToString(); resEnity.BatchNumber = sys_result.BatchNumber; resEnity.MessageParagraph = messageParagraph; resEnity.SubmitID = ID; resEnity.CreatedBy = HttpContext.User.Identity.Name; await _ ResponceSubmitReqDomain.Insert(resEnity); list.Add(sys_result); result.List = list; result.Status = 0; result.Message = "OK"; return(result); } else { result.Status = 1; result.Message = "Error in Data"; return(result); } } catch (Exception ex) { if (ex.Message == "Client does not exists") { ErrorMsg.ErrorCode = "20001"; ErrorMsg.ErrorMessage = "العميل غير مسجل "; result.Message = ErrorMsg.ErrorMessage + " رقم الخطاء : " + ErrorMsg.ErrorCode; result.Status = 1; } else if (ex.Message == "Client is Inactive") { ErrorMsg.ErrorCode = "20002"; ErrorMsg.ErrorMessage = "العميل غير مفعل "; result.Message = ErrorMsg.ErrorMessage + " رقم الخطاء : " + ErrorMsg.ErrorCode; result.Status = 1; } else if (ex.Message == "Submit does not exists.") { ErrorMsg.ErrorCode = "20003"; ErrorMsg.ErrorMessage = "تم اختيار قالب غير صحيح "; result.Message = ErrorMsg.ErrorMessage + " رقم الخطاء : " + ErrorMsg.ErrorCode; result.Status = 1; } else if (ex.Message == "Submit Parameters are inconsistent with request parameters") { ErrorMsg.ErrorCode = "10003"; ErrorMsg.ErrorMessage = "تم اختيار قالب غير متوافق "; result.Message = ErrorMsg.ErrorMessage + " رقم الخطاء : " + ErrorMsg.ErrorCode; result.Status = 1; } else if (ex.Message == "Language incorrect") { ErrorMsg.ErrorCode = "20004"; ErrorMsg.ErrorMessage = "تم اختيار لغة غير صحيحة "; result.Message = ErrorMsg.ErrorMessage + " رقم الخطاء : " + ErrorMsg.ErrorCode; result.Status = 1; } else if (ex.Message == "Any of the date is missing or empty") { ErrorMsg.ErrorCode = "20005"; ErrorMsg.ErrorMessage = "أحد البيانات مفقود أو لايوجد "; result.Message = ErrorMsg.ErrorMessage + " رقم الخطاء : " + ErrorMsg.ErrorCode; result.Status = 1; //return result; } else { result.Message = " مشكلة من مزود الخدمة توجد مشكلة لايمكن الارسال عدد متغييرات الرسالة غير متناسب مع عدد الأعمدة بالملف المرفق. الرجاء التأكد من أن عدد المتغييرات لابد أن يساوي عدد الأعمدة بالملف المرفق ليتناسب مع قالب الارسال، أو الملف الذي تم ارفاقه يحتوي على رقم هوية أو اقامة غير صحيح "; result.Status = 1; } } } } return(result); }
private async Task planning() { if (SourceText.Selected == null) { new MessageDialog(App.Common.Services.Resources.LocalizedStringOf("PlanningSourceEmpty")).ShowAsync(); return; } if (TargetText.Selected == null) { new MessageDialog(App.Common.Services.Resources.LocalizedStringOf("PlanningTargetEmpty")).ShowAsync(); return; } var source = SourceText.Selected; var target = TargetText.Selected; var pickedDateTime = DateTimePicker.Time; App.UB.History.AddPlanningHistory(source, true); App.UB.History.AddPlanningHistory(target, false); ResultList.ItemsSource().Clear(); ResultBorder.Height = 0; ProgressBar.IsIndeterminate = true; await App.TB.UsingFiles; Stopwatch watch = Stopwatch.StartNew(); await Task.Run(() => { try { App.Planner.SetParams(new PlanningArgs { Type = DateTimePicker.TimeType, EnabledTypes = Convert(new bool[] { PlanSettingsModel.TramAllowed, PlanSettingsModel.MetroAllowed, PlanSettingsModel.UrbanTrainAllowed, PlanSettingsModel.BusAllowed, true, true, true, true }), OnlyWheelchairAccessibleTrips = PlanSettingsModel.WheelchairAccessibleTrips, OnlyWheelchairAccessibleStops = PlanSettingsModel.WheelchairAccessibleStops, LatitudeDegreeDistance = App.Config.LatitudeDegreeDistance, LongitudeDegreeDistance = App.Config.LongitudeDegreeDistance, WalkSpeedRate = PlanSettingsModel.WalkingSpeed / 3.6 * 60 }); } catch (Exception e) { Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => new MessageDialog(App.Common.Services.Resources.LocalizedStringOf("PlanningError")).ShowAsync()); } }); IEnumerable <PlanningAspect> aspects = new PlanningAspect[] { PlanningAspect.Time, PlanningAspect.TransferCount, PlanningAspect.WalkDistance }; //aspects = aspects.Take(App.Config.PlanningAspectsCount); //aspects = aspects.Take(1); await Task.WhenAll(aspects.Select(async aspect => { MiddleWay middleResult = await Task.Run(() => { try { return(App.Planner.CalculatePlanning(source.ID, target.ID, pickedDateTime.ToString(CultureInfo.InvariantCulture), aspect)); } catch (Exception e) { Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => new MessageDialog(App.Common.Services.Resources.LocalizedStringOf("PlanningError")).ShowAsync()); return(null); } }); if (middleResult != null) { //new MessageDialog(middleResult.Message).ShowAsync(); Way result = createWay(middleResult, PlanSettingsModel.WalkingSpeedInMps); var resultList = ResultList.ItemsSource as ObservableCollection <WayModel>; if (resultList.All(x => !x.Way.Equals(result))) { int i = 0; while (i < resultList.Count && resultList[i].Way < result) { i++; } resultList.Insert(i, new WayModel(result, source, target, pickedDateTime)); ResultBorder.Height = double.NaN; } } })); ProgressBar.IsIndeterminate = false; if (ResultList.ItemsSource().Count == 0) { new MessageDialog(App.Common.Services.Resources.LocalizedStringOf("PlanningNoResult")).ShowAsync(); } else { TimeText.Text = string.Format("{0} ({1:0.##} sec)", App.Common.Services.Resources.LocalizedStringOf("PlanningTimeLabel"), watch.ElapsedMilliseconds / 1000.0); await Task.Delay(3000); TimeText.Text = ""; } }
public async Task <IResultList <IAssetEntity> > QueryAsync(DomainId appId, DomainId?parentId, Q q, CancellationToken ct = default) { using (Profiler.TraceMethod <MongoAssetRepository>("QueryAsyncByQuery")) { try { if (q.Ids != null && q.Ids.Count > 0) { var filter = BuildFilter(appId, q.Ids.ToHashSet()); var assetEntities = await Collection.Find(filter).SortByDescending(x => x.LastModified).ThenBy(x => x.Id) .QueryLimit(q.Query) .QuerySkip(q.Query) .ToListAsync(ct); long assetTotal = assetEntities.Count; if (q.NoTotal) { assetTotal = -1; } else if (assetEntities.Count >= q.Query.Take || q.Query.Skip > 0) { assetTotal = await Collection.Find(filter).CountDocumentsAsync(ct); } return(ResultList.Create(assetTotal, assetEntities.OfType <IAssetEntity>())); } else { var query = q.Query.AdjustToModel(appId); var filter = query.BuildFilter(appId, parentId); var assetEntities = await Collection.Find(filter) .QueryLimit(query) .QuerySkip(query) .QuerySort(query) .ToListAsync(ct); long assetTotal = assetEntities.Count; if (q.NoTotal) { assetTotal = -1; } else if (assetEntities.Count >= q.Query.Take || q.Query.Skip > 0) { assetTotal = await Collection.Find(filter).CountDocumentsAsync(ct); } return(ResultList.Create <IAssetEntity>(assetTotal, assetEntities)); } } catch (MongoQueryException ex) when(ex.Message.Contains("17406")) { throw new DomainException(T.Get("common.resultTooLarge")); } } }
public Task <ResultList <AppointmentCoreModel> > List(FilterModel model) => ResultList <AppointmentCoreModel> .TryAsync(async() => { var isAdmin = generalDataService.User.Permissions.Any(p => p == (int)PermissionType.Admin); var appointmentes = new List <Appointment>(); if (isAdmin) { appointmentes = (await _repository.ListAsNoTrackingAsync <Appointment>(i => (model.DateTime == null || model.DateTime.Value.ToString("d") == i.Date.ToString("d")) && (string.IsNullOrEmpty(model.Keyword) || model.Keyword == i.Title), a => a.Invoice)) .Data ?.ToList(); } else { appointmentes = (await _repository.ListAsNoTrackingAsync <Appointment>(i => i.UserId == generalDataService.User.Id && (model.DateTime == null || model.DateTime.Value.ToString("d") == i.Date.ToString("d")) && (string.IsNullOrEmpty(model.Keyword) || model.Keyword == i.Title), a => a.Invoice)) .Data ?.ToList(); } if (appointmentes == null) { return(ResultList <AppointmentCoreModel> .Failed(Error.WithCode(ErrorCodes.NotFound))); } var users = (await _membershipServiceApi.SystemUserApiService.ListByIds(appointmentes .Select(a => a.UserId) .Union(appointmentes .Select(a => a.RepresentativeId != null ? a.RepresentativeId.Value : Guid.Empty) .Where(a => a != Guid.Empty)).ToList())).Data; var appointmentModels = appointmentes.Select(appointment => new AppointmentCoreModel { Id = appointment.Id, Title = appointment.Title, Description = appointment.Description, User = users.FirstOrDefault(u => u.Id == appointment.UserId), Representative = users.FirstOrDefault(u => u.Id == appointment.RepresentativeId), CreationDate = appointment.CreationDate, Date = appointment.Date, Type = appointment.Type, Duration = appointment.Duration, Invoice = appointment.Invoice != null ? new InvoiceCoreModel { Id = appointment.Invoice.Id, Amount = appointment.Invoice.Amount, Enabled = appointment.Invoice.Enabled, CreationDate = appointment.Invoice.CreationDate, Description = appointment.Invoice.Description, Title = appointment.Invoice.Title } : null, Approved = appointment.Approved }).OrderBy(a => a.CreationDate).Reverse().ToList(); return(ResultList <AppointmentCoreModel> .Successful(appointmentModels)); });
public ResultList MSASbuildQuery(Query query) { MSASQueryURLBuilder MSB = new MSASQueryURLBuilder(); String URL = MSB.buildQuery(query); this.query = query; var strUrl = new Uri(URL); Console.WriteLine(URL); this.resultList.resultType = query.resultType; this.resultList.loadType(); this.resultList = MSASConnectFetch(strUrl); return this.resultList; }
public async Task Should_also_fetch_union_contents_when_field_is_included_in_query() { var contentRefId = Guid.NewGuid(); var contentRef = CreateRefContent(schemaRefId1, contentRefId, "ref1-field", "ref1"); var contentId = Guid.NewGuid(); var content = CreateContent(contentId, contentRefId, Guid.Empty); var query = @" query { findMySchemaContent(id: ""<ID>"") { id data { myUnion { iv { ... on Content { id } ... on MyRefSchema1 { data { ref1Field { iv } } } __typename } } } } }".Replace("<ID>", contentId.ToString()); A.CallTo(() => contentQuery.QueryAsync(MatchsContentContext(), A <IReadOnlyList <Guid> > .Ignored)) .Returns(ResultList.CreateFrom(0, contentRef)); A.CallTo(() => contentQuery.QueryAsync(MatchsContentContext(), MatchId(contentId))) .Returns(ResultList.CreateFrom(1, content)); var result = await sut.QueryAsync(requestContext, new GraphQLQuery { Query = query }); var expected = new { data = new { findMySchemaContent = new { id = content.Id, data = new { myUnion = new { iv = new[] { new { id = contentRefId, data = new { ref1Field = new { iv = "ref1" } }, __typename = "MyRefSchema1" } } } } } } }; AssertResult(expected, result); }
public HttpResponseMessage GetEntitaByPartialName(string text, string type, int start, int limit) { ResponseType <Item> response = new ResponseType <Item>(); if (String.IsNullOrEmpty(text) || string.IsNullOrEmpty(type)) { this.Request.CreateResponse <ResponseType <Item> >(HttpStatusCode.OK, response); } start = (start == 0) ? ++start : start; IList <EntitaType> filtro = new List <EntitaType>(); KeyValuePair <FastIndexedAttributes, string> matchingString = new KeyValuePair <FastIndexedAttributes, string>(); IndexedCatalogs catalogo; try { List <string> types = type.Split(':').ToList(); string tipoRicerca = types.First(); catalogo = (IndexedCatalogs)Enum.Parse(typeof(IndexedCatalogs), types.Last()); var f = from t in types where types.IndexOf(t) != 0 && types.IndexOf(t) != (types.Count - 1) select(EntitaType) Enum.Parse(typeof(EntitaType), t); if (f.Count() != 0) { filtro = f.ToList(); } matchingString = new KeyValuePair <FastIndexedAttributes, string>( (FastIndexedAttributes)Enum.Parse(typeof(FastIndexedAttributes), tipoRicerca), text); } catch { response.message = "Errore: la stringa di ricerca è mal formata"; response.totale = 0; response.Items = null; return(this.Request.CreateResponse <ResponseType <Item> >(HttpStatusCode.OK, response)); } ResultList <SimpleResultItem> res = null; try { ContattoService service = new ContattoService(); res = service.GetFieldsByParams(catalogo, filtro, matchingString, start, limit); if (res == null || res.List.Count == 0) { response.message = "la ricerca non ha prodotto risultati"; response.totale = 0; response.Items = null; return(this.Request.CreateResponse <ResponseType <Item> >(HttpStatusCode.OK, response)); } response.totale = res.Totale; response.Items = (from i in res.List select new SendMail.Model.WebserviceMappings.Item { Id = string.Format("{0}#{1}", i.Value, (res.List as List <SimpleResultItem>).IndexOf(i)), Title = i.Text, Text = i.Description, Subtype = i.SubType }).ToList(); response.success = bool.TrueString; response.message = ""; } catch (Exception e) { response.message = "Errore: " + e.Message; } return(this.Request.CreateResponse <ResponseType <Item> >(HttpStatusCode.OK, response)); }
public async Task Should_return_single_content_when_finding_content() { var contentId = Guid.NewGuid(); var content = CreateContent(contentId, Guid.Empty, Guid.Empty); var query = @" query { findMySchemaContent(id: ""<ID>"") { id version created createdBy lastModified lastModifiedBy status statusColor url data { myString { de } myNumber { iv } myBoolean { iv } myDatetime { iv } myJson { iv } myGeolocation { iv } myTags { iv } myLocalized { de_DE } } } }".Replace("<ID>", contentId.ToString()); A.CallTo(() => contentQuery.QueryAsync(MatchsContentContext(), MatchId(contentId))) .Returns(ResultList.CreateFrom(1, content)); var result = await sut.QueryAsync(requestContext, new GraphQLQuery { Query = query }); var expected = new { data = new { findMySchemaContent = new { id = content.Id, version = 1, created = content.Created, createdBy = "subject:user1", lastModified = content.LastModified, lastModifiedBy = "subject:user2", status = "DRAFT", statusColor = "red", url = $"contents/my-schema/{content.Id}", data = new { myString = new { de = "value" }, myNumber = new { iv = 1 }, myBoolean = new { iv = true }, myDatetime = new { iv = content.LastModified }, myJson = new { iv = new { value = 1 } }, myGeolocation = new { iv = new { latitude = 10, longitude = 20 } }, myTags = new { iv = new[] { "tag1", "tag2" } }, myLocalized = new { de_DE = "de-DE" } } } } }; AssertResult(expected, result); }
protected override void OnAdded(int collectionIndex, int index, TSource value) => ResultList.Add(_concatIndex + index, value);
public void OnceMore() { ResultList.Add(new Tuple <decimal, Account, string>(PartialAmount, PartialArticle, PartialComment)); ChangeAllProperties(); }
protected override void OnRemoved(int collectionIndex, int index, TSource value) => ResultList.Remove(_concatIndex + index);
/// <summary> /// Called when [convert]. /// </summary> /// <param name="dataForProcessing">The data for processing.</param> /// <returns>Unprocessed, incomplete packet</returns> private string OnConvert(string dataForProcessing) { if (_log.IsInfoEnabled) { _log.InfoFormat("{0}--string for processing: {1}", MethodBase.GetCurrentMethod().ToString(), dataForProcessing); } string retVal = string.Empty; //Could have multiple packets: need to code to handle. //Packet p = new Packet(me.RawData); //How Data looks from Wireshark: //ef:be:ad:de:8c:00:00:00:01:00:00:00:00:00:00:00:78:00:00:00:da:b3:04:6d:70:00:00:00:59:6f:75:20:68:61:76:65:20:63:6f:6e:6e:65:63:74:65:64:20:74:6f:20:54:68:6f:6d:20:52:6f:62:65:72:74:73:6f:6e:27:73:20:41:72:74:65:6d:69:73:20:42:72:69:64:67:65:20:53:69:6d:75:6c:61:74:6f:72:2e:20:20:50:6c:65:61:73:65:20:63:6f:6e:6e:65:63:74:20:77:69:74:68:20:61:6e:20:61:75:74:68:6f:72:69:7a:65:64:20:67:61:6d:65:20:63:6c:69:65:6e:74:2e //2222 List <byte> byteArray = new List <byte>(ConvertToByteArray(dataForProcessing)); //byteArray is now total message--need to parse out multiple messages. int ln = 0; List <byte> workArray = null; int startIndex = 0; do { ln = Packet.GetLength(byteArray.ToArray(), startIndex); if (byteArray.Count < startIndex + ln) { break; } if (_log.IsInfoEnabled) { _log.InfoFormat("Start--creating new packet. Length determined: {0}", ln.ToString()); } if (startIndex + ln > byteArray.Count) { ln = byteArray.Count - startIndex; } workArray = new List <byte>(); for (int i = startIndex; i < startIndex + ln; i++) { workArray.Add(byteArray[i]); } Packet p = new Packet(workArray.ToArray()); bool ignore = false; if (_log.IsInfoEnabled) { _log.InfoFormat("Packet Created, length of byte array: {0}", workArray.Count.ToString()); } if (FilterPackets && p.PacketType == PacketTypes.ObjectStatusUpdatePacket) { ObjectStatusUpdatePacket objP = p.Package as ObjectStatusUpdatePacket; if (objP != null && objP.SubPacketType == ArtemisComm.ObjectStatusUpdateSubPackets.ObjectStatusUpdateSubPacketTypes.UnknownSubPacket) { ignore = true; } } if (!ignore) { GetPropertyInformation(Result, p, p.PacketType.ToString(), 0); PropertyValue pv = new PropertyValue("----------", "-----------", "-----------", "-----------"); Result.Add(pv); } startIndex += ln; } while (startIndex < byteArray.Count - ArtemisComm.Packet.HeaderLength); if (startIndex < byteArray.Count) { List <string> elem = new List <string>(); for (int i = startIndex; i < byteArray.Count; i++) { elem.Add(byteArray[i].ToString("X")); } retVal = string.Join(":", elem.ToArray()); } ResultList.ScrollIntoView(ResultList.Items[Result.Count - 1]); System.Media.SystemSounds.Beep.Play(); return(retVal); }
protected override void OnReplaced(int collectionIndex, int index, TSource oldValue, TSource newValue) => ResultList.Replace(_concatIndex + index, newValue);
public async Task Should_return_multiple_contents_with_total_when_querying_contents_with_total() { const string query = @" query { queryMySchemaContentsWithTotal(top: 30, skip: 5) { total items { id version created createdBy lastModified lastModifiedBy status url data { myString { de } myNumber { iv } myBoolean { iv } myDatetime { iv } myJson { iv } myGeolocation { iv } myTags { iv } myLocalized { de_DE } } } } }"; var content = CreateContent(Guid.NewGuid(), Guid.Empty, Guid.Empty); A.CallTo(() => contentQuery.QueryAsync(MatchsContentContext(), schemaId.ToString(), A <Q> .That.Matches(x => x.ODataQuery == "?$top=30&$skip=5"))) .Returns(ResultList.Create(10, content)); var result = await sut.QueryAsync(context, new GraphQLQuery { Query = query }); var expected = new { data = new { queryMySchemaContentsWithTotal = new { total = 10, items = new dynamic[] { new { id = content.Id, version = 1, created = content.Created, createdBy = "subject:user1", lastModified = content.LastModified, lastModifiedBy = "subject:user2", status = "DRAFT", url = $"contents/my-schema/{content.Id}", data = new { myString = new { de = "value" }, myNumber = new { iv = 1 }, myBoolean = new { iv = true }, myDatetime = new { iv = content.LastModified }, myJson = new { iv = new { value = 1 } }, myGeolocation = new { iv = new { latitude = 10, longitude = 20 } }, myTags = new { iv = new[] { "tag1", "tag2" } }, myLocalized = new { de_DE = "de-DE" } } } } } } }; AssertResult(expected, result); }
protected override void OnMoved(int collectionIndex, int oldIndex, int newIndex, TSource value) => ResultList.Move(_concatIndex + oldIndex, _concatIndex + newIndex);
public async Task Should_return_multiple_flat_contents_when_querying_contents() { const string query = @" query { queryMySchemaContents(top: 30, skip: 5) { id version created createdBy lastModified lastModifiedBy status statusColor url flatData { myString myNumber myBoolean myDatetime myJsonValue: myJson(path: ""value"") myJson myGeolocation myTags myLocalized myArray { nestedNumber nestedBoolean } } } }"; var content = CreateContent(Guid.NewGuid(), Guid.Empty, Guid.Empty); A.CallTo(() => contentQuery.QueryAsync(MatchsContentContext(), schemaId.Id.ToString(), A <Q> .That.Matches(x => x.ODataQuery == "?$top=30&$skip=5"))) .Returns(ResultList.CreateFrom(0, content)); var result = await sut.QueryAsync(requestContext, new GraphQLQuery { Query = query }); var expected = new { data = new { queryMySchemaContents = new dynamic[] { new { id = content.Id, version = 1, created = content.Created, createdBy = "subject:user1", lastModified = content.LastModified, lastModifiedBy = "subject:user2", status = "DRAFT", statusColor = "red", url = $"contents/my-schema/{content.Id}", flatData = new { myString = "value", myNumber = 1, myBoolean = true, myDatetime = content.LastModified, myJsonValue = 1, myJson = new { value = 1 }, myGeolocation = new { latitude = 10, longitude = 20 }, myTags = new[] { "tag1", "tag2" }, myLocalized = "de-DE", myArray = new[] { new { nestedNumber = 10, nestedBoolean = true }, new { nestedNumber = 20, nestedBoolean = false } } } } } } }; AssertResult(expected, result); }
protected override void OnReset(int collectionIndex, IReadOnlyList <TSource> newItems) => ResultList.ReplaceRange(_concatIndex, Count - _concatIndex, newItems);
public async Task Should_return_single_asset_when_finding_asset() { var assetId = Guid.NewGuid(); var asset = CreateAsset(assetId); var query = @" query { findAsset(id: ""<ID>"") { id version created createdBy lastModified lastModifiedBy url thumbnailUrl sourceUrl mimeType fileName fileHash fileSize fileVersion isImage pixelWidth pixelHeight tags slug } }".Replace("<ID>", assetId.ToString()); A.CallTo(() => assetQuery.QueryAsync(MatchsAssetContext(), null, MatchIdQuery(assetId))) .Returns(ResultList.CreateFrom(1, asset)); var result = await sut.QueryAsync(requestContext, new GraphQLQuery { Query = query }); var expected = new { data = new { findAsset = new { id = asset.Id, version = 1, created = asset.Created, createdBy = "subject:user1", lastModified = asset.LastModified, lastModifiedBy = "subject:user2", url = $"assets/{asset.Id}", thumbnailUrl = $"assets/{asset.Id}?width=100", sourceUrl = $"assets/source/{asset.Id}", mimeType = "image/png", fileName = "MyFile.png", fileHash = "ABC123", fileSize = 1024, fileVersion = 123, isImage = true, pixelWidth = 800, pixelHeight = 600, tags = new[] { "tag1", "tag2" }, slug = "myfile.png" } } }; AssertResult(expected, result); }
protected override void OnAdded(int index, TSource value) { ++_concatIndex; ResultList.Add(index, value); }
public MSASParser() { resultList = new ResultList(); }
public void ResultList_Constructor_ExceptionIsNotNull_HasErrorsIsTrue() { //------------Setup for test-------------------------- var ex = new Exception("Error Occurred", new Exception("Inner Error")); //------------Execute Test--------------------------- var resultList = new ResultList<string>(ex); //------------Assert Results------------------------- Assert.IsNotNull(resultList.Items); Assert.IsTrue(resultList.HasErrors); Assert.AreEqual("Error Occurred\r\nInner Error\r\n", resultList.Errors); }
public ResultList MSASConnectFetch(Uri URL) { WebClient wc = new WebClient(); wc.Proxy = WebProxy.GetDefaultProxy(); ResultList resList = new ResultList(); var data = " "; try { data = wc.DownloadString(URL); //Console.WriteLine(data); } catch (Exception e) { //TabPage.displayError("MS Also blocking Dude !!! YY !!!!"); return null; } JObject obj = JObject.Parse(data); int paperCount = 0; if (obj["d"]["Publication"]["Result"].Count() == 0) { //TabPage.displayError("No Results"); return null; } int total = (int)obj["d"]["Publication"]["TotalItem"]; Console.WriteLine("sdfsd" + total); resList.setCount(total); while (paperCount < obj["d"]["Publication"]["Result"].Count()) { Result result = new Result(); Paper p = new Paper(); String title = (String)obj["d"]["Publication"]["Result"][paperCount]["Title"]; p.settitle(title); String content = (String)obj["d"]["Publication"]["Result"][paperCount]["Abstract"]; p.setdescription(content); int authorCount = 0; String authors = ""; while (authorCount < obj["d"]["Publication"]["Result"][paperCount]["Author"].Count() && authorCount < 5) { authors += (String)obj["d"]["Publication"]["Result"][paperCount]["Author"][authorCount]["FirstName"] + " "; if ((String)obj["d"]["Publication"]["Result"][paperCount]["Author"][authorCount]["MiddleName"] != "") authors += (String)obj["d"]["Publication"]["Result"][paperCount]["Author"][authorCount]["MiddleName"] + " " + (String)obj["d"]["Publication"]["Result"][paperCount]["Author"][authorCount]["LastName"] + " , "; else authors += (String)obj["d"]["Publication"]["Result"][paperCount]["Author"][authorCount]["LastName"] + " , "; authorCount++; } p.setYear((int)obj["d"]["Publication"]["Result"][paperCount]["Year"]); p.setauthors(authors); //if (obj["d"]["Publication"]["Result"][paperCount]["Conference"] != null) // p.setConferenceUrl(((String)(obj["d"]["Publication"]["Result"][paperCount]["Conference"][0]))); int citations = Convert.ToInt32((String)obj["d"]["Publication"]["Result"][paperCount]["CitationCount"]); p.setnumCitations(citations); String url = ""; if (obj["d"]["Publication"]["Result"][paperCount]["FullVersionURL"].Count() > 0) { url = (String)obj["d"]["Publication"]["Result"][paperCount]["FullVersionURL"][0]; } if (url != "") { Uri titleURL = new Uri(url); p.seturl(titleURL); } else { p.seturl(null); } int id = (int)obj["d"]["Publication"]["Result"][paperCount]["ID"]; p.setid(id); paperCount++; result.addPaper(p); resList.Add(result); } return resList; }
public ResultList getGSCitations(String url) { Searcher searcher = new Searcher(); ResultList resultList = new ResultList(); resultList = searcher.GSsearchCitationUrl(url); return resultList; //tab.setResult(resultList); }
public void setResult(ResultList resultList) { this.ResultsPane.Items.Clear(); firstSearchFlag = 1; if (newResultFlag == 1 && resultList != null) { btnAddFav.IsEnabled = true; btnAddFav.Visibility = Visibility.Visible; sep1.Visibility = Visibility.Visible; sep2.Visibility = Visibility.Visible; btnExport.IsEnabled = true; btnExport.Visibility = Visibility.Visible; newResultFlag = 0; pageList = new List<Button>(); Button b; Console.WriteLine(resultList.getCount()); maxCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(resultList.getCount() / 20))); //updateStatusBar(maxCount.ToString()); Console.WriteLine(maxCount); //status.Text = "" + maxCount; for (int i = 0; i < 12; i++) { b = new Button(); b.HorizontalAlignment = HorizontalAlignment.Stretch; b.Background = new SolidColorBrush(Colors.White); b.Foreground = new SolidColorBrush(Colors.Blue); b.BorderBrush = Brushes.White; b.MaxWidth = 20; b.BorderThickness = new Thickness(0); b.Cursor = Cursors.Hand; b.Uid = i + ""; if (i == 0) b.Content = b.Uid = "<<"; else if (i == 11) b.Content = b.Uid = ">>"; else b.Content = (i) + ""; if (i == 1) { b.Foreground = new SolidColorBrush(Colors.Black); b.Background = Brushes.LightGray; } else { b.Background = Brushes.White; b.Foreground = new SolidColorBrush(Colors.Blue); } b.Click += b_Click; if (i > maxCount && i != 11) { b.IsEnabled = false; b.Visibility = Visibility.Hidden; } pageList.Add(b); if (currentPageSelected == 1) { pageList[0].Visibility = Visibility.Hidden; pageList[0].IsEnabled = false; } else { pageList[0].IsEnabled = true; pageList[0].Visibility = Visibility.Visible; } Pagination.Children.Add(pageList[i]); } } try { changePagination(currentPageSelected); } catch (Exception) { } if (resultList != null) { Pagination.Visibility = Visibility.Visible; Pagination.IsEnabled = true; foreach (Result r in resultList) { List<Paper> paperList = new List<Paper>(); paperList = r.getResults(); Page2 page; ListBoxItem item; foreach (Paper p in paperList) { page = new Page2(mw, this, p, fav); item = new ListBoxItem(); page.setAuthors(p.getauthors() + p.getYear()); page.setTitle(p.gettitle()); page.setDescription(p.getdescription()); page.setNumberOfCitations(p.getnumCitations()); page.setlinkUrl(p.geturl()); page.setCitationList(p.getcitationsUrl()); item = page.listItem; page.Content = null; this.ResultsPane.Items.Add(item); } } type = resultList.type; ResultType resultType = resultList.resultType; if ((type != null && type.getname() != null) && resultType == ResultType.AUTHOR) { //Console.WriteLine("Ohhhhhhhhhhhhhhhhh I didnt expect"); Author auth = new Author(); auth = (Author)type; this.statsUrl = auth.getstatsGraphUrl(); Page3 auth_profile = new Page3(this); auth_profile.auth_name.Text = type.getname(); auth_profile.num_cite.Text = type.getnumPapers().ToString(); auth_profile.hindex.Text = type.gethIndex().ToString(); auth_profile.iindex.Text = type.getiIndex().ToString(); Grid g = new Grid(); g = auth_profile.author_profile; auth_profile.Content = null; this.Author.Children.Clear(); this.Author.Children.Add(g); } else if (type != null && resultList.resultType == ResultType.JOURNAL) { //this.Author.Text = ""; type = new Journal(); type = (Journal)resultList.type; JournalPage auth_profile = new JournalPage(this); auth_profile.journal_name.Text = this.searchBox.Text; Journal j = (Journal)type; Grid g = new Grid(); g = auth_profile.author_profile; auth_profile.Content = null; this.Author.Children.Clear(); this.Author.Children.Add(g); this.statsUrl = j.getStatsUrl(); // Console.WriteLine("==========="+j.getStatsUrl().ToString()); } } }
public ResultList initiateSearch(data d) { String queryString = d.qs; //tab.getSearchBoxText(); if (d.b.CancellationPending) { return null; } if (queryString == null || queryString == "") { TabPage.displayError("Please Enter a Query"); return null; } d.b.ReportProgress(0, null); int ylo = d.yl; int yhi = d.yh; //tab.getYhi(); Boolean includeCitations = d.ic; // tab.getIncludePatents(); SortOrder sortOrder = d.so; //tab.getSortOrder(); ResultType resultType = d.rt; // tab.getResultType(); d.b.ReportProgress(10, null); Query query = new Query(); query.setqueryString(queryString); if (ylo != 0) query.setylo(ylo); if (yhi != 0) query.setyhi(yhi); query.setincludePatents(includeCitations); query.sortOrder = sortOrder; query.resultType = resultType; query.setpageid(d.pageId); if (d.b.CancellationPending) { return null; } //bool networkUp = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); bool networkUp = Controller.CheckForInternetConnection(); Console.WriteLine(networkUp); if (networkUp) { Searcher searcher = new Searcher(); ResultList resultListGS = new ResultList(); ResultList resultListMS = new ResultList(); ResultList resultList = new ResultList(); SearchType type; d.b.ReportProgress(20, null); resultListGS = searcher.GSsearch(query); if (d.b.CancellationPending) { return null; } d.b.ReportProgress(50, null); resultListMS = searcher.MSASsearch(query); if (d.b.CancellationPending) { return null; } d.b.ReportProgress(70, null); if (resultListMS != null) resultList = resultListMS; else if (resultListMS == null && resultListGS != null) resultList = resultListGS; else { TabPage.displayError("Cannot connect to Data Sources."); return null; } if (d.b.CancellationPending) { return null; } d.b.ReportProgress(85, null); if (resultListGS != null) { if (resultListGS.type != null) resultList.type = resultListGS.type; } else { MSASQueryURLBuilder MSQ = new MSASQueryURLBuilder(); String URL = ""; if (resultType == ResultType.AUTHOR) { URL = MSQ.buildAuthorUrl(queryString); } else if (resultType == ResultType.JOURNAL) { URL = MSQ.buildJournalUrl(queryString); } Uri url = new Uri(URL); Console.WriteLine(url.ToString()); MSASParser parser = new MSASParser(); if (resultType == ResultType.AUTHOR) { resultList.resultType = ResultType.AUTHOR; resultList.type = parser.MSParseProfile(url, queryString, resultType); } else { resultList.resultType = ResultType.JOURNAL; resultList.loadType(); Console.WriteLine("Reached"); resultList.type =(Journal) parser.MSParseJournal(queryString); Console.WriteLine(";;;;;"+resultList.type); } if (d.b.CancellationPending) { return null; } } // tab.setResult(resultList); if (d.b.CancellationPending) { return null; } d.b.ReportProgress(100, null); return resultList; } else { TabPage.displayError("Oops !! No Internet Connection !!!"); return null; } }
protected override void OnRemoved(int index, TSource value) { --_concatIndex; ResultList.Remove(index); }
public async Task Should_return_single_content_with_duplicate_names() { var contentId = Guid.NewGuid(); var content = CreateContent(contentId, Guid.Empty, Guid.Empty); var query = @" query { findMySchemaContent(id: ""<ID>"") { data { myNumber { iv } myNumber2 { iv } myArray { iv { nestedNumber nestedNumber2 } } } } }".Replace("<ID>", contentId.ToString()); A.CallTo(() => contentQuery.QueryAsync(MatchsContentContext(), MatchId(contentId))) .Returns(ResultList.CreateFrom(1, content)); var result = await sut.QueryAsync(requestContext, new GraphQLQuery { Query = query }); var expected = new { data = new { findMySchemaContent = new { data = new { myNumber = new { iv = 1 }, myNumber2 = new { iv = 2 }, myArray = new { iv = new[] { new { nestedNumber = 10, nestedNumber2 = 11 }, new { nestedNumber = 20, nestedNumber2 = 21 } } } } } } }; AssertResult(expected, result); }
protected override void OnReplaced(int index, TSource oldValue, TSource newValue) { ResultList.Replace(index, newValue); }
protected override void OnMoved(int oldIndex, int newIndex, TSource value) { ResultList.Move(oldIndex, newIndex); }
/// <summary> /// Search shell (not interactive at this level) /// </summary> public static void Search(Index index, IEnumerable<CommandQuery> qReader, ShellSearchOptions searchOps, IEnumerable<string> args) { string names = null; string[] dbnames = null; if (searchOps.Names != null) { dbnames = File.ReadAllLines (names); } BinaryWriter ResultOutput = null; if (searchOps.ResultName != null) { ResultOutput = new BinaryWriter (File.Create (searchOps.ResultName + ".tmp")); } SortedDictionary<double, int> avg_hist = new SortedDictionary<double, int> (); int qid = 0; long totaltime = 0; SearchCost totalCost = new SearchCost (0, 0); if (ResultOutput != null) { var reslist = new ResultList (searchOps.IndexName, searchOps.QueryName); // Dirty.SerializeBinary (Output, reslist); reslist.Save (ResultOutput); } foreach (CommandQuery qItem in qReader) { long tstart = DateTime.Now.Ticks; SearchCost startCost = index.Cost; IResult res; if (qItem.QTypeIsRange) { res = index.ParseSearch (qItem.QRaw, qItem.QArg); } else { res = index.ParseKNNSearch (qItem.QRaw, (int)qItem.QArg); } SearchCost finalCost = index.Cost; finalCost.Internal -= startCost.Internal; finalCost.External -= startCost.External; totalCost.Internal += finalCost.Internal; totalCost.External += finalCost.External; long time = DateTime.Now.Ticks - tstart; totaltime += time; if (searchOps.Filter != null) { res = searchOps.Filter (qItem.QRaw, qItem.QArg, res, index); } SortedDictionary<double, int> hist = new SortedDictionary<double, int> (); if (searchOps.ShowHist) { foreach (ResultPair p in res) { if (hist.ContainsKey (p.dist)) { hist [p.dist]++; } else { hist [p.dist] = 1; } } foreach (var p in hist) { if (avg_hist.ContainsKey (p.Key)) { avg_hist [p.Key] += p.Value; } else { avg_hist [p.Key] = p.Value; } } if (avg_hist.Count > 1000) { searchOps.ShowHist = false; Console.WriteLine ("WARNING: Histogram of distances was disabled because there are too many bins"); } } ResultInfo info = new ResultInfo (qid, qItem.EncodeQTypeQArgInSign(), qItem.QRaw, finalCost, new TimeSpan (time), res); if (ResultOutput != null) { // Dirty.SerializeBinary (ResultOutput, info); info.Save (ResultOutput); } Console.WriteLine (info.ToString (searchOps.ShowMaxResult, dbnames)); if (searchOps.ShowHist) { Console.WriteLine ("Distance histogram (dist => counter)"); foreach (KeyValuePair<double, int> xp in hist) { Console.Write ("({0} => {1}), ", xp.Key, xp.Value); } Console.WriteLine ("<TheEnd>"); } Console.WriteLine ("Number Results: {0}", res.Count); qid++; } if (searchOps.ShowHist) { Console.WriteLine ("Average Distance histogram (dist => counter)"); foreach (KeyValuePair<double, int> xp in avg_hist) { Console.Write ("({0} => {1}), ", xp.Key, ((double)xp.Value) / qid); } Console.WriteLine ("<TheEnd>"); } if (ResultOutput != null) { ResultOutput.Close (); if (File.Exists (searchOps.ResultName)) { File.Delete (searchOps.ResultName); } File.Move (searchOps.ResultName + ".tmp", searchOps.ResultName); } Console.WriteLine ("Number queries: {0}", qid); Console.WriteLine ("Average numdists: {0}", (totalCost.Internal + totalCost.External + 0.0) / qid); Console.WriteLine ("Total search time: {0}", (new TimeSpan (totaltime)).TotalSeconds); Console.WriteLine ("Average search time: {0}", (new TimeSpan (totaltime / qid)).TotalSeconds); }
protected override void OnReset(IReadOnlyList <TSource> newItems) { ResultList.ReplaceRange(0, _concatIndex, newItems); _concatIndex = newItems.Count; }
public ResultList getMSASCitations(soid s) { Searcher searcher = new Searcher(); ResultList resultList = new ResultList(); String URL; s.c.ReportProgress(10, null); if (s.c.CancellationPending) return null; MSASQueryURLBuilder citationBuild = new MSASQueryURLBuilder(); s.c.ReportProgress(40, null); URL = citationBuild.buildCitationUrl(s.i,s.sOrder,s.start); if (s.c.CancellationPending) return null; s.c.ReportProgress(60, null); resultList = searcher.MSASsearchCitationUrl(URL); s.c.ReportProgress(90, null); if (s.c.CancellationPending) return null; return resultList; //tab.setResult(resultList); }
public async Task <IActionResult> Post([FromBody] DeckSearchOptions deckSearchOptions) { using (var repository = new Repository()) { var dbResult = repository.Context.Decks .Include(x => x.Status) .Include(x => x.Creator).AsNoTracking(); if (!string.IsNullOrWhiteSpace(deckSearchOptions.Search)) { dbResult = dbResult.Where( it => it.Name.Contains(deckSearchOptions.Search) || it.Creator.Name.Contains(deckSearchOptions.Search)); } if (deckSearchOptions.ExportTiles.HasValue) { var exportTiles = deckSearchOptions.ExportTiles.Value; dbResult = dbResult.Where(x => x.ExportTiles == exportTiles); } if (deckSearchOptions.MyDecks.HasValue && deckSearchOptions.MyDecks.Value) { var userGuid = HttpContext.GetUserGuid(); if (userGuid != Guid.Empty) { dbResult = dbResult.Where(x => x.Creator.Guid == userGuid); } } if (deckSearchOptions.Status == null && deckSearchOptions.ExcludeDrafts.HasValue && deckSearchOptions.ExcludeDrafts.Value) { dbResult = dbResult.Where(x => x.Status == null || x.Status.Guid != PredefinedGuids.Draft); } if (deckSearchOptions.Status != null) { dbResult = dbResult.Where(x => x.Status != null && x.Status.Guid == deckSearchOptions.Status.Guid); } var totalCount = dbResult.Count(); // default order by if (string.IsNullOrWhiteSpace(deckSearchOptions.OrderBy)) { deckSearchOptions.OrderBy = "Name"; } var orderByType = QueryHelper.GetPropertyType <DeckModel>(deckSearchOptions.OrderBy); if (orderByType != null) { if (orderByType == typeof(string)) { var orderByExpression = QueryHelper.GetPropertyExpression <DeckModel, string>(deckSearchOptions.OrderBy); dbResult = deckSearchOptions.ReverseOrder ? dbResult.OrderByDescending(orderByExpression) : dbResult.OrderBy(orderByExpression); } if (orderByType == typeof(int)) { var orderByExpression = QueryHelper.GetPropertyExpression <DeckModel, int>(deckSearchOptions.OrderBy); dbResult = deckSearchOptions.ReverseOrder ? dbResult.OrderByDescending(orderByExpression) : dbResult.OrderBy(orderByExpression); } if (orderByType == typeof(DateTime)) { var orderByExpression = QueryHelper.GetPropertyExpression <DeckModel, DateTime>(deckSearchOptions.OrderBy); dbResult = deckSearchOptions.ReverseOrder ? dbResult.OrderByDescending(orderByExpression) : dbResult.OrderBy(orderByExpression); } } deckSearchOptions.PageSize = Math.Min(50, deckSearchOptions.PageSize); var query = await dbResult.Skip((deckSearchOptions.PageNumber - 1) *deckSearchOptions.PageSize) .Take(deckSearchOptions.PageSize) .ToListAsync(); var result = new ResultList <Deck>(query.Select(x => x.FromDal()).ToList()) { TotalItems = totalCount, SearchOptions = deckSearchOptions }; return(Ok(result)); } }
/// <summary> /// Search shell (not interactive at this level) /// </summary> public static void Search(Index index, IEnumerable<CommandQuery> qReader, ShellSearchOptions searchOps) { BinaryWriter ResultOutput = null; if (searchOps.ResultName != null) { ResultOutput = new BinaryWriter (File.Create (searchOps.ResultName + ".tmp")); } int qid = 0; long totaltime = 0; SearchCost totalCost = new SearchCost (0, 0); if (ResultOutput != null) { var reslist = new ResultList (searchOps.IndexName, searchOps.QueryName); // Dirty.SerializeBinary (Output, reslist); reslist.Save (ResultOutput); } foreach (CommandQuery qItem in qReader) { long tstart = DateTime.Now.Ticks; SearchCost startCost = index.Cost; IResult res; var qobj = qItem.QObj; if (qobj == null) { qobj = index.DB.Parse (qItem.QRaw, true); } if (qItem.QTypeIsRange) { res = index.SearchRange (qobj, qItem.QArg); } else { res = index.SearchKNN (qobj, (int)qItem.QArg); } var qraw = qItem.QRaw; if (qraw.Length > 1024) { qraw = "<very-large-qraw>"; } SearchCost finalCost = index.Cost; finalCost.Internal -= startCost.Internal; finalCost.Total -= startCost.Total; totalCost.Internal += finalCost.Internal; totalCost.Total += finalCost.Total; long time = DateTime.Now.Ticks - tstart; totaltime += time; ResultInfo info = new ResultInfo (qid, qItem.EncodeQTypeQArgInSign(), qraw, finalCost, new TimeSpan (time), res); Console.WriteLine ("== qid: {0}", qid); Console.WriteLine ("== index: {0}, db: {1}, result: {2}", index, index.DB.Name, searchOps.ResultName); if (ResultOutput != null) { // Dirty.SerializeBinary (ResultOutput, info); info.Save (ResultOutput); } Console.WriteLine (info.ToString (searchOps.ShowMaxResult, null)); qid++; } if (ResultOutput != null) { ResultOutput.Close (); if (File.Exists (searchOps.ResultName)) { File.Delete (searchOps.ResultName); } File.Move (searchOps.ResultName + ".tmp", searchOps.ResultName); } Console.WriteLine ("Number queries: {0}", qid); Console.WriteLine ("Average total-numdists: {0}", (totalCost.Total + 0.0) / qid); Console.WriteLine ("Average internal-distances: {0}", (totalCost.Internal + 0.0) / qid); Console.WriteLine ("Average external-distances: {0}", (totalCost.Total - totalCost.Internal + 0.0) / qid); Console.WriteLine ("Total search time: {0}", (new TimeSpan (totaltime)).TotalSeconds); Console.WriteLine ("Average search time: {0}", (new TimeSpan (totaltime / qid)).TotalSeconds); }
private void Searcher_DoWork(object sender, DoWorkEventArgs e) { Console.WriteLine("Thread started"); data di = (data)e.Argument; BackgroundWorker b = sender as BackgroundWorker; //updateStatusBar("Looking up for"); test = new Controller(this); aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 1 minute. aTimer.Interval = 140000; aTimer.Enabled = true; //updateStatusBar(" "); resultList = test.initiateSearch(di); //updateStatusBar("fetched results for "+di.qs); if (d.b.CancellationPending) e.Cancel = true; Console.WriteLine("why dis kolaveri"); //TabPage tab = new TabPage(mw); }