protected void ValidateProductListResponse(ListResponse<Product> result) { Assert.IsNotNull(result, "Expected a result"); Assert.IsNotNull(result.StatusCode, "Expected a status code"); Assert.IsTrue(result.StatusCode.HasValue, "Expected a status code"); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode.Value, "Expected a 200 response"); Assert.IsNotNull(result.Result, "Expected a list of results"); Assert.IsNull(result.Error, "Expected no error"); Assert.Greater(result.Result.Count, 0, "Expected more than 0 results"); foreach (Product productItem in result.Result) { Assert.IsFalse(string.IsNullOrEmpty(productItem.Id), "Expected Id to be populated"); Assert.IsFalse(string.IsNullOrEmpty(productItem.Name), "Expected Name to be populated"); Assert.AreNotEqual(Category.Unknown, productItem.Category, "Expected Category to be set"); if (productItem.Category == Category.Album) { Assert.That(productItem.Tracks.Count, Is.AtLeast(1)); foreach (var track in productItem.Tracks) { Assert.IsFalse(string.IsNullOrEmpty(track.Id), "Expected trackId to be populated"); Assert.IsFalse(string.IsNullOrEmpty(track.Name), "Expected trackName to be populated"); Assert.AreNotEqual(Category.Unknown, track.Category, "Expected trackCategory to be set"); } } } }
public ListResponse<TranslationItem> List(TranslationListRequest request) { var result = new ListResponse<TranslationItem>(); var availableKeys = GetAllAvailableLocalTextKeys(); var targetLanguageID = request.TargetLanguageID.TrimToNull(); var customTranslations = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var textsFilePath = GetUserTextsFilePath(targetLanguageID); if (File.Exists(textsFilePath)) { var json = JsonConfigHelper.LoadConfig<Dictionary<string, JToken>>(textsFilePath); JsonLocalTextRegistration.ProcessNestedDictionary(json, "", customTranslations); foreach (var key in customTranslations.Keys) availableKeys.Add(key); } var sorted = new string[availableKeys.Count]; availableKeys.CopyTo(sorted); Array.Sort(sorted); var registry = Dependency.Resolve<ILocalTextRegistry>(); targetLanguageID = targetLanguageID ?? ""; var sourceLanguageID = request.SourceLanguageID.TrimToEmpty(); result.Entities = new List<TranslationItem>(); Func<string, string> effective = delegate (string key) { if (key.StartsWith("Navigation.")) { key = key.Substring("Navigation.".Length); return key.Split(new char[] { '/' }).Last(); } else if (key.StartsWith("Forms.") && key.Contains(".Categories.")) { return key.Split(new char[] { '.' }).Last().TrimToNull(); } return key; }; foreach (var key in sorted) { string customText; if (!customTranslations.TryGetValue(key, out customText)) customText = null; result.Entities.Add(new TranslationItem { Key = key, SourceText = registry.TryGet(sourceLanguageID, key) ?? effective(key), TargetText = registry.TryGet(targetLanguageID, key) ?? effective(key), CustomText = customText }); } return result; }
public void EnsureIListPropertiesWorkForErrorCase() { ListResponse<Artist> response = new ListResponse<Artist>(HttpStatusCode.NotFound, new ApiCallFailedException(), null, Guid.Empty); Artist artist = new Artist() { Id = "1234", Name = "Artist" }; Assert.AreEqual(0, response.Count, "Expected an empty list"); Assert.AreEqual(false, response.IsReadOnly, "Expected a readonly list"); Assert.IsNull(response[0], "Expected an empty list"); Assert.AreEqual(-1, response.IndexOf(artist), "Expected an empty list"); Assert.IsFalse(response.Contains(artist), "Expected an empty list"); // Check adding cases... response[0] = artist; Assert.AreEqual(0, response.Count, "Expected an empty list"); response.Add(artist); Assert.AreEqual(0, response.Count, "Expected an empty list"); response.Insert(0, artist); Assert.AreEqual(0, response.Count, "Expected an empty list"); // Check CopyTo does nothing... Artist[] artists = new Artist[0]; response.CopyTo(artists, 0); Assert.AreEqual(0, artists.Length, "Expected an empty list"); // Check remove cases... response.Remove(artist); Assert.AreEqual(0, response.Count, "Expected an empty list"); response.RemoveAt(0); Assert.AreEqual(0, response.Count, "Expected an empty list"); response.Clear(); Assert.AreEqual(0, response.Count, "Expected an empty list"); }
public void ValidateAFailedListResponse() { Exception e = new ApiCredentialsRequiredException(); ListResponse<MusicItem> response = new ListResponse<MusicItem>(HttpStatusCode.OK, e); Assert.IsNotNull(response, "Expected a new Response"); Assert.AreEqual(e, response.Error, "Expected the same error"); Assert.IsNull(response.Result, "Expected no result"); }
public ListResponse<User> GetActiveUsers() { var result = new ListResponse<User>(); ExecuteUsers(entities => { result.List = UserService.GetActiveUsers(entities); }, result); return result; }
//[HttpGet] //public ObjectResponse<Graph> GetFloorPlanData(int floorId) //{ // ObjectResponse<Graph> result = GetGraphForFloor(floorId); // return result; //} public ListResponse<Node> GetConnectedNodes(int nodeId) { var result = new ListResponse<Node>(); ExecuteMaps(entities => { result.List = GraphService.GetConnectedNodes(entities, nodeId); }, result); return result; }
private void ArtistsResponseHandler(ListResponse<Artist> response) { Dispatcher.BeginInvoke(() => { this.LoadingArtists.Visibility = Visibility.Collapsed; this.SimilarArtists.ItemsSource = response.Result; }); }
public ListResponse<NodeProbability> GetNodeProbabiltyForScan(LocationRequest request) { var result = new ListResponse<NodeProbability>(); ExecuteMaps(entities => { result.List = FingerprintService.GetNodeProbabiltyForScan(entities, request); }, result); return result; }
private void ProductResponse(ListResponse<Product> result) { Assert.IsNotNull(result, "Expected a result"); Assert.IsNotNull(result.StatusCode, "Expected a status code"); Assert.IsTrue(result.StatusCode.HasValue, "Expected a status code"); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode.Value, "Expected a 200 response"); Assert.IsNotNull(result.Result, "Expected a list of results"); Assert.IsNull(result.Error, "Expected no error"); Assert.Greater(result.Result.Count, 0, "Expected more than 0 results"); }
public void EnsureIListPropertiesWorkForSuccessCase() { List<Artist> artists = new List<Artist>() { new Artist() { Id = "1234", Name = "Artist" }, new Artist() { Id = "12345", Name = "Artist" }, new Artist() { Id = "123456", Name = "Artist" } }; ListResponse<Artist> response = new ListResponse<Artist>(HttpStatusCode.OK, artists, 0, 10, 3, Guid.Empty); Assert.AreEqual(3, response.Count, "Expected a list"); Assert.AreEqual(false, response.IsReadOnly, "Expected a readonly list"); Assert.AreEqual(false, response.IsFixedSize, "Expected a non fixed size list"); Assert.AreEqual(false, response.IsSynchronized, "Expected a non sync list"); Assert.IsNotNull(response.SyncRoot, "Expected an object"); Assert.AreEqual(artists[0], response[0], "Expected the same item"); Assert.AreEqual(artists[0], (response as IList)[0], "Expected the same item"); Assert.AreEqual(1, response.IndexOf(artists[1]), "Expected the same item"); Assert.AreEqual(1, (response as IList).IndexOf(artists[1]), "Expected the same item"); Assert.IsTrue(response.Contains(artists[1]), "Expected the item in there"); Assert.IsTrue((response as IList).Contains(artists[1]), "Expected the item in there"); // Check adding cases... response[2] = new Artist(); Assert.AreEqual(3, response.Count, "Expected same items"); (response as IList)[1] = new Artist(); Assert.AreEqual(3, response.Count, "Expected same items"); response.Add(new Artist()); Assert.AreEqual(4, response.Count, "Expected more items"); (response as IList).Add(new Artist()); Assert.AreEqual(5, response.Count, "Expected more items"); response.Insert(1, new Artist()); Assert.AreEqual(6, response.Count, "Expected more items"); (response as IList).Insert(1, new Artist()); Assert.AreEqual(7, response.Count, "Expected more items"); // Check CopyTo... Artist[] newArtists = new Artist[response.Count]; response.CopyTo(newArtists, 0); Assert.AreEqual(response.Count, newArtists.Length, "Expected the same number"); (response as IList).CopyTo(newArtists, 0); Assert.AreEqual(response.Count, newArtists.Length, "Expected the same number"); // Check remove cases... response.Remove(artists[0]); Assert.AreEqual(6, response.Count, "Expected less items"); (response as IList).Remove(artists[0]); Assert.AreEqual(5, response.Count, "Expected less items"); response.RemoveAt(0); Assert.AreEqual(4, response.Count, "Expected less items"); response.Clear(); Assert.AreEqual(0, response.Count, "Expected an empty list"); }
public ListResponse<IlRow> YetkiIlList(IDbConnection connection, BayiIlIlceYetkisiListRequest request) { request.ColumnSelection = ColumnSelection.Details; var entities= new BayiIlIlceYetkisiController().List(connection, request) .Entities.Select(x => new IlRow() { Id = x.IlId, Ad = x.IlAd }).ToList(); ListResponse<IlRow> res = new ListResponse<IlRow>(); res.Entities = entities; return res; }
public void ValidateAFailedListResponse() { Exception e = new ApiCredentialsRequiredException(); Guid requestId = Guid.NewGuid(); ListResponse<MusicItem> response = new ListResponse<MusicItem>(HttpStatusCode.OK, e, "ErrorResponseBody", requestId); Assert.IsNotNull(response, "Expected a new Response"); Assert.AreEqual(e, response.Error, "Expected the same error"); Assert.AreEqual("ErrorResponseBody", response.ErrorResponseBody, "Expected the same error"); Assert.AreEqual(requestId, response.RequestId, "Expected the same request id"); Assert.IsNull(response.Result, "Expected no result"); Assert.IsFalse(response.Succeeded, "Expected failure"); }
public void ValidateASuccessfulListResponse() { const int ItemsPerPage = 10; const int TotalResults = 23; const int StartIndex = 11; List<string> list = new List<string>() { "1", "2" }; ListResponse<string> response = new ListResponse<string>(HttpStatusCode.OK, list, StartIndex, ItemsPerPage, TotalResults); Assert.IsNotNull(response, "Expected a new ListResponse"); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Expected the same status code"); Assert.AreEqual(list.Count, response.Result.Count, "Expected the same result"); Assert.AreEqual(ItemsPerPage, response.ItemsPerPage, "Expected the same ItemsPerPage"); Assert.AreEqual(TotalResults, response.TotalResults, "Expected the same TotalResults"); Assert.AreEqual(StartIndex, response.StartIndex, "Expected the same StartIndex"); Assert.IsNull(response.Error, "Expected no error"); }
private void ProductResponse(ListResponse<Product> result) { Assert.IsNotNull(result, "Expected a result"); Assert.IsNotNull(result.StatusCode, "Expected a status code"); Assert.IsTrue(result.StatusCode.HasValue, "Expected a status code"); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode.Value, "Expected a 200 response"); Assert.IsNotNull(result.Result, "Expected a list of results"); Assert.IsNull(result.Error, "Expected no error"); Assert.Greater(result.Result.Count, 0, "Expected more than 0 results"); foreach (Product productItem in result.Result) { Assert.IsFalse(string.IsNullOrEmpty(productItem.Id), "Expected Id to be populated"); Assert.IsFalse(string.IsNullOrEmpty(productItem.Name), "Expected Name to be populated"); Assert.AreNotEqual(Category.Unknown, productItem.Category, "Expected Category to be set"); } }
public ListResponse<IConfigurationSetting> Load() { var response = new ListResponse<IConfigurationSetting>(); try { var _manager = StatWinner.Common.DependencyInjection.DependencyContainer.GetInstance<IConfigurationManager>(); var lst = _manager.ConfigurationSettings; response.Result = lst; } catch (Exception ex) { } return response; }
public ListResponse<EventCategory> ListEventCategories() { var response = new ListResponse<EventCategory>(); try { var clnEventCategories = this.StatWinnerDatabase.GetCollection<EventCategoryDBEntity>("EventCategories"); var sortDefinition = new SortDefinitionBuilder<EventCategoryDBEntity>(); var lst = clnEventCategories.Find(_ => true) .Sort(sortDefinition.Ascending(s => s.Name)) .ToListAsync() .Result.Select(EventManagementFactory.ConvertToEventCategory) .ToList(); response.Result = lst; } catch (Exception ex) { response.SetError(ex); } return response; }
public ListResponse<Country> LoadAllCountries() { var response = new ListResponse<Country>(); try { var mongoCollection = this.StatWinnerDatabase.GetCollection<CountryEntity>("Countries"); var sortDefinition = new SortDefinitionBuilder<CountryEntity>(); var lst = mongoCollection.Find(_ => true) .Sort(sortDefinition.Ascending("name")) .ToListAsync() .Result.Select(UserAccountManagementFactory.convertToCountry) .ToList(); response.Result = lst; } catch (Exception ex) { response.SetError(ex); } return response; }
public ListResponse<Floor> GetFloorsForMap(int mapId) { var result = new ListResponse<Floor>(); ExecuteMaps(entities => { result.List = FloorService.GetFloorsForMapCached(mapId); }, result); return result; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); //Class which encapsulate webservices. /* var _autoCompleteService = new AutoCompleteService(); * * _searchView = v.FindViewById<AutoCompleteTextView>(Resource.Id.SearchBox); * * _searchView.TextChanged += async (sender, e) => * { * try * { * //async call which fetch suggestin from webservices. * var results = await _autoCompleteService.SearchSuggestionAsync(_searchView.Text); * var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, results.ToList()); * _searchView.Adapter = adapter; * } * catch * { * } * }; * * _searchView.AfterTextChanged += (sender, e) => * { * if (!_searchView.IsPopupShowing && _searchView.Text.Length > 0) * { * _searchView.ShowDropDown(); * } * }; * * SetContentView(Resource.Layout.Main); * ////////*/ //setting the view for the Activity //////// SetContentView(Resource.Layout.activity_container_selection); //Get autoComplete1 AutoCompleteTextView and btn_Hello Button control from the Main.xaml Layout. box_name1 = FindViewById <AutoCompleteTextView>(Resource.Id.box_name1); box_selection = FindViewById <Button>(Resource.Id.box_selection); btn_box_registr = FindViewById <Button>(Resource.Id.btn_box_registr); btn_back_a = FindViewById <ImageButton>(Resource.Id.btn_back_a); preloader = FindViewById <ProgressBar>(Resource.Id.preloader); string dir_path = "/storage/emulated/0/Android/data/GeoGeometry.GeoGeometry/files/"; //string array used for displayling AutoComplete Suggestion /*var names = new string[] { "Anoop", "Arjit", "Akshay", "Ankit", "Rakesh" }; * //Use ArrayAdapter for filling the View in other words AutoCompleteTextView with the list of names(Array). * //Use SimpleSpinnerItem(Predefined layout in Android Resources) for displaying the dropdown list * ArrayAdapter adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerItem, names); * box_name1.Adapter = adapter;*/ /////////// /*SetContentView(Resource.Layout.activity_container_selection); * * box_name1 = FindViewById<AutoCompleteTextView>(Resource.Id.box_name1); * box_selection = FindViewById<Button>(Resource.Id.box_selection); * btn_back_a = FindViewById<ImageButton>(Resource.Id.btn_back_a); * preloader = FindViewById<ProgressBar>(Resource.Id.preloader); * * btn_back_a.Click += (s, e) => * { * Finish(); * };*/ box_name1.TextChanged += async(sender, e) => { try { //async call which fetch suggestin from webservices. RegisterBoxModel register = new RegisterBoxModel { Name = box_name1.Text, }; var myHttpClient = new HttpClient(); var uri = ("http://iot.tmc-centert.ru/api/container/getboxesbyname?name=" + box_name1.Text); HttpResponseMessage response = await myHttpClient.GetAsync(uri); AuthApiData <ListResponse <ContainerResponse> > o_data = new AuthApiData <ListResponse <ContainerResponse> >(); string s_result; using (HttpContent responseContent = response.Content) { s_result = await responseContent.ReadAsStringAsync(); } o_data = JsonConvert.DeserializeObject <AuthApiData <ListResponse <ContainerResponse> > >(s_result); var o_boxes_data = o_data.ResponseData; StaticBox.AddInfoObjects(o_boxes_data); //запись в файл using (FileStream fs = new FileStream(dir_path + "box_list.txt", FileMode.OpenOrCreate)) { await System.Text.Json.JsonSerializer.SerializeAsync <ListResponse <ContainerResponse> >(fs, o_boxes_data); } //чтение данных с файла using (FileStream fs = new FileStream(dir_path + "box_list.txt", FileMode.OpenOrCreate)) { ListResponse <ContainerResponse> containers = await System.Text.Json.JsonSerializer.DeserializeAsync <ListResponse <ContainerResponse> >(fs); var name = containers.Objects[0].Name; } var boxes = o_data.ResponseData.Objects.Select(b => new BoxNames { Name = b.Name }).ToList(); int count = boxes.Count(); string[] names1 = new string[count]; for (int i = 0; i < boxes.Count(); i++) { names1[i] = boxes[i].Name; } ArrayAdapter adapter1 = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerItem, names1); box_name1.Adapter = adapter1; } catch { } }; //box_name1.AfterTextChanged += (sender, e) => //{ // if (!box_name1.IsPopupShowing && box_name1.Text.Length > 0) // { // box_name1.ShowDropDown(); // } //}; //SetContentView(Resource.Layout.activity_container_selection); box_selection.Click += async delegate { preloader.Visibility = Android.Views.ViewStates.Visible; box_selection.Click += btn_Submit_Click; /* * XmlSerializer serializer = new XmlSerializer(typeof(ListResponse<ContainerResponse>)); * //Сериализация * using (FileStream fs = new FileStream(dir_path + "box_list.xml", FileMode.OpenOrCreate)) * serializer.Serialize(fs,); * /* * ListResponse<ContainerResponse> boxess = new ListResponse<ContainerResponse>(); * using (FileStream fs = new FileStream(dir_path + "box_list.txt", FileMode.OpenOrCreate)) * { * await System.Text.Json.JsonSerializer.DeserializeAsync<ListResponse<ContainerResponse>>(fs); * } */ /* * */ ListResponse <ContainerResponse> boxess = new ListResponse <ContainerResponse>(); var Res = ContainerSelection.DeserializeListResponse(dir_path + "box_list.txt"); if (Res != null) { boxess = Res; } var name = box_selection.Text; var uri = "http://iot.tmc-centert.ru/api/container/getbox?id=" + box_selection.Id; }; btn_box_registr.Click += async delegate { Intent ContainerRegisterActivity = new Intent(this, typeof(Auth.RegisterBoxActivity)); StartActivity(ContainerRegisterActivity); this.Finish(); }; }
private void FillReport(bool isInitial = false, bool throwException = true) { string rep_params = vals.Text; ReportGenericRequest req = new ReportGenericRequest(); req.paramString = rep_params; if (req.Parameters["_employeeId"] == "0") { return; } ListResponse <Model.Reports.RT303A> resp = _reportsService.ChildGetAll <Model.Reports.RT303A>(req); if (!resp.Success) { Common.ReportErrorMessage(resp, GetGlobalResourceObject("Errors", "Error_1").ToString(), GetGlobalResourceObject("Errors", "ErrorLogId").ToString()); } resp.Items.ForEach(x => { DateTime date = DateTime.ParseExact(x.dayId, "yyyyMMdd", new CultureInfo("en")); x.dateString = date.ToString(_systemService.SessionHelper.GetDateformat()); x.dowString = GetGlobalResourceObject("Common", date.DayOfWeek.ToString() + "Text").ToString(); x.specialTasks = x.jobTasks = "00:00"; x.specialTasks = x.unpaidLeaves; x.jobTasks = x.paidLeaves; x.dayStatusString = GetLocalResourceObject("status" + x.dayStatus.ToString()).ToString(); //if (x.workingHours != "00:00") //{ // x.unpaidLeaves = "00:00"; // x.jobTasks = x.paidLeaves; // x.paidLeaves = "00:00"; // x.specialTasks = x.unpaidLeaves; //} //else } ); string getLang = _systemService.SessionHelper.getLangauge(); Dictionary <string, string> parameters = Web.UI.Forms.Common.FetchReportParameters(texts.Text); OldDetailedAttendance h = new OldDetailedAttendance(parameters, getLang); h.RightToLeft = _systemService.SessionHelper.CheckIfArabicSession() ? DevExpress.XtraReports.UI.RightToLeft.Yes : DevExpress.XtraReports.UI.RightToLeft.No; h.RightToLeftLayout = _systemService.SessionHelper.CheckIfArabicSession() ? DevExpress.XtraReports.UI.RightToLeftLayout.Yes : DevExpress.XtraReports.UI.RightToLeftLayout.No; h.DataSource = resp.Items; //string from = DateTime.ParseExact(req.Parameters["_fromDayId"], "yyyyMMdd", new CultureInfo("en")).ToString(_systemService.SessionHelper.GetDateformat(), new CultureInfo("en")); //string to = DateTime.ParseExact(req.Parameters["_toDayId"], "yyyyMMdd", new CultureInfo("en")).ToString(_systemService.SessionHelper.GetDateformat(), new CultureInfo("en")); string user = _systemService.SessionHelper.GetCurrentUser(); h.Parameters["User"].Value = user; // h.Parameters["Fitlers"].Value = texts.Text; h.PrintingSystem.Document.ScaleFactor = 4; h.CreateDocument(); ASPxWebDocumentViewer1.OpenReport(h); }
/// <summary> /// Initializes a new instance of the <see cref="InsertListOnlineResponse"/> class. /// </summary> /// <param name="model">The response model.</param> /// <param name="document">The document after modification.</param> public InsertListOnlineResponse(ListResponse model, System.IO.Stream document) { this.Model = model; this.Document = document; }
public async Task <ListResponse <DeploymentInstanceSummary> > GetInstancesForOrgAsync(string orgId, ListRequest listRequest) { var items = await base.QueryAsync(qry => qry.OwnerOrganization.Id == orgId, listRequest); return(ListResponse <DeploymentInstanceSummary> .Create(listRequest, items.Model.Where(itm => itm.IsArchived == false).Select(itm => itm.CreateSummary()))); }
public ListResponse<NodeInformation> GetNodeInformation(int mapId, int floorId) { var result = new ListResponse<NodeInformation>(); ExecuteMaps(entities => { result.List = InformationService.GetNodeInformation(entities, mapId, floorId); }, result); return result; }
public ListResponse<Room> GetRoomsForMap(int mapId) { var result = new ListResponse<Room>(); ExecuteMaps(entities => { result.List = InformationService.GetRoomsForMap(entities, mapId); }, result); return result; }
private IListResponse<Organization> WaitForOrganizationToBeAvailiable(IZendeskQuery<Organization> query) { IListResponse<Organization> searchResults = new ListResponse<Organization>() { Results = new List<Organization>() }; var i = 100; while (i > 0 && !searchResults.Results.Any()) { searchResults = _client.Search.Find(query); i--; Thread.Sleep(3000); } if (searchResults == null || searchResults.Results == null || !searchResults.Results.Any()) Assert.Fail("Query returned no matching results"); return searchResults; }
public async Task <ListResponse <DeploymentInstanceSummary> > GetInstancesForOrgAsync() { var instanceSummaries = await _instanceManager.GetInstanceForOrgAsync(OrgEntityHeader.Id, UserEntityHeader); return(ListResponse <DeploymentInstanceSummary> .Create(instanceSummaries)); }
public async Task <ActionResult> Index() { ListResponse <PaymentResponse> paymentList = await this._paymentClient.GetPaymentListAsync(0, NumberOfPaymentsToList); return(View(paymentList.Data)); }
public async Task <ActionResult> Index() { ListResponse <PaymentListData> paymentList = await this._paymentClient.GetPaymentListAsync(null, NumberOfPaymentsToList); return(this.View(paymentList.Embedded.Payments)); }
public ListResponse <TranslationItem> List(TranslationListRequest request) { var result = new ListResponse <TranslationItem>(); var availableKeys = GetAllAvailableLocalTextKeys(); var targetLanguageID = request.TargetLanguageID.TrimToNull(); var customTranslations = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); var textsFilePath = GetUserTextsFilePath(targetLanguageID); if (File.Exists(textsFilePath)) { var json = JsonConfigHelper.LoadConfig <Dictionary <string, JToken> >(textsFilePath); JsonLocalTextRegistration.ProcessNestedDictionary(json, "", customTranslations); foreach (var key in customTranslations.Keys) { availableKeys.Add(key); } } var sorted = new string[availableKeys.Count]; availableKeys.CopyTo(sorted); Array.Sort(sorted); var registry = Dependency.Resolve <ILocalTextRegistry>(); targetLanguageID = targetLanguageID ?? ""; var sourceLanguageID = request.SourceLanguageID.TrimToEmpty(); result.Entities = new List <TranslationItem>(); Func <string, string> effective = delegate(string key) { if (key.StartsWith("Navigation.")) { key = key.Substring("Navigation.".Length); return(key.Split(new char[] { '/' }).Last()); } else if (key.StartsWith("Forms.") && key.Contains(".Categories.")) { return(key.Split(new char[] { '.' }).Last().TrimToNull()); } return(key); }; foreach (var key in sorted) { string customText; if (!customTranslations.TryGetValue(key, out customText)) { customText = null; } result.Entities.Add(new TranslationItem { Key = key, SourceText = registry.TryGet(sourceLanguageID, key) ?? effective(key), TargetText = registry.TryGet(targetLanguageID, key) ?? effective(key), CustomText = customText }); } return(result); }
protected override ListResponse <ProductRow> OnViewProcessData(ListResponse <ProductRow> response) { pendingChanges.Clear(); SetSaveButtonState(); return(base.OnViewProcessData(response)); }
protected void SaveGroupUsers(object sender, DirectEventArgs e) { try { //Getting the id to check if it is an Add or an edit as they are managed within the same form. string id = e.ExtraParams["id"]; string selected = e.ExtraParams["selectedGroups"]; List <SecurityGroupUser> selectedUsers = JsonConvert.DeserializeObject <List <SecurityGroupUser> >(selected); selectedUsers.ForEach(x => x.userId = CurrentUser.Text); GroupUsersListRequest request = new GroupUsersListRequest(); request.UserId = CurrentUser.Text; ListResponse <SecurityGroupUser> userGroups = _accessControlService.ChildGetAll <SecurityGroupUser>(request); if (!userGroups.Success) { Common.errorMessage(userGroups); return; } PostRequest <SecurityGroupUser> req = new PostRequest <SecurityGroupUser>(); PostResponse <SecurityGroupUser> resp = new PostResponse <SecurityGroupUser>(); userGroups.Items.ForEach(x => { req.entity = x; resp = _accessControlService.ChildDelete <SecurityGroupUser>(req); if (!resp.Success) { Common.errorMessage(resp); throw new Exception(); } }); //req.entity = new SecurityGroupUser() { sgId = "0", userId = CurrentUser.Text }; //resp = _accessControlService.ChildDelete<SecurityGroupUser>(req); foreach (var item in selectedUsers) { req.entity = item; req.entity.userId = CurrentUser.Text; resp = _accessControlService.ChildAddOrUpdate <SecurityGroupUser>(req); if (!resp.Success) { Common.errorMessage(resp); throw new Exception(); } } Notification.Show(new NotificationConfig { Title = Resources.Common.Notification, Icon = Icon.Information, Html = Resources.Common.RecordSavingSucc }); groupUsersWindow.Close(); UserGroupsStore.Reload(); } catch (Exception exp) { X.MessageBox.Alert(GetGlobalResourceObject("Common", "Error").ToString(), exp.Message); } }
/// <summary> /// Loads the list of notification events /// </summary> /// <returns></returns> public ListResponse<EventEntity> LoadNotificationEvents() { var response = new ListResponse<EventEntity>(); try { var clnEvents = this.StatWinnerDatabase.GetCollection<EventDbEntity>("NotificationEvents"); var sortDefinition = new SortDefinitionBuilder<EventDbEntity>(); var events = clnEvents.Find(_ => true).Sort(sortDefinition.Ascending(r => r.EventKey)).ToListAsync().Result.Select(EventManagementFactory.ConvertToEvent).ToList(); //Set Event Categories var clnEventCategories = this.StatWinnerDatabase.GetCollection<EventCategoryDBEntity>("EventCategories"); var evenTcategoriIds = events.Where(e => !e.EventCategoryId.IsNullOrEmpty()).Select(e => ObjectId.Parse(e.EventCategoryId)).ToList(); var eventCategoriesFilter = Builders<EventCategoryDBEntity>.Filter.In("_id", evenTcategoriIds); var eventCategories = clnEventCategories.Find(eventCategoriesFilter).ToListAsync().Result.ToList(); events.ForEach(ev => ev.EventCategoryName = (eventCategories.Single(ec => ec.Id.ToString() == ev.EventCategoryId).Name)); response.Result = events; } catch (Exception ex) { response.SetError(ex); } return response; }
public async Task <ListResponse <DeploymentInstanceSummary> > GetInstancesForOrgAsync(NuvIoTEditions edition, string orgId, ListRequest listRequest) { var items = await base.QueryAsync(qry => qry.OwnerOrganization.Id == orgId && (qry.NuvIoTEdition.HasValue && qry.NuvIoTEdition.Value == edition), listRequest); return(ListResponse <DeploymentInstanceSummary> .Create(listRequest, items.Model.Select(itm => itm.CreateSummary()))); }
protected void Page_Load(object sender, EventArgs e) { if (!X.IsAjaxRequest && !IsPostBack) { SetExtLanguage(); HideShowButtons(); HideShowColumns(); currentEmployeeId.Text = _systemService.SessionHelper.GetEmployeeId(); try { AccessControlApplier.ApplyAccessControlOnPage(typeof(AdminDocument), BasicInfoTab1, GridPanel1, null, null); } catch (AccessDeniedException exp) { X.MessageBox.ButtonText.Ok = Resources.Common.Ok; X.Msg.Alert(Resources.Common.Error, Resources.Common.ErrorAccessDenied, "closeCurrentTab()").Show(); Viewport1.Hidden = true; return; } FillDepartment(); dateFormat.Text = _systemService.SessionHelper.GetDateformat().ToUpper(); AdminDepartmentListRequest req = new AdminDepartmentListRequest(); req.status = 0; ListResponse <AdminDepartment> resp = _administrationService.ChildGetAll <AdminDepartment>(req); if (!resp.Success) { Common.errorMessage(resp); return; } if (resp.Items.Count > 0) { DeptId1.Text = resp.Items[0].departmentId; GridPanel1.Hidden = false; GridPanel1.Title = resp.Items[0].departmentName; } if (resp.Items.Count > 1) { DeptId2.Text = resp.Items[1].departmentId; GridPanel2.Hidden = false; GridPanel2.Title = resp.Items[1].departmentName; } if (resp.Items.Count > 2) { DeptId3.Text = resp.Items[2].departmentId; GridPanel3.Hidden = false; GridPanel3.Title = resp.Items[2].departmentName; } if (resp.Items.Count > 3) { DeptId4.Text = resp.Items[3].departmentId; GridPanel4.Hidden = false; GridPanel4.Title = resp.Items[3].departmentName; } if (resp.Items.Count > 4) { DeptId5.Text = resp.Items[4].departmentId; GridPanel5.Hidden = false; GridPanel5.Title = resp.Items[4].departmentName; } if (resp.Items.Count > 5) { DeptId6.Text = resp.Items[5].departmentId; GridPanel6.Hidden = false; GridPanel6.Title = resp.Items[5].departmentName; } } }
private IEnumerable<Torrent> GetTorrents(string s) { if (string.IsNullOrEmpty(s)) return Enumerable.Empty<Torrent>(); ListResponse list = null; try { list = new ListResponse(JsonConvert.DeserializeObject<JsonListResponse>(s)); } catch (Exception ex) { } if (list == null) return Enumerable.Empty<Torrent>(); return list.Torrents; }
public ListResponse<Map> GetMaps() { var result = new ListResponse<Map>(); Execute(() => { result.List = MapService.GetMapsCached(); }, result); return result; }
public void EnsureValidResultGivesEnumerator() { ListResponse<MusicItem> response = new ListResponse<MusicItem>(HttpStatusCode.OK, new List<MusicItem>(), null, null, null, Guid.Empty); Assert.IsNotNull((response as System.Collections.IEnumerable).GetEnumerator(), "Expected a non-null enumerator"); Assert.IsNotNull((response as System.Collections.Generic.IEnumerable<MusicItem>).GetEnumerator(), "Expected a non-null enumerator"); }
public ListResponse<PoiType> GetPoiTypes() { var result = new ListResponse<PoiType>(); ExecuteMaps(entities => { result.List = InformationService.GetPoiTypes(entities); }, result); return result; }
public async Task <ListResponse <Verifier> > GetVerifiersForComponentAsync(string componentid) { var verifiers = await _verifierManager.GetVerifierForComponentAsync(componentid, OrgEntityHeader, UserEntityHeader); return(ListResponse <Verifier> .Create(verifiers)); }
public ListResponse<Node> GetRouteBetween(int mapId, int startNodeId, int endNodeId) { var result = new ListResponse<Node>(); ExecuteMaps( entities => { result.List = NavigationService.GetRouteBetweenCached(mapId, startNodeId, endNodeId); }, result); return result; }
public async Task <ListResponse <PipelineModuleConfigurationSummary> > GetListenerConfigurationsForOrgAsync() { var configs = await _pipelineModuleManager.GetListenerConfiugrationsForOrgAsync(OrgEntityHeader.Id, UserEntityHeader); return(ListResponse <PipelineModuleConfigurationSummary> .Create(configs)); }
public async Task <ListResponse <PipelineModuleConfigurationSummary> > GetCustomPipelineModuleConfigurationsForOrgAsync(String orgid) { var configs = await _pipelineModuleManager.GetCustomPipelineModuleConfiugrationsForOrgAsync(orgid, UserEntityHeader); return(ListResponse <PipelineModuleConfigurationSummary> .Create(configs)); }
public IActionResult GetFlights([FromBody] SearchFlight searchFlightCriteria) { Logger?.LogDebug("'{0}' has been invoked", nameof(GetFlights)); if (!searchFlightCriteria.NumberOfRecord.HasValue) { searchFlightCriteria.NumberOfRecord = 20; } var response = new ListResponse <Flight>(); try { if (searchFlightCriteria.GetType() .GetProperties() .Select(p => p.GetValue(searchFlightCriteria)) .Any(p => p != null) ) { var flightDetail = DbContext.Flight.Where(p => (string.IsNullOrEmpty(searchFlightCriteria.From) || p.Depart == searchFlightCriteria.From) && (string.IsNullOrEmpty(searchFlightCriteria.To) || p.Return == searchFlightCriteria.To) && (searchFlightCriteria.DepartDate == null || p.DepartTime.ToDateTime() == searchFlightCriteria.DepartDate.Value.Date) && (searchFlightCriteria.ReturnDate == null || p.ReturnTime.ToDateTime() == searchFlightCriteria.ReturnDate.Value.Date) && (string.IsNullOrEmpty(searchFlightCriteria.ClassType) || p.ClassType.Contains(searchFlightCriteria.ClassType)) && (searchFlightCriteria.RoundTrip == null || p.RoundTrip == searchFlightCriteria.RoundTrip) && (searchFlightCriteria.PriceFrom == null || p.TotalMoney >= searchFlightCriteria.PriceFrom) && (searchFlightCriteria.PriceTo == null || p.TotalMoney <= searchFlightCriteria.PriceTo) && (searchFlightCriteria.Airlines == null || searchFlightCriteria.Airlines.Count == 0 || searchFlightCriteria.Airlines.Contains(p.DepartAirlineName) || searchFlightCriteria.Airlines.Contains(p.ReturnAirlineName))); if (searchFlightCriteria.OrderBy == OrderByEnum.TotalMoney) { flightDetail = flightDetail.OrderBy(p => p.TotalMoney); } if (searchFlightCriteria.OrderBy == OrderByEnum.DepartTime) { flightDetail = flightDetail.OrderBy(p => Convert.ToDateTime(p.DepartTime)); } response.Model = flightDetail.Take(searchFlightCriteria.NumberOfRecord.Value).ToList(); } else { response.Model = DbContext.Flight.ToList(); } } catch (Exception ex) { response.DidError = true; response.ErrorMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; Logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(GetFlights), ex); } return(response.ToHttpResponse()); }
void test(ListResponse d) { var i = 0; }
/// <summary> /// Invoked when the Page is loaded and becomes the current source of a parent Frame. /// </summary> /// <param name="e">Event data that can be examined by overriding code. The event data is representative of the pending navigation that will load the current Page. Usually the most relevant property to examine is Parameter.</param> protected async override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); if (e.NavigationMode == Windows.UI.Xaml.Navigation.NavigationMode.New) { #if WINDOWS_PHONE_APP this.Pivot.Items.Clear(); this.Pivot.Title = "LOADING..."; #else this.pageTitle.Text = "loading..."; #endif List <GroupedItems> datasource = null; string title = null; // See if we're displaying an artist... Artist artist = e.Parameter as Artist; if (artist != null) { title = artist.Name.ToLowerInvariant(); var topSongs = new GroupedItems() { Title = "top songs" }; var similarArtists = new GroupedItems() { Title = "similar artists" }; datasource = new List <GroupedItems>() { topSongs, similarArtists }; ListResponse <Product> topSongsList = await App.ApiClient.GetArtistProductsAsync(artist.Id, category : Category.Track, itemsPerPage : 6); if (topSongsList.Result != null) { foreach (Product p in topSongsList) { topSongs.Items.Add(p); } } ListResponse <Artist> similarArtistList = await App.ApiClient.GetSimilarArtistsAsync(artist.Id, itemsPerPage : 8); if (similarArtistList.Result != null) { foreach (Artist a in similarArtistList) { similarArtists.Items.Add(a); } } } // See if we're displaying a product... Product product = e.Parameter as Product; if (product != null) { title = product.Name.ToLowerInvariant(); var tracks = new GroupedItems() { Title = "tracks" }; var similarAlbums = new GroupedItems() { Title = "similar albums" }; datasource = new List <GroupedItems>() { tracks, similarAlbums }; Response <Product> productDetails = await App.ApiClient.GetProductAsync(product.Id); if (productDetails.Result != null) { foreach (Product p in productDetails.Result.Tracks) { tracks.Items.Add(p); } } ListResponse <Product> similarAlbumsList = await App.ApiClient.GetSimilarProductsAsync(product.Id, itemsPerPage : 8); if (similarAlbumsList.Result != null) { foreach (Product p in similarAlbumsList) { similarAlbums.Items.Add(p); } } } // See if we're displaying a genre... Genre genre = e.Parameter as Genre; if (genre != null) { title = genre.Name.ToLowerInvariant(); var topArtists = new GroupedItems() { Title = "top artists" }; var topAlbums = new GroupedItems() { Title = "top albums" }; var topSongs = new GroupedItems() { Title = "top songs" }; var newAlbums = new GroupedItems() { Title = "new albums" }; var newSongs = new GroupedItems() { Title = "new songs" }; datasource = new List <GroupedItems>() { topArtists, topAlbums, topSongs, newAlbums, newSongs }; ListResponse <Artist> topArtistsList = await App.ApiClient.GetTopArtistsForGenreAsync(genre.Id, itemsPerPage : 6); if (topArtistsList.Result != null) { foreach (Artist a in topArtistsList.Result) { topArtists.Items.Add(a); } } ListResponse <Product> topAlbumsList = await App.ApiClient.GetTopProductsForGenreAsync(genre.Id, Category.Album, itemsPerPage : 6); if (topAlbumsList.Result != null) { foreach (Product p in topAlbumsList) { topAlbums.Items.Add(p); } } ListResponse <Product> topSongsList = await App.ApiClient.GetTopProductsForGenreAsync(genre.Id, Category.Track, itemsPerPage : 6); if (topSongsList.Result != null) { foreach (Product p in topSongsList) { topSongs.Items.Add(p); } } ListResponse <Product> newAlbumsList = await App.ApiClient.GetNewReleasesForGenreAsync(genre.Id, Category.Album, itemsPerPage : 6); if (newAlbumsList.Result != null) { foreach (Product p in newAlbumsList) { newAlbums.Items.Add(p); } } ListResponse <Product> newSongsList = await App.ApiClient.GetNewReleasesForGenreAsync(genre.Id, Category.Track, itemsPerPage : 6); if (topSongsList.Result != null) { foreach (Product p in newSongsList) { newSongs.Items.Add(p); } } } #if WINDOWS_APP this.groupedItemsViewSource.Source = datasource; this.pageTitle.Text = title; #elif WINDOWS_PHONE_APP this.Pivot.Title = title.ToUpperInvariant(); foreach (var group in datasource) { var pivotItem = new PivotItem(); pivotItem.Header = group.Title; var listbox = new ListBox(); listbox.SelectionMode = SelectionMode.Single; listbox.SelectionChanged += this.ShowItem; listbox.ItemsSource = group.Items; listbox.ItemTemplate = Application.Current.Resources["ApiListItem"] as DataTemplate; listbox.Background = Application.Current.Resources["ApplicationPageBackgroundThemeBrush"] as SolidColorBrush; pivotItem.Content = listbox; this.Pivot.Items.Add(pivotItem); } #endif } }
public JsonResult Chart11_Datasource() { var postedData = _LoadViewModel(); var datasourceRequest = DeserializeDatasourceRequest(postedData["datasourceRequest"].ToString()); var queryable = Get_Chart11_DatasourceQueryable(datasourceRequest); var response = new ListResponse { TotalRows = DatasourceRetriever.ApplyDynamicFilterToQueryable(datasourceRequest, queryable).Count(), }; //Total items count if (CLMS.AppDev.Cache.CacheManager.Current.HasKey($"{Request.RequestContext.HttpContext.Session.SessionID}_Chart11_TotalItems")) { CLMS.AppDev.Cache.CacheManager.Current.Set($"{Request.RequestContext.HttpContext.Session.SessionID}_Chart11_TotalItems", response.TotalRows); } else { CLMS.AppDev.Cache.CacheManager.Current.Add($"{Request.RequestContext.HttpContext.Session.SessionID}_Chart11_TotalItems", response.TotalRows); } if (response.TotalRows < datasourceRequest.StartRow + 1) { datasourceRequest.StartRow = 0; } if (datasourceRequest.GroupBy.Any()) { var groups = DatasourceRetriever.RetrieveGrouped(datasourceRequest, queryable, q => q.Id, postedData); IDictionary <string, string> groupLabels = new Dictionary <string, string>() { { "isavailabletoallauthorizedusers", "Actions" }, { "id", "Actions" } }; var data = new List <ChartHelper.ChartResult>(); foreach (var group in groups.SubGroups) { var result = new ChartHelper.ChartResult(); result.Label = group.KeyFormatted; foreach (var aggr in group.Aggregates) { if (aggr.Column == "__Count") { continue; } result.Values.Add(aggr.Value); if (groupLabels.ContainsKey(aggr.Column.ToLower())) { result.ValueLabels.Add(groupLabels[aggr.Column.ToLower()]); } else { result.ValueLabels.Add(aggr.Column); } } data.Add(result); } response.Data = data; //Fix for total items in GetGroupsClosed if (datasourceRequest.GroupBy.FirstOrDefault().GetGroupsClosed) { response.TotalRows = DatasourceRetriever.GetTotalGroups(groups); } } else { var items = DatasourceRetriever.Retrieve(datasourceRequest, queryable);; var _dtos = items.Select(i => new ApplicationOperationDataSet_ApplicationOperationDTO(i, true)).ToList(); var chartData = new List <ChartHelper.ChartResult>(); foreach (var _dto in _dtos) { chartData.Add(new ChartHelper.ChartResult(_dto, _dto?.IsAvailableToAllAuthorizedUsers, new List <object> { _dto?.Id }, new List <object> { "Actions" }, new List <object> { })); } response.Data = chartData; } var __result = Json(new { Type = "DatasourceData", Data = Serialize(response) }, JsonRequestBehavior.AllowGet); __result.MaxJsonLength = int.MaxValue; return(__result); }
private void StoreSystemDefaults() { ListRequest req = new ListRequest(); ListResponse <KeyValuePair <string, string> > defaults = _systemService.ChildGetAll <KeyValuePair <string, string> >(req); if (!defaults.Success) { X.MessageBox.ButtonText.Ok = Resources.Common.Ok; X.Msg.Alert(Resources.Common.Error, defaults.Summary).Show(); return; } try { _systemService.SessionHelper.SetDateformat(defaults.Items.Where(s => s.Key == "dateFormat").First().Value); } catch { _systemService.SessionHelper.SetDateformat("MMM, dd, yyyy"); } try { _systemService.SessionHelper.SetNameFormat(defaults.Items.Where(s => s.Key == "nameFormat").First().Value); } catch { _systemService.SessionHelper.SetNameFormat("{firstName}{lastName} "); } try { _systemService.SessionHelper.SetCurrencyId(defaults.Items.Where(s => s.Key == "currencyId").First().Value); } catch { _systemService.SessionHelper.SetCurrencyId("0"); } try { _systemService.SessionHelper.SetHijriSupport(Convert.ToBoolean(defaults.Items.Where(s => s.Key == "enableHijri").First().Value)); } catch { _systemService.SessionHelper.SetHijriSupport(false); } //try //{ // _systemService.SessionHelper.SetDefaultTimeZone(Convert.ToInt32(defaults.Items.Where(s => s.Key == "timeZone").First().Value)); //} //catch //{ // _systemService.SessionHelper.SetDefaultTimeZone(0); //} try { _systemService.SessionHelper.SetCalendarId(defaults.Items.Where(s => s.Key == "caId").First().Value); } catch { _systemService.SessionHelper.SetCalendarId("0"); } try { _systemService.SessionHelper.SetVacationScheduleId(defaults.Items.Where(s => s.Key == "vsId").First().Value); } catch { _systemService.SessionHelper.SetVacationScheduleId("0"); } try { EmployeeListRequest request = new EmployeeListRequest(); // request.BranchId = request.DepartmentId = request.PositionId = "0"; request.StartAt = "0"; request.SortBy = "hireDate"; request.Size = "1"; // request.IncludeIsInactive = 2; var resp = _employeeService.GetAll <Employee>(request); _systemService.SessionHelper.SetStartDate(resp.Items[0].hireDate.Value); } catch (Exception exp) { _systemService.SessionHelper.SetStartDate(DateTime.Now); } }
/// <summary> /// Populates the new tracks list with results from API. /// </summary> /// <param name="response">List of items from the API</param> private void NewSongsResponseHandler(ListResponse<Product> response) { Dispatcher.BeginInvoke(() => { this.LoadingNewSongs.Visibility = Visibility.Collapsed; this.NewSongs.ItemsSource = response.Result; }); }
public async Task <ListResponse <MediaResourceSummary> > GetResourceForLibraryAsync(string libraryid) { var summaries = await _mediaServicesManager.GetMediaResourceSummariesAsync(libraryid, OrgEntityHeader.Id, UserEntityHeader); return(ListResponse <MediaResourceSummary> .Create(summaries)); }
public void EnsureNullResultGivesNoEnumerator() { ListResponse<MusicItem> response = new ListResponse<MusicItem>(HttpStatusCode.OK, new ApiCredentialsRequiredException(), null, Guid.Empty); Assert.IsNull((response as System.Collections.IEnumerable).GetEnumerator(), "Expected a null enumerator"); Assert.IsNull((response as System.Collections.Generic.IEnumerable<MusicItem>).GetEnumerator(), "Expected a null enumerator"); }
public async Task <ListResponse <VerifierSummary> > GetVerifiersForOrgAsync(string orgid) { var verifiers = await _verifierManager.GetVerifierForOrgsAsync(orgid, UserEntityHeader); return(ListResponse <VerifierSummary> .Create(verifiers)); }