public async Task <IResponseResult <IPaginationCollection <ActiveToken> > > GetActiveTokensAsync( string userId, TokenBase token, int?skip = null, int?limit = null, bool?withCount = null, string orderBy = null, SortDirection?sortDirection = null) { var query = "{ 'where': { 'user_id': '" + userId + "', 'membership_id': '" + this.MembershipId + "' } }"; return(await this.ExecuteRequestAsync <PaginationCollection <ActiveToken> >( HttpMethod.Post, $"{this.BaseUrl}/memberships/{this.MembershipId}/active-tokens/_query", QueryStringHelper.GetQueryString(skip, limit, withCount, orderBy, sortDirection), HeaderCollection.Add("Authorization", token.ToString()), new JsonRequestBody(Newtonsoft.Json.JsonConvert.DeserializeObject(query)))); }
public async Task <APIResponse> GetReviews(ReviewsParameter reviewsParameter) { try { string serializedStories; // List<AssetResponse> stories; /* var encodedStories = await distributedCache.GetAsync(BlogServiceOperation.GetStoriesCacheName); * * if (encodedStories != null) * { * serializedStories = Encoding.UTF8.GetString(encodedStories); * stories = JsonConvert.DeserializeObject<List<StoryResponse>>(serializedStories); * } * else * {*/ var client = httpClientFactory.CreateClient(VendorServiceOperation.serviceName); UriBuilder url = new UriBuilder(servicesConfig.Blog + VendorServiceOperation.GetReviews()); url.Query = QueryStringHelper.ConvertToQueryString(reviewsParameter); var response = await client.GetAsync(url.ToString()); var reviewResponse = JsonConvert.DeserializeObject <APIResponse>(await response.Content.ReadAsStringAsync()); serializedStories = JsonConvert.SerializeObject(reviewResponse); /* encodedStories = Encoding.UTF8.GetBytes(serializedStories); * var options = new DistributedCacheEntryOptions() * .SetSlidingExpiration(TimeSpan.FromMinutes(1)) * .SetAbsoluteExpiration(DateTime.Now.AddHours(1)); * * await distributedCache.SetAsync(VendorServiceOperation.GetStoriesCacheName, encodedStories, options); * }*/ return(new APIResponse(reviewResponse, HttpStatusCode.OK)); } catch (Exception ex) { logger.Error(ex, "Exception in method 'GetReviews()'"); var exMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message; return(new APIResponse(exMessage, HttpStatusCode.InternalServerError)); } }
private void AddPagerLi(Control parentControl) { for (var i = StartIndex; i <= EndIndex; i++) { var li = new HtmlGenericControl("li"); var anchor = new HtmlAnchor { HRef = QueryStringHelper.AddUpdateQueryStringGetUrl("pageIndex", i), InnerText = i.ToString(), Title = "Go to page " + i }; if (PageIndex == i) { li.AddCssClass("active"); } li.Controls.Add(anchor); parentControl.Controls.Add(li); } }
/// <summary> /// Removes a parameter from the specified URL. /// </summary> /// <param name="request">The request containing the URL to manage.</param> /// <param name="parameterName">Parameter to be removed.</param> /// <returns>The updated URL.</returns> public static string RemoveParameterFromUrl(HttpRequest request, string parameterName) { try { var qsh = new QueryStringHelper(request.Url.Query); qsh.RemoveByName(parameterName); var returnUri = new UriBuilder(request.Url.Scheme, request.Url.Host, request.Url.Port) { Path = request.Url.AbsolutePath, Query = qsh.GetQueryString() }; return returnUri.ToString(); } catch { return string.Empty; } }
/// <summary> /// Adds a Querystring parameter to the current Request's URL. /// </summary> /// <param name="request">The request containing the URL to manage.</param> /// <param name="parameterName">The key for the Querystring entry.</param> /// <param name="parameterValue">The value for the Querystring entry.</param> /// <returns>A URL concatenated with the new querystring parameter.</returns> public static string AddParameterToUrl(HttpRequest request, string parameterName, string parameterValue) { try { var qsh = new QueryStringHelper(request.Url.Query); qsh.AddOrReplace(parameterName, parameterValue); var returnUri = new UriBuilder(request.Url.Scheme, request.Url.Host, request.Url.Port) { Path = request.Url.AbsolutePath, Query = qsh.GetQueryString() }; return returnUri.ToString(); } catch { return string.Empty; } }
public async Task <IActionResult> GetContent(int desaId, string contentType, string contentSubtype = null) { Stopwatch sw = new Stopwatch(); sw.Start(); var auth = GetAuth(desaId); if (auth == null) { return(StatusCode((int)HttpStatusCode.Forbidden, new Dictionary <string, string>())); } var timestamp = QueryStringHelper.GetQueryString <int>(Request.Query, "timestamp", 0); var contentQuery = dbContext.SidekaContent .Where(sc => sc.DesaId == desaId) .Where(sc => sc.Timestamp > timestamp) .Where(sc => sc.Type == contentType) .Where(sc => sc.ApiVersion == "1.0"); if (!string.IsNullOrWhiteSpace(contentSubtype)) { contentQuery = contentQuery.Where(sc => sc.Subtype == contentSubtype); } var content = await contentQuery .OrderByDescending(sc => sc.Timestamp) .Select(sc => sc.Content) .FirstOrDefaultAsync(); if (string.IsNullOrWhiteSpace(content)) { return(StatusCode((int)HttpStatusCode.NotFound, new Dictionary <string, string>())); } sw.Stop(); await Logs((int)auth["user_id"], desaId, "", "get_content", contentType, contentSubtype, sw.Elapsed.Milliseconds); return(Ok(content)); }
public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { try { var param = QueryStringHelper.GetModelFromQueryString <TopModel>(req); return(new JsonResult(param)); } catch (Exception ex) { log.LogError(ex, ex.Message); Console.WriteLine(ex.StackTrace); return(new ContentResult { StatusCode = 500, Content = ex.Message }); } }
public async Task <JArray> GetEventsAsync(NewFilterInput filterInput, long blockFrom, long blockTo) { var parameters = new { module = "logs", action = "getLogs", fromBlock = blockFrom, toBlock = blockTo, address = filterInput.Address.First(), apikey = _options.ApiKey, topic0 = filterInput.Topics.Length > 0 ? filterInput.Topics[0] : null, topic1 = filterInput.Topics.Length > 1 ? filterInput.Topics[1] : null, topic2 = filterInput.Topics.Length > 2 ? filterInput.Topics[2] : null }; var url = _options.ApiUrl + QueryStringHelper.ToQueryString(parameters); var response = await GetJsonTimedAsync <EventsResult>(url); return(response.Result); }
public async Task <ActionResult> IndependentSchoolsSearch(IndSchoolsSearchViewModel viewModel) { await PopulateLookupData(viewModel); if (!string.Equals(viewModel.ActionName, IndSchoolsSearchViewModel.ActionSearch)) { ModelState.Clear(); } if (viewModel.MinDate.ToDateTime().HasValue&& viewModel.MaxDate.ToDateTime().HasValue&& viewModel.MinDate.ToDateTime() > viewModel.MaxDate.ToDateTime()) { ModelState.AddModelError("date-range", "Please use a valid date range"); } if (ModelState.IsValid) { switch (viewModel.ActionName) { case IndSchoolsSearchViewModel.ActionSearch: return(View("IndependentSchoolsSearchResults", viewModel.SetResults( new PaginatedResult <EstablishmentSearchResultModel>(viewModel.Skip, viewModel.Take, await _establishmentReadService.SearchAsync(await CreateIndSchoolSearchPayload(viewModel), User))))); case IndSchoolsSearchViewModel.ActionSaveSet: return(Redirect(string.Concat(Url.RouteUrl("CreatePredefinedLASet"), "?", QueryStringHelper.ToQueryString(IndSchoolsSearchViewModel.BindAliasForSelectedLocalAuthorityIds, viewModel.SelectedLocalAuthorityIds.ToArray())))); default: break; } } viewModel.LocalAuthoritySets = (await _localAuthoritySetRepository.GetAllAsync()).Items .OrderBy(x => x.Title) .Select(x => new IndSchoolsSearchViewModel.LASetViewModel(x)); return(View(viewModel)); }
private void InitData(int PageIndex, string name, int stateid) { this.Title = "链接列表"; // 设置标题 DataSet ds = new DataSet(); int recordcount = 0; //获取总条数 string where = string.Empty; if (!string.IsNullOrEmpty(name)) { where = "title like '%" + name + "%'"; } if (stateid >= 0) { if (!string.IsNullOrEmpty(where)) { where += " and "; } where += " stateid=" + stateid; ddlState.SelectedValue = stateid + ""; } int ppid = QueryStringHelper.GetInt("txtAID"); if (ppid > 0) { if (!string.IsNullOrEmpty(where)) { where += " and "; } where += " qicq='" + ppid + "'"; } //txtAID //搜索 ds = bll.GetList(AspNetPager1.PageSize, PageIndex, where, out recordcount); AspNetPager1.RecordCount = recordcount; this.rptBind.DataSource = ds.Tables[0].DefaultView; this.rptBind.DataBind(); }
/// <summary> /// /// </summary> /// <returns></returns> public ActionResult NewRegistrationfromSocialPage() { bool isFromSocialMedia = Convert.ToBoolean(QueryStringHelper.getValue("sm")); if (!isFromSocialMedia) { isFromSocialMedia = TempData["isFromSocialMedia"] == null ? false : (bool)TempData["isFromSocialMedia"]; } ViewBag.isFromSocialMedia = isFromSocialMedia; UserDomainLogic userDomainLogic = new UserDomainLogic(); BusinessDomainLogic businessDomainLogic = new BusinessDomainLogic(); UserProfile userProfile = userDomainLogic.FindUser(UserVariables.LoggedInUserGuid); CommonDomainLogic commonDomainLogic = new CommonDomainLogic(); userProfile.BusinessTypeList = businessDomainLogic.GetBusinessTypes(); userProfile.Cities = commonDomainLogic.GetCities(); userProfile.Cities.Add(new Domain.City { CityGuid = Guid.Empty, CityName = "Other", CityUrlName = "Other" }); ViewBag.isFromSocialMedia = isFromSocialMedia; return(View(userProfile)); }
public ReturnValue UpdateItemByCode() { try { string model = QueryStringHelper.GetString("model", ""); if (string.IsNullOrEmpty(model)) { returnValue.ErrorCode = 1; returnValue.ErrorMsg = "model不能为空"; return(returnValue); } string feemz = QueryStringHelper.GetString("feemz", ""); returnValue.ShowMsg = testDemoServices.GetLocHouseRoomName("feemz").GUID; return(returnValue); } catch (Exception ex) { returnValue.ErrorCode = 1; returnValue.ErrorMsg = ex.Message; return(returnValue); } }
private void InitFromDeepLinkingParams() { var action = Intent.Action; if (Intent.Data == null) { return; } try { var parsedOptions = QueryStringHelper.ParseQueryStringForAndroid(Intent.Data.Query); if (parsedOptions.ContainsKey(Constants.EMAIL_KEY)) { mEmail = parsedOptions[Constants.EMAIL_KEY]; } if (parsedOptions.ContainsKey(Constants.PASSWORD_KEY)) { mPassword = parsedOptions[Constants.PASSWORD_KEY]; } if (!string.IsNullOrWhiteSpace(mEmail)) { mEtEmail.Text = mEmail; } if (!string.IsNullOrWhiteSpace(mPassword)) { mEtPassword.Text = mPassword; } } catch (Exception ex) { ex.ToString(); throw ex; } }
protected virtual Task HandleWebResourceRequest(CoreWebView2WebResourceRequestedEventArgs eventArgs) { #if WEBVIEW2_WINFORMS || WEBVIEW2_WPF // Unlike server-side code, we get told exactly why the browser is making the request, // so we can be smarter about fallback. We can ensure that 'fetch' requests never result // in fallback, for example. var allowFallbackOnHostPage = eventArgs.ResourceContext == CoreWebView2WebResourceContext.Document || eventArgs.ResourceContext == CoreWebView2WebResourceContext.Other; // e.g., dev tools requesting page source var requestUri = QueryStringHelper.RemovePossibleQueryString(eventArgs.Request.Uri); if (TryGetResponseContent(requestUri, allowFallbackOnHostPage, out var statusCode, out var statusMessage, out var content, out var headers)) { var headerString = GetHeaderString(headers); eventArgs.Response = _coreWebView2Environment.CreateWebResourceResponse(content, statusCode, statusMessage, headerString); } #elif WEBVIEW2_MAUI // No-op here because all the work is done in the derived WinUIWebViewManager #endif return(Task.CompletedTask); }
void WebSingleSignon_Navigating(object sender, NavigatingEventArgs e) { App.Model.PendingServiceCalls++; if (e.Uri.ToString().StartsWith(RedirectUrl)) { var queryParams = QueryStringHelper.ParseQueryString(e.Uri.Query); string grantToken; if (queryParams.TryGetValue("grant_token", out grantToken)) { e.Cancel = true; App.Model.PendingServiceCalls = 0; var settings = IsolatedStorageSettings.ApplicationSettings; //grantToken = HttpUtility.UrlDecode(grantToken); //grantToken = grantToken.Replace("%7", "|"); //var regex = new Regex("grant_token=([^&]*)"); settings["grantToken"] = grantToken; settings.Save(); this.NavigationService.Navigate(new Uri("/Views/SplashPage.xaml", UriKind.Relative)); } } }
protected override void Initialize(HttpControllerContext controllerContext) { //获取token string uname = QueryStringHelper.GetString("tokencode"); //判断对比 if (string.IsNullOrEmpty(uname) || ConfigHelper.GetSettings("TokenCode") != uname) { //返回没有权限消息 ReturnValue result = new ReturnValue(); result.ErrorMsg = "tokencode令牌无效"; result.ErrorCode = 100; HttpContext.Current.Response.Write(JsonHelper.ObjectToJSON(result)); //var response= controllerContext.Request.CreateResponse(HttpStatusCode.OK); //response.Content = new StringContent(JsonHelper.ObjectToJSON(result), Encoding.UTF8, "application/json"); HttpContext.Current.Response.End(); } else { base.Initialize(controllerContext); } }
protected void ibtnAdd_Click(object sender, EventArgs e) { //验证代码 try { SiteConfig tempModel = new SiteConfig(); try { tempModel = bllSiteConfig.GetModel(hdfID.Value); } catch { } if (tempModel == null) { tempModel = new SiteConfig(); tempModel.description = txtDescription.Value; tempModel.title = txtTitle.Value; tempModel.mata = txtMata.Value; tempModel.footer = txtFooter.Value; tempModel.codeNo = QueryStringHelper.GetString("code"); bllSiteConfig.Add(tempModel); } else { tempModel.description = txtDescription.Value; tempModel.title = txtTitle.Value; tempModel.mata = txtMata.Value; tempModel.footer = txtFooter.Value; bllSiteConfig.Update(tempModel); } Msg.Show("保存成功!"); } catch (Exception ex) { log.Error(ex.Message); Msg.Show("网络错误!原因:" + ex.Message); } }
public override WebResourceResponse?ShouldInterceptRequest(AWebView?view, IWebResourceRequest?request) { if (request is null) { throw new ArgumentNullException(nameof(request)); } var allowFallbackOnHostPage = false; var requestUri = request?.Url?.ToString(); var appBaseUri = new Uri(AppOrigin); var fileUri = requestUri != null ? new Uri(requestUri) : null; if (fileUri != null && appBaseUri.IsBaseOf(fileUri)) { var relativePath = appBaseUri.MakeRelativeUri(fileUri).ToString(); if (string.IsNullOrEmpty(relativePath)) { // For app root, use host page (something like wwwroot/index.html) allowFallbackOnHostPage = true; } } requestUri = QueryStringHelper.RemovePossibleQueryString(requestUri); if (requestUri != null && _webViewHandler != null && _webViewHandler.WebviewManager != null && _webViewHandler.WebviewManager.TryGetResponseContentInternal(requestUri, allowFallbackOnHostPage, out var statusCode, out var statusMessage, out var content, out var headers)) { var contentType = headers["Content-Type"]; return(new WebResourceResponse(contentType, "UTF-8", statusCode, statusMessage, headers, content)); } return(base.ShouldInterceptRequest(view, request)); }
public void SetUp() { _sut = new QueryStringHelper(); }
public void QueryStringHelper_ParseQueryString_ShouldCreateEmptyOnEmptyString() { var collection = QueryStringHelper.ParseQueryString(""); collection.Should().BeEmpty(); }
public void QueryStringHelper_ParseQueryString_ThrowsOnNull() { Action a = () => QueryStringHelper.ParseQueryString(null); a.Should().Throw <ArgumentNullException>(); }
public async Task <IActionResult> GetContentV2(int desaId, string contentType, string contentSubtype = null) { Stopwatch sw = new Stopwatch(); sw.Start(); var auth = GetAuth(desaId); if (auth == null) { return(StatusCode((int)HttpStatusCode.Forbidden, new Dictionary <string, string>() { { "message", "Invalid or no token" } })); } var clientChangeId = 0; var changeId = QueryStringHelper.GetQueryString <int>(Request.Query, "changeId", 0); if (changeId > 0) { clientChangeId = changeId; } var sizeComparison = await GetSizeComparison(desaId, contentType, contentSubtype, clientChangeId); Log.Information("After comparing sizes {0}", sw.Elapsed); var contentQuery = dbContext.SidekaContent .Where(sc => sc.DesaId == desaId) .Where(sc => sc.Type == contentType) .Where(sc => sc.ChangeId >= clientChangeId); if (!string.IsNullOrWhiteSpace(contentSubtype)) { contentQuery = contentQuery.Where(sc => sc.Subtype == contentSubtype); } var contentId = await contentQuery.OrderByDescending(sc => sc.ChangeId).Select(sc => sc.Id).FirstOrDefaultAsync(); if (contentId == 0) { return(StatusCode((int)HttpStatusCode.NotFound, new Dictionary <string, string>())); } var sidekaContent = await dbContext.SidekaContent.FindAsync(contentId); Log.Information("After querying sd contents {0}", sw.Elapsed); dynamic content = JsonConvert.DeserializeObject <JObject>(sidekaContent.Content); Log.Information("After deserialized {0}", sw.Elapsed); if (sidekaContent.ApiVersion == "1.0") { content["columns"] = JArray.FromObject(new string[] { "nik", "nama_penduduk", "tempat_lahir", "tanggal_lahir", "jenis_kelamin", "pendidikan", "agama", "status_kawin", "pekerjaan", "pekerjaan_ped", "kewarganegaraan", "kompetensi", "no_telepon", "email", "no_kitas", "no_paspor", "golongan_darah", "status_penduduk", "status_tinggal", "kontrasepsi", "difabilitas", "no_kk", "nama_ayah", "nama_ibu", "hubungan_keluarga", "nama_dusun", "rw", "rt", "alamat_jalan" }); } var returnData = new Dictionary <string, object>() { { "success", true }, { "changeId", sidekaContent.ChangeId }, { "apiVersion", sidekaContent.ApiVersion }, { "columns", content["columns"] }, // TODO: remove this later { "change_id", sidekaContent.ChangeId }, }; Dictionary <string, object> diffs = null; if (sidekaContent.ChangeId == clientChangeId) { returnData.Add("diffs", new List <object>()); } else if (clientChangeId == 0 || sizeComparison["contentSize"] < sizeComparison["diffSize"]) { returnData.Add("data", content["data"]); } else { diffs = GetDiffsNewerThanClient(desaId, contentType, contentSubtype, clientChangeId, (JObject)content["columns"]); Log.Information("After get diff {0}", sw.Elapsed); returnData.Add("diffs", diffs); } Log.Information("After preparing return data {0}", sw.Elapsed); sw.Stop(); await Logs((int)auth["user_id"], desaId, "", "get_content", contentType, contentSubtype, sw.Elapsed.Milliseconds); Log.Information("After inserting logs {0}", sw.Elapsed); return(Ok(returnData)); }
public async Task <IActionResult> UpdateSizes(int desaId, string contentType, string contentSubtype = null) { var clientChangeId = 0; var changeId = QueryStringHelper.GetQueryString <int>(Request.Query, "changeId", 0); if (changeId > 0) { clientChangeId = changeId; } var contentQuery = dbContext.SidekaContent .Where(sc => sc.DesaId == desaId) .Where(sc => sc.Type == contentType) .Where(sc => sc.Subtype == contentSubtype) .Where(sc => sc.ChangeId >= clientChangeId); var sidekaContents = await contentQuery.OrderByDescending(sc => sc.ChangeId).ToListAsync(); var sizes = new List <Dictionary <string, int> >(); var result = new Dictionary <string, object>() { { "success", true }, { "content", sizes } }; foreach (var sidekaContent in sidekaContents) { var sidekaContentJObject = JsonConvert.DeserializeObject <JObject>(sidekaContent.Content); var sizeItem = new Dictionary <string, int>(); try { var content = new SidekaContentViewModel(sidekaContentJObject); var contentSize = ASCIIEncoding.Unicode.GetByteCount(JsonConvert.SerializeObject(content.Data)); var diffSize = ASCIIEncoding.Unicode.GetByteCount(JsonConvert.SerializeObject(content.Diffs)); sizeItem.Add("contentSize", contentSize); if (content.Diffs == null) { sizeItem.Add("diffSize", 0); } else { sizeItem.Add("diffSize", diffSize); } sidekaContent.ContentSize = contentSize; sidekaContent.DiffSize = diffSize; dbContext.Update(sidekaContent); await dbContext.SaveChangesAsync(); sizes.Add(sizeItem); } catch (Exception ex) { } } return(Ok(result)); }
/// <summary> /// Returns the Query as a query string /// Example : "query= distinct=0" /// </summary> public string ToQueryString() { return(QueryStringHelper.ToQueryString(this)); }
public async Task GetCharge_SearchFilterByReferenceMonth_ReturnsTrue(ChargeSearchMessage search, ChargeMessage charge) { // Arrange IHttpConnector connector = HttpConnectorHelper.GetChargeConnector(); await connector.PostAsync <ChargeMessage, bool>(string.Empty, charge); // Act IApplicationResult <List <ChargeMessage> > result = await connector.GetAsync <List <ChargeMessage> >(QueryStringHelper.GetChargeSearch(search)); // Assert Assert.True(result.Data.Count > 0); Assert.NotNull(result.Data.FirstOrDefault(it => it.Cpf == charge.Cpf)); }
public static FormUrlEncodedContent FromObject(object value) { return(new FormUrlEncodedContent(QueryStringHelper.ToKeyValue(value) ?? new Dictionary <string, string>())); }
private void InitData(int PageIndex, string name, int parentId) { this.Title = "列表"; // 设置标题 DataSet ds = new DataSet(); int recordcount = 0; //获取总条数 string wheStr = string.Empty; int sHotid = QueryStringHelper.GetInt("sHotID"); if (sHotid == 1) { chkIsHot.Checked = true; wheStr = "isHot=1"; } int sTjid = QueryStringHelper.GetInt("sTuiJian"); if (sTjid == 1) { chkTuiJian.Checked = true; if (!string.IsNullOrEmpty(wheStr)) { wheStr += " and "; } wheStr += " isTuijian=1"; } int siscx = QueryStringHelper.GetInt("iscx"); if (siscx == 1) { chkIsCX.Checked = true; if (!string.IsNullOrEmpty(wheStr)) { wheStr += " and "; } wheStr += " desFild1=1"; } if (!name.Equals(string.Empty) || parentId != -1) { ddlType.SelectedValue = parentId + ""; //搜索 ds = bll.GetSearchNameList(AspNetPager1.PageSize, PageIndex, name, parentId, wheStr, out recordcount); try { txtSearchName.Text = name; } catch { } } else { ds = bll.GetAllListByCodeNo(AspNetPager1.PageSize, PageIndex, CodeNo, wheStr, out recordcount); } AspNetPager1.RecordCount = recordcount; DataTable dt = ds.Tables[0]; if (dt.Rows.Count > 0) { dt.Columns.Add("pcodeNo", typeof(string)); foreach (DataRow dr in dt.Rows) { dr["pcodeNo"] = codeNo; } } this.rptBind.DataSource = ds.Tables[0].DefaultView; this.rptBind.DataBind(); }
public async Task <IActionResult> PostContentV2([FromBody] JObject contentJObject, int desaId, string contentType, string contentSubtype = null) { Stopwatch sw = new Stopwatch(); sw.Start(); string lockName = desaId + "_" + contentType + "_" + contentSubtype; object writeLock = writeLocks.GetOrAdd(lockName, new object()); lock (writeLock){ var auth = GetAuth(desaId); if (auth == null) { return(StatusCode((int)HttpStatusCode.Forbidden, new Dictionary <string, string>() { { "message", "Invalid or no token" } })); } var permission = contentType; if (new string[] { "perencanaan", "penganggaran", "spp", "penerimaan" }.Contains(contentType)) { permission = "keuangan"; } var roles = (List <string>)auth["roles"]; if (!roles.Contains("administrator") && !roles.Contains(permission)) { return(StatusCode((int)HttpStatusCode.Forbidden, new Dictionary <string, string>() { { "message", "Your account doesn't have the permission" } })); } var content = new SidekaContentViewModel(contentJObject); // Validate foreach (var column in content.Columns) { if (content.Diffs != null && content.Diffs.ContainsKey(column.Key)) { var index = 0; foreach (var diff in content.Diffs[column.Key]) { var location = string.Format("Diff {0} ({1}) tab {2}", index, "added", column.Key); var invalid = Validate(column.Value, diff.Added, location); if (invalid != null) { return(invalid); } location = string.Format("Diff {0} ({1}) tab {2}", index, "modified", column.Key); invalid = Validate(column.Value, diff.Modified, location); if (invalid != null) { return(invalid); } location = string.Format("Diff {0} ({1}) tab {2}", index, "deleted", column.Key); invalid = Validate(column.Value, diff.Deleted, location, false); if (invalid != null) { return(invalid); } } } if (content.Data != null && content.Data.ContainsKey(column.Key)) { var location = string.Format("Data tab {0}", column.Key); var invalid = Validate(column.Value, content.Data[column.Key], location); if (invalid != null) { return(invalid); } } } var clientChangeId = 0; var changeId = QueryStringHelper.GetQueryString <int>(Request.Query, "changeId", 0); if (changeId > 0) { clientChangeId = changeId; } // Find max change id var maxChangeIdQuery = dbContext.SidekaContent .Where(sc => sc.DesaId == desaId) .Where(sc => sc.Type == contentType); if (!string.IsNullOrWhiteSpace(contentSubtype)) { maxChangeIdQuery = maxChangeIdQuery.Where(sc => sc.Subtype == contentSubtype); } var maxChangeId = maxChangeIdQuery.Select(sc => sc.ChangeId).DefaultIfEmpty(0).Max(); // TODO: This is risky!! Consider changing change_id column to serial or autoincrement var newContent = new SidekaContentViewModel(); // Initialize new content to be saved foreach (var column in content.Columns) { newContent.Data[column.Key] = new List <object>().ToArray(); newContent.Columns[column.Key] = column.Value; if (content.Diffs != null && content.Diffs.ContainsKey(column.Key)) { newContent.Diffs[column.Key] = content.Diffs[column.Key]; } else { newContent.Diffs[column.Key] = new List <SidekaDiff>().ToArray(); } } var latestContentQuery = dbContext.SidekaContent .Where(sc => sc.DesaId == desaId) .Where(sc => sc.Type == contentType); if (!string.IsNullOrWhiteSpace(contentSubtype)) { latestContentQuery = latestContentQuery.Where(sc => sc.Subtype == contentSubtype); } var latestContentString = latestContentQuery .OrderByDescending(sc => sc.ChangeId) .Select(sc => sc.Content) .FirstOrDefault(); JObject latestContentJObject = null; if (string.IsNullOrWhiteSpace(latestContentString)) { latestContentJObject = new JObject { { "data", new JObject() }, { "columns", contentJObject["columns"] } }; } else { latestContentJObject = JsonConvert.DeserializeObject <JObject>(latestContentString); } var diffs = GetDiffsNewerThanClient(desaId, contentType, contentSubtype, clientChangeId, (JObject)contentJObject["columns"]); if (latestContentJObject["data"] is JArray && contentType == "penduduk") { newContent.Data["penduduk"] = MergeDiffs(newContent.Columns["penduduk"], newContent.Diffs["penduduk"], new List <object>().ToArray()); } else { var latestContent = new SidekaContentViewModel(latestContentJObject); foreach (var column in content.Columns) { // Initialize so the latest content have the same tab with the posted content if (!latestContent.Columns.ContainsKey(column.Key)) { latestContent.Columns[column.Key] = column.Value; } if (!latestContent.Data.ContainsKey(column.Key)) { latestContent.Data[column.Key] = new List <object>().ToArray(); } if (content.Data != null && content.Data[column.Key] != null && new string[] { "perencanaan", "penganggaran", "penerimaan", "spp" }.Contains(contentType)) { var invalid = ValidateDuplicatesData(column.Key, column.Value, content.Data[column.Key]); if (invalid != null) { return(invalid); } // Special case for client who posted data instead of diffs newContent.Data[column.Key] = content.Data[column.Key]; // Add new diffs to show that the content is rewritten var sidekaDiff = new SidekaDiff { Added = new List <object>().ToArray(), Modified = new List <object>().ToArray(), Deleted = new List <object>().ToArray(), Total = 0, Rewritten = true }; newContent.Diffs[column.Key].Append(sidekaDiff); } else if (newContent.Diffs[column.Key].Length > 0) { // There's diffs in the posted content for this tab, apply them to latest data var latestColumns = latestContent.Columns[column.Key]; var transformedLatestData = TransformData( latestContentJObject["columns"][column.Key], contentJObject["columns"][column.Key], latestContent.Data[column.Key]); var invalid = ValidateDuplicatesDiffs(column.Key, column.Value, content.Diffs[column.Key], transformedLatestData); if (invalid != null) { return(invalid); } var mergedData = MergeDiffs(column.Value, content.Diffs[column.Key], transformedLatestData); newContent.Data[column.Key] = mergedData; newContent.Columns[column.Key] = column.Value; } else { // There's no diffs in the posted content for this tab, use the old data newContent.Data[column.Key] = latestContent.Data[column.Key]; } } } var contentSize = ASCIIEncoding.Unicode.GetByteCount(JsonConvert.SerializeObject(newContent.Data)); var diffSize = ASCIIEncoding.Unicode.GetByteCount(JsonConvert.SerializeObject(newContent.Diffs)); int newChangeId = GetNextChangeId(desaId, contentType, contentSubtype); var sidekaContent = new SidekaContent { DesaId = desaId, Type = contentType, Subtype = contentSubtype, Content = JsonConvert.SerializeObject(newContent), DateCreated = DateTime.Now, CreatedBy = (int)auth["user_id"], ChangeId = newChangeId, ApiVersion = configuration.GetValue <string>("ApiVersion"), ContentSize = contentSize, DiffSize = diffSize }; dbContext.Add(sidekaContent); dbContext.SaveChanges(); var result = new Dictionary <string, object>() { { "success", true }, { "changeId", newChangeId }, { "change_id", newChangeId }, { "diffs", diffs }, { "columns", content.Columns }, }; sw.Stop(); Logs((int)auth["user_id"], desaId, "", "save_content", contentType, contentSubtype, sw.Elapsed.Milliseconds); return(Ok(result)); } }
/// <summary> /// The render service options. /// </summary> /// <param name="output"> /// The output. /// </param> /// <param name="source"> /// The source. /// </param> /// <param name="controlId"> /// The control id. /// </param> protected void RenderServiceOptions(HtmlTextWriter output, string source, string controlId) { // TODO: Ed, this appears to be very CW centric, can we make it more generalized in name? var current = Client.GetItemNotNull(this.ItemID, global::Sitecore.Context.ContentDatabase); var siteItem = current.Axes.SelectSingleItem("ancestor-or-self::*[contains(@@templatename, 'Site')]"); var luceneQuery = source.Replace("lucene:", string.Empty); var qh = new QueryStringHelper(luceneQuery); var templateid = qh.GetByName("templateid"); var fullSiteSearch = false; if (qh.NameExists("fullsite")) { fullSiteSearch = qh.GetByName<bool>("fullsite"); } using (output.RenderTag(HtmlTextWriterTag.Script, new HtmlAttribute("type", "text/javascript"))) { output.WriteLine("jQuery(\"#{0}\").tokenInput(\"/tokenizedlisthandler.axd\", ".FormatWith(controlId)); output.WriteLine("{theme: \"facebook\", "); output.WriteLine("tokenDelimiter: \"|\", "); output.WriteLine("preventDuplicates: true, "); output.WriteLine("makeSortable: true, "); output.WriteLine("minChars: 3,"); output.WriteLine("luceneFullSite: \"{0}\",".FormatWith(fullSiteSearch)); output.WriteLine("luceneLanguage: \"{0}\",".FormatWith(this.ItemLanguage)); if (siteItem != null && !fullSiteSearch) { output.WriteLine("luceneSiteName: \"{0}\",".FormatWith(siteItem.Key)); } if (!string.IsNullOrEmpty(templateid)) { output.WriteLine("luceneTemplateId: \"{0}\",".FormatWith(templateid)); } output.WriteLine("parseName: function(item) { "); output.WriteLine(" if (typeof item.site !== \"undefined\") { "); output.WriteLine(" if (item.site == null) { "); output.WriteLine(" return \"Unmatched People >\" + item.name; "); output.WriteLine(" } else {"); output.WriteLine(" return item.site + \" >\" + item.name; "); output.WriteLine(" } "); output.WriteLine(" } "); output.WriteLine(" return item.name; "); output.WriteLine("}, "); output.WriteLine("disabled: " + this.Disabled.ToString().ToLowerInvariant()); if (fullSiteSearch) { this.RenderValueWithSite(output); } else { this.RenderValue(output); } output.WriteLine("});"); } }
public async Task <ActionResult> IndexResults(SearchViewModel viewModel) { if (!viewModel.NoResults) { if (viewModel.LocalAuthorityToRemove.HasValue) { return(Redirect("/?" + QueryStringHelper.ToQueryString(SearchViewModel.BIND_ALIAS_LAIDS, viewModel.RemoveLocalAuthorityId(viewModel.LocalAuthorityToRemove.Value).SelectedLocalAuthorityIds.ToArray()) + "#la")); } if (viewModel.SearchType.HasValue) { if (viewModel.SearchType == eSearchType.LocalAuthorityDisambiguation) { return(await ProcessLocalAuthorityDisambiguation(viewModel)); } if (viewModel.SearchType == eSearchType.ByLocalAuthority && !string.IsNullOrEmpty(viewModel.LocalAuthorityToAdd)) { return(await ProcessLocalAuthorityDisambiguation(viewModel)); } if (ModelState.IsValid) { if (viewModel.SearchType == eSearchType.Location && LatLon.Parse(viewModel.LocationSearchModel.AutoSuggestValue) == null && !viewModel.LocationSearchModel.Text.IsNullOrEmpty()) { var disambiguationResult = await ProcessLocationDisambiguation(viewModel.LocationSearchModel.Text); if (disambiguationResult != null) { return(disambiguationResult); } } if (viewModel.SearchType.OneOfThese(eSearchType.ByLocalAuthority, eSearchType.Location, eSearchType.Text, eSearchType.EstablishmentAll)) { var url = Url.Action("Index", "EstablishmentsSearch", new { area = "Establishments" }); url = viewModel.OpenOnly ? $"{url}?{Request.QueryString.AddIfNonExistent(SearchViewModel.BIND_ALIAS_STATUSIDS, (int)eStatus.Open, (int)eStatus.OpenButProposedToClose)}" : $"{url}?{Request.QueryString.AddIfNonExistent("OpenOnly", "false")}"; return(Redirect(url)); } if (viewModel.SearchType.OneOfThese(eSearchType.Group, eSearchType.GroupAll)) { return(Redirect(Url.Action("Index", "GroupSearch", new { area = "Groups" }) + "?" + Request.QueryString)); } if (viewModel.SearchType.OneOfThese(eSearchType.Governor, eSearchType.GovernorReference, eSearchType.GovernorAll)) { return(Redirect( $"{Url.Action("Index", "GovernorSearch", new { area = "Governors" })}?{Request.QueryString}&{string.Join("&", viewModel.GovernorSearchModel.RoleId.Select(r => $"&{Areas.Governors.Models.GovernorSearchViewModel.BIND_ALIAS_ROLE_ID}={r}"))}")); } throw new NotSupportedException($"The search type '{viewModel.SearchType}' is not recognised."); } } } return(await Index(viewModel)); }
public async Task <ActionResult> Index(SearchViewModel viewModel) { if (!viewModel.NoResults) { if (viewModel.LocalAuthorityToRemove.HasValue) { return(Redirect("/?" + QueryStringHelper.ToQueryString(SearchViewModel.BIND_ALIAS_LAIDS, viewModel.RemoveLocalAuthorityId(viewModel.LocalAuthorityToRemove.Value).SelectedLocalAuthorityIds.ToArray()) + "#la")); } if (viewModel.SearchType.HasValue) { if (viewModel.SearchType == eSearchType.LocalAuthorityDisambiguation) { return(await ProcessLocalAuthorityDisambiguation(viewModel)); } if (ModelState.IsValid) { if (viewModel.SearchType == eSearchType.Location && LatLon.Parse(viewModel.LocationSearchModel.AutoSuggestValue) == null && !viewModel.LocationSearchModel.Text.IsNullOrEmpty()) { var disambiguationResult = await ProcessLocationDisambiguation(viewModel.LocationSearchModel.Text); if (disambiguationResult != null) { return(disambiguationResult); } } } else if (viewModel.SearchType == eSearchType.GovernorReference) { var fieldError = viewModel.GovernorSearchModel.Gid.HasValue ? "We could not find any governors matching your search criteria" : "Please enter a governor ID to start a search"; viewModel.ErrorPanel = "GovernorId"; ModelState.AddModelError("GovernorSearchModel.Gid", fieldError); } } } else { var fieldId = "TextSearchModel.Text"; var fieldError = "We could not find any establishments matching your search criteria"; var la = Request.QueryString["LocalAuthorityToAdd"]; switch (viewModel.SearchType) { case eSearchType.Text: if (viewModel.TextSearchModel.Text.IsNullOrEmpty()) { fieldError = "Please enter an establishment name, URN, LAESTAB or UKPRN to start a search"; } viewModel.ErrorPanel = "Name"; break; case eSearchType.Location: fieldId = "LocationSearchModel.Text"; fieldError = "Please enter a postcode, town or city to start a search"; viewModel.ErrorPanel = "Location"; break; case eSearchType.ByLocalAuthority: if (!string.IsNullOrEmpty(viewModel.LocalAuthorityToAdd)) { return(await ProcessLocalAuthorityDisambiguation(viewModel)); } fieldId = "LocalAuthorityToAdd"; fieldError = viewModel.SelectedLocalAuthorityIds.Any() ? "We could not find any local authorities matching your search criteria" : "Please enter a local authority to start a search"; viewModel.ErrorPanel = "LocalAuthority"; break; case eSearchType.Group: fieldId = "GroupSearchModel.Text"; fieldError = viewModel.GroupSearchModel.Text.IsNullOrEmpty() ? "Please enter an establishment group to start a search" : "We could not find any establishment groups matching your search criteria"; viewModel.ErrorPanel = "Group"; break; case eSearchType.Governor: fieldId = "GovernorSearchModel.Forename"; fieldError = viewModel.GovernorSearchModel.Forename.IsNullOrEmpty() && viewModel.GovernorSearchModel.Surname.IsNullOrEmpty() && viewModel.GovernorSearchModel.RoleId.Length == 0 ? "Please enter a governor to start a search" : "We could not find any governors matching your search criteria"; viewModel.ErrorPanel = "Governor"; break; case eSearchType.GovernorReference: fieldId = "GovernorSearchModel.Gid"; fieldError = viewModel.GovernorSearchModel.Gid.HasValue ? "We could not find any governors matching your search criteria" : "Please enter a governor ID to start a search"; viewModel.ErrorPanel = "GovernorId"; break; } ModelState.AddModelError(fieldId, fieldError); } viewModel.LocalAuthorities = (await _cachedLookupService.LocalAuthorityGetAllAsync()).OrderBy(x => x.Name).Select(x => new LookupItemViewModel(x)); viewModel.GovernorRoles = (await _cachedLookupService.GovernorRolesGetAllAsync()).OrderBy(x => x.Name).Select(x => new LookupItemViewModel(x)); return(View("Index", viewModel)); }
/// <summary> /// Creates a fully formatted url for use with building page links. /// </summary> /// <param name="page">The page number.</param> /// <returns>The fully formatted url.</returns> private string CreateUrl(int page) { var request = HttpContext.Current.Request; var helper = new QueryStringHelper(request.Url.Query); helper.AddOrReplace("page", page.ToString(CultureInfo.InvariantCulture)); var returnUri = new UriBuilder(request.Url.Scheme, request.Url.Host, request.Url.Port) { Path = request.Url.AbsolutePath, Query = helper.GetQueryString() }; return returnUri.ToString(); }
private Uri MapProtocolLaunchUri(Uri uri) { string originalString = uri.OriginalString; Dictionary <string, string> parametersAsDict = QueryStringHelper.GetParametersAsDict(originalString); string str1 = "/VKClient.Common;component/NewsPage.xaml"; string str2; if (parametersAsDict.ContainsKey("encodedLaunchUri")) { str2 = HttpUtility.UrlDecode(parametersAsDict["encodedLaunchUri"]); if (parametersAsDict.ContainsKey("sourceAppIdentifier")) { string str3 = parametersAsDict["sourceAppIdentifier"]; if (str2.Contains("/?")) { str2 = str2.Replace("/?", "?"); } string oldValue = "vkappconnect://authorize"; if (!str2.StartsWith(oldValue)) { if (str2.StartsWith("vk://")) { return(new Uri(NavigatorImpl.GetOpenUrlPageStr(str2.Replace("vk://", "https://vk.com/")), UriKind.Relative)); } MessageBox.Show("Unsupported protocol: " + str2); str2 = str1; } else if (str2.Contains("RedirectUri=vkc")) { MessageBox.Show("Unsupported redirect uri. Please, use the latest version of WP SDK."); str2 = str1; } else { str2 = str2.Replace(oldValue, "/VKClient.Common;component/SDKAuthPage.xaml") + "&SDKGUID=" + str3.ToLowerInvariant(); } } else if (str2.StartsWith("fb128749580520227://authorize")) { if (((UriMapperBase) new FacebookUriMapper()).MapUri(uri).OriginalString.StartsWith("/SuccessfulFacebookLogin.xaml")) { return(new Uri("/VKClient.Common;component/FriendsImportFacebookPage.xaml", UriKind.Relative)); } } else if (str2.StartsWith("com.vk.vkclient:/gmail-oauth/code")) { Dictionary <string, string> queryString = CustomUriMapper.ParseQueryString(str2); if (queryString != null && queryString.ContainsKey("code")) { string str3 = queryString["code"]; if (!string.IsNullOrEmpty(str3)) { return(new Uri(string.Format("/VKClient.Common;component/FriendsImportGmailPage.xaml?code={0}", str3), UriKind.Relative)); } } } else if (str2.StartsWith("com.vk.vkclient://twitter-oauth/callback")) { Dictionary <string, string> queryString = CustomUriMapper.ParseQueryString(str2); if (queryString != null && queryString.ContainsKey("oauth_token") && queryString.ContainsKey("oauth_verifier")) { string str3 = queryString["oauth_token"]; string str4 = queryString["oauth_verifier"]; if (!string.IsNullOrEmpty(str3) && !string.IsNullOrEmpty(str4)) { return(new Uri(string.Format("/VKClient.Common;component/FriendsImportTwitterPage.xaml?oauthToken={0}&oauthVerifier={1}", str3, str4), UriKind.Relative)); } } } } else { MessageBox.Show("Unable to identify source app or uri launch from uri " + originalString); str2 = str1; } return(new Uri(str2, UriKind.Relative)); }
public void GetWithQueryString() { var fields = "abc"; var url = QueryHelpers.AddQueryString("http://www.google.com", QueryStringHelper.ToKeyValue(fields)); }