public void RequestComplete(object sender, ApiCall.OnResponseEventArgs e) { var response = e.Response; var statusCode = response.Status; Log.DebugFormat("Getting http status code handler's for the status {0} ({1})", (int)statusCode, statusCode); var handlers = new List<IHttpStatusCodeExceptionHandler>(); foreach (var httpStatusCodeExceptionHandler in _httpStatusCodeExceptionHandlers) { if (httpStatusCodeExceptionHandler.StatusCode == statusCode) { handlers.Add(httpStatusCodeExceptionHandler); } } switch (handlers.Count) { case 0: Log.DebugFormat("A handler was not found for the status code {0} ({1})", (int)statusCode, statusCode); break; case 1: Log.DebugFormat("The handler {0} was returned for the status code {0} ({1})", (int)statusCode, statusCode); handlers[0].Handle(response); break; default: Log.ErrorFormat("{0} handlers were found for the status code {1} {2}", handlers.Count, (int)statusCode, statusCode); throw new ArgumentOutOfRangeException(string.Format("More than one exception handler found for the status code {0}", statusCode)); } }
// Perform a relayr API operation. Takes the operation, URI arguments, and a dictionary // of key -> value pairs (which will be converted to a JSON string) for operation content public async Task<HttpResponseMessage> PerformHttpOperation(ApiCall operation, string[] arguments, Dictionary<string, string> content) { // Get the URI extension and opration type from the attributes of the operation Type type = operation.GetType(); FieldInfo field = type.GetRuntimeField(operation.ToString()); string uriExtension = ((UriAttribute) field.GetCustomAttribute(typeof(UriAttribute), false)).Value; string operationType = ((OperationType) field.GetCustomAttribute(typeof(OperationType), false)).Value; // Add the arguments to the URI, if required uriExtension = processArguments(uriExtension, arguments); // Create the content json, if required StringContent contentJson = null; if (content != null) { contentJson = new StringContent(createContentJson(content)); contentJson.Headers.ContentType = new MediaTypeHeaderValue("application/json"); } // Set up the http request HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod(operationType); httpRequest.RequestUri = new Uri(uriExtension, UriKind.Relative); httpRequest.Content = contentJson; // Send the http request, return the response message try { return await _httpClient.SendAsync(httpRequest); } catch(ProtocolViolationException e) { throw new InvalidOperationException("Cannot send content with operation of type " + operationType, e); } }
public void Login_Clicked(object sender, EventArgs e) { //if(txtEmail.Text == "giulio.ises") //{ // Navigation.PushAsync(new HomePage()); //} var apiCall = new ApiCall(); apiCall.Post<Users, List<UserResult>>("auth", new Users() { useremail = txtEmail.Text, userpassword = txtSenha.Text }).ContinueWith(t => { if (!t.IsCanceled && !t.IsFaulted) { Device.BeginInvokeOnMainThread(() => { App.Current.MainPage = new NavigationPage(new MoveU.Page.Home()); }); } else { Device.BeginInvokeOnMainThread(() => { DisplayAlert("Faio", "Deu erro ze", "Belz?"); }); } }); }
public async void OnLocationChanged (Location location) { _currentLocation = location; if (_currentLocation == null) { _locationText.Text = "Unable to determine your location. Try again in a short while."; Insights.Track ("UnableToDetermineLocation"); } else { _locationText.Text = string.Format ("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude); Address address = await ReverseGeocodeCurrentLocation (); DisplayAddress (address); } var apiCall = new ApiCall (); await apiCall.Post<TestDriveLog, List<TestDriveLog>> ("test-drive-log", new TestDriveLog () { test_drive_id = 1, latitude = _currentLocation.Latitude, longitude = _currentLocation.Longitude }).ContinueWith (t => { var tData = new Dictionary<string, string>{ {"Status", t.Status.ToString()}, {"Task", t.ToString()}, }; if(t.IsCanceled) { Insights.Track ("ApiCallCanceled", tData); } else if(t.IsFaulted) { Insights.Track ("ApiCallFaulted", tData); } else if(t.IsCompleted) { Insights.Track ("ApiCallCompleted", tData); } else { Insights.Track ("ApiCallUnknown", tData); } }); }
public Login() { Title = "WhoAmIEAC"; InitializeComponent(); NavigationPage.SetHasNavigationBar(this, false); WhoAmI.ApiCall apiCall = new ApiCall (); List<RegistroPonto> lista = apiCall.GetResponse<List<RegistroPonto>> ("registrosDiaModulo", "1").ContinueWith(t => { //O ContinueWith é responsavel por fazer algo após o request finalizar //Aqui verificamos se houve problema ne requisição if (t.IsFaulted) { //Debug.WriteLine(t.Exception.Message); Device.BeginInvokeOnMainThread(() => { DisplayAlert("Falha", "Ocorreu um erro na Requisição :(", "Ok"); }); } //Aqui verificamos se a requisição foi cancelada por algum Motivo else if (t.IsCanceled) { //Debug.WriteLine("Requisição cancelada"); Device.BeginInvokeOnMainThread(() => { DisplayAlert("Cancela", "Requisição Cancelada :O", "Ok"); }); } //Caso a requisição ocorra sem problemas, cairemos aqui else { //Se Chegarmos aqui, está tudo ok, agora itemos tratar nossa Lista //Aqui Usaremos a Thread Principal, ou seja, a que possui as references da UI Device.BeginInvokeOnMainThread(() => { //ListRanking.ItemsSource = t.Result; }); } }); }
private ApiCall QuoteList(IEnumerable syntaxList, string name) { IEnumerable <object> sourceList = syntaxList.Cast <object>(); string methodName = SyntaxFactory("List"); string listType = null; var propertyType = syntaxList.GetType(); if (propertyType.IsGenericType) { var methodType = propertyType.GetGenericArguments()[0].Name; listType = methodType; if (propertyType.GetGenericTypeDefinition() == typeof(SeparatedSyntaxList <>)) { listType = "SyntaxNodeOrToken"; methodName = SyntaxFactory("SeparatedList"); sourceList = ((SyntaxNodeOrTokenList) syntaxList.GetType().GetMethod("GetWithSeparators").Invoke(syntaxList, null)) .Cast <object>() .ToArray(); } methodName += "<" + methodType + ">"; } if (propertyType.Name == "SyntaxTokenList") { methodName = SyntaxFactory("TokenList"); } if (propertyType.Name == "SyntaxTriviaList") { methodName = SyntaxFactory("TriviaList"); } var elements = new List <object>(sourceList .Select(o => Quote(o)) .Where(cb => cb != null)); if (elements.Count == 0) { return(null); } else if (elements.Count == 1) { if (methodName.StartsWith("List")) { methodName = "SingletonList" + methodName.Substring("List".Length); } if (methodName.StartsWith(SyntaxFactory("List"))) { methodName = SyntaxFactory("SingletonList") + methodName.Substring(SyntaxFactory("List").Length); } if (methodName.StartsWith("SeparatedList")) { methodName = "SingletonSeparatedList" + methodName.Substring("SeparatedList".Length); } if (methodName.StartsWith(SyntaxFactory("SeparatedList"))) { methodName = SyntaxFactory("SingletonSeparatedList") + methodName.Substring(SyntaxFactory("SeparatedList").Length); } } else { elements = new List <object> { new ApiCall( "methodName", "new " + listType + "[]", elements, useCurliesInsteadOfParentheses: true) }; } var codeBlock = new ApiCall(name, methodName, elements); return(codeBlock); }
public PagedListViewModel <TextContentViewModel> Search(Guid FolderId, string Keyword, ApiCall call) { var sitedb = call.WebSite.SiteDb(); if (string.IsNullOrWhiteSpace(Keyword) || FolderId == default(Guid)) { return(new PagedListViewModel <TextContentViewModel>()); } int pagesize = ApiHelper.GetPageSize(call, 50); int pagenr = ApiHelper.GetPageNr(call); string language = string.IsNullOrEmpty(call.Context.Culture) ? call.WebSite.DefaultCulture : call.Context.Culture; PagedListViewModel <TextContentViewModel> model = new PagedListViewModel <TextContentViewModel>(); model.PageNr = pagenr; model.PageSize = pagesize; var all = sitedb.TextContent.Query.Where(o => o.FolderId == FolderId).SelectAll(); var textContents = all.Where(o => o.Body.IndexOf(Keyword, StringComparison.OrdinalIgnoreCase) > -1).OrderByDescending(o => o.LastModified); model.TotalCount = textContents.Count(); model.TotalPages = ApiHelper.GetPageCount(model.TotalCount, model.PageSize); var list = textContents.OrderByDescending(o => o.LastModified).Skip(model.PageNr * model.PageSize - model.PageSize).Take(model.PageSize).ToList(); var contenttype = call.Context.WebSite.SiteDb().ContentTypes.GetByFolder(FolderId); model.List = new List <TextContentViewModel>(); foreach (var item in list) { model.List.Add(Sites.Helper.ContentHelper.ToListDisplayView(item, contenttype, language)); } return(model); }
/// <summary> /// Enumerating site collections using Graph Sites endpoint. Only works when using application permissions with Sites.Read.All or higher! /// </summary> internal async static Task <List <ISiteCollection> > GetViaGraphSitesApiAsync(PnPContext context) { List <ISiteCollection> loadedSites = new List <ISiteCollection>(); ApiCall sitesEnumerationApiCall = new ApiCall("sites?$select=sharepointIds,id,webUrl,displayName,root", ApiType.Graph); bool paging = true; while (paging) { var result = await(context.Web as Web).RawRequestAsync(sitesEnumerationApiCall, HttpMethod.Get).ConfigureAwait(false); #region Json response /* * "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites", * "@odata.nextLink": "https://graph.microsoft.com/v1.0/sites?$skiptoken=UGFnZWQ9VFJVRSZwX0ZpbGVMZWFmUmVmPTE3MjgyXy4wMDAmcF9JRD0xNzI4Mg", * "value": [ * { * "createdDateTime": "2017-11-13T10:10:59Z", * "id": "bertonline.sharepoint.com,84285b61-b18d-45eb-97c7-014614efa7bc,71fe5817-15b4-4e6a-aeb4-b95c5fe9c31f", * "lastModifiedDateTime": "2021-09-24T09:55:42.8767445Z", * "name": "ESPC 2017 test", * "displayName": "ESPC 2017 test", * "webUrl": "https://bertonline.sharepoint.com/sites/espctest1", * "sharepointIds": { * "siteId": "84285b61-b18d-45eb-97c7-014614efa7bc", * "siteUrl": "https://bertonline.sharepoint.com/sites/espctest1", * "tenantId": "d8623c9e-30c7-473a-83bc-d907df44a26e", * "webId": "71fe5817-15b4-4e6a-aeb4-b95c5fe9c31f" * }, * "siteCollection": { * "hostname": "bertonline.sharepoint.com" * }, * "root": {} * }, * { * "createdDateTime": "2016-10-10T07:35:53Z", * "id": "bertonline.sharepoint.com,0fac3e8a-4157-433f-9cfd-0b10a41cd7b7,074c0dc1-274c-4f92-8a6a-15a3b9088b9b", * "lastModifiedDateTime": "2021-09-24T09:55:42.9236211Z", * "name": "ab1", * "displayName": "ab1", * "webUrl": "https://bertonline.sharepoint.com/sites/ab1", * "sharepointIds": { * "siteId": "0fac3e8a-4157-433f-9cfd-0b10a41cd7b7", * "siteUrl": "https://bertonline.sharepoint.com/sites/ab1", * "tenantId": "d8623c9e-30c7-473a-83bc-d907df44a26e", * "webId": "074c0dc1-274c-4f92-8a6a-15a3b9088b9b" * }, * "siteCollection": { * "hostname": "bertonline.sharepoint.com" * }, * "root": {} * }, */ #endregion var json = JsonSerializer.Deserialize <JsonElement>(result.Json); if (json.TryGetProperty("@odata.nextLink", out JsonElement nextLink)) { sitesEnumerationApiCall = new ApiCall(nextLink.GetString().Replace($"{PnPConstants.MicrosoftGraphBaseUrl}{PnPConstants.GraphV1Endpoint}/", ""), ApiType.Graph); } else { paging = false; } if (json.GetProperty("value").ValueKind == JsonValueKind.Array) { foreach (var siteInformation in json.GetProperty("value").EnumerateArray()) { // Root sites have the root property set, ensuring we're not loading up sub sites as site collections if (siteInformation.TryGetProperty("root", out JsonElement _)) { var sharePointIds = siteInformation.GetProperty("sharepointIds"); AddLoadedSite(loadedSites, siteInformation.GetProperty("id").GetString(), siteInformation.GetProperty("webUrl").GetString(), sharePointIds.GetProperty("siteId").GetGuid(), sharePointIds.GetProperty("webId").GetGuid(), siteInformation.TryGetProperty("displayName", out JsonElement rootWebDescription) ? rootWebDescription.GetString() : null); } } } } return(loadedSites); }
private void AddModifyingCall(ApiCall apiCall, MethodCall methodCall) { if (RemoveRedundantModifyingCalls) { var before = Evaluate(apiCall, UseDefaultFormatting); apiCall.Add(methodCall); var after = Evaluate(apiCall, UseDefaultFormatting); if (before == after) { apiCall.Remove(methodCall); } return; } apiCall.Add(methodCall); }
public Guid LangUpdate(ApiCall call) { var sitedb = call.WebSite.SiteDb(); LangTextContentViewModel updatemodel = call.Context.Request.Model as LangTextContentViewModel; Guid folderId = GetFolderId(call); var contenttype = sitedb.ContentTypes.GetByFolder(folderId); if (contenttype == null || folderId == default(Guid)) { return(default(Guid)); } Guid parentId = call.GetValue <Guid>("ParentId"); string userkey = ExtraValue(updatemodel, "userkey"); if (!string.IsNullOrEmpty(userkey)) { userkey = Kooboo.Sites.Contents.UserKeyHelper.ToSafeUserKey(userkey); } string stronline = ExtraValue(updatemodel, "online"); bool online = true; if (!string.IsNullOrEmpty(stronline) && stronline.ToLower() == "false") { online = false; } int sequence = 0; var strsequence = ExtraValue(updatemodel, "sequence"); if (!string.IsNullOrEmpty(strsequence)) { int.TryParse(strsequence, out sequence); } TextContent newcontent = sitedb.TextContent.Get(call.ObjectId); if (newcontent == null) { newcontent = new TextContent() { FolderId = folderId, ContentTypeId = contenttype.Id, UserKey = userkey, ParentId = parentId, Order = sequence }; if (!string.IsNullOrEmpty(userkey) && sitedb.TextContent.IsUserKeyExists(userkey)) { throw new Exception(Data.Language.Hardcoded.GetValue("UserKey has been taken", call.Context)); } } if (!string.IsNullOrEmpty(userkey) && newcontent.UserKey != userkey) { var existings = sitedb.TextContent.Get(userkey); if (existings != null && existings.Id != newcontent.Id) { throw new Exception(Data.Language.Hardcoded.GetValue("UserKey has been taken", call.Context)); } sitedb.TextContent.Delete(newcontent.Id); newcontent.UserKey = userkey; } newcontent.Online = online; newcontent.Order = sequence; newcontent.Embedded = updatemodel.Embedded; foreach (var item in contenttype.Properties.Where(o => !o.IsSystemField && !o.MultipleLanguage)) { var value = ExtraValue(updatemodel, item.Name); if (!string.IsNullOrWhiteSpace(value)) { newcontent.SetValue(item.Name, value, call.WebSite.DefaultCulture); } } foreach (var langDict in updatemodel.Values) { string lang = langDict.Key; foreach (var item in langDict.Value) { string value = item.Value == null ? string.Empty : item.Value.ToString(); newcontent.SetValue(item.Key, value, lang); } } // sitedb.TextContent.EusureNonLangContent(newcontent, contenttype); sitedb.TextContent.AddOrUpdate(newcontent, call.Context.User.Id); if (updatemodel.Categories.Count > 0) { foreach (var item in updatemodel.Categories) { sitedb.ContentCategories.UpdateCategory(newcontent.Id, item.Key, item.Value.ToList(), call.Context.User.Id); } } return(newcontent.Id); }
private static void Print( ApiCall codeBlock, StringBuilder sb, int depth = 0, bool openParenthesisOnNewLine = false, bool closingParenthesisOnNewLine = false) { Print( codeBlock.FactoryMethodCall, sb, depth, useCurliesInsteadOfParentheses: codeBlock.UseCurliesInsteadOfParentheses, openParenthesisOnNewLine: openParenthesisOnNewLine, closingParenthesisOnNewLine: closingParenthesisOnNewLine); if (codeBlock.InstanceMethodCalls != null) { foreach (var call in codeBlock.InstanceMethodCalls) { PrintNewLine(sb); Print( call, sb, depth, useCurliesInsteadOfParentheses: codeBlock.UseCurliesInsteadOfParentheses, openParenthesisOnNewLine: openParenthesisOnNewLine, closingParenthesisOnNewLine: closingParenthesisOnNewLine); } } }
/// <summary> /// Flattens a tree of ApiCalls into a single string. /// </summary> private string Print(ApiCall root) { var sb = new StringBuilder(); Print(root, sb, 0, OpenParenthesisOnNewLine, ClosingParenthesisOnNewLine); var generatedCode = sb.ToString(); return generatedCode; }
public List <Domain> Domains(ApiCall apiCall) { return(Data.GlobalDb.Domains.ListForEmail(apiCall.Context.User)); }
public storeSize GetSize(string storename, ApiCall call) { storeSize storesize = new storeSize() { Name = storename }; var sitedb = call.WebSite.SiteDb(); var repo = sitedb.GetRepository(storename); storesize.ItemCount = repo.Store.Count(); storesize.Disk = Lib.Helper.IOHelper.GetDirectorySize(repo.Store.ObjectFolder); var logs = sitedb.Log.GetByStoreName(storename); storesize.LogCount = logs.Count; Dictionary <Guid, long> keyblockPosition = new Dictionary <Guid, long>(); HashSet <long> DeletedBlock = new HashSet <long>(); foreach (var item in logs) { long blockposition = 0; if (item.EditType == IndexedDB.EditType.Delete) { blockposition = item.OldBlockPosition; DeletedBlock.Add(blockposition); storesize.CanClean = true; } else { blockposition = item.NewBlockPosition; if (item.EditType == IndexedDB.EditType.Update && item.OldBlockPosition > 0) { storesize.CanClean = true; } } if (keyblockPosition.ContainsKey(item.KeyHash)) { var currentposition = keyblockPosition[item.KeyHash]; if (blockposition > currentposition) { keyblockPosition[item.KeyHash] = blockposition; } } else { keyblockPosition[item.KeyHash] = blockposition; } } foreach (var item in keyblockPosition) { if (item.Value > 0) { if (!DeletedBlock.Contains(item.Value)) { var itemsize = repo.Store.getLength(item.Value); storesize.ItemLength += itemsize; } } } return(storesize); }
private void AddFactoryMethodArguments( MethodInfo factory, MethodCall factoryMethodCall, List <ApiCall> quotedValues) { foreach (var factoryMethodParameter in factory.GetParameters()) { var parameterName = factoryMethodParameter.Name; var parameterType = factoryMethodParameter.ParameterType; ApiCall quotedCodeBlock = FindValue(parameterName, quotedValues); // if we have Block(List<StatementSyntax>(new StatementSyntax[] { A, B })), just simplify it to // Block(A, B) if (quotedCodeBlock != null && factory.GetParameters().Length == 1 && factoryMethodParameter.GetCustomAttribute <ParamArrayAttribute>() != null) { var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall; if (methodCall != null && methodCall.Name.Contains("List") && methodCall.Arguments.Count == 1) { var argument = methodCall.Arguments[0] as ApiCall; var arrayCreation = argument.FactoryMethodCall as MethodCall; if (argument != null && arrayCreation != null && arrayCreation.Name.StartsWith("new ") && arrayCreation.Name.EndsWith("[]")) { foreach (var arrayElement in arrayCreation.Arguments) { factoryMethodCall.AddArgument(arrayElement); } quotedValues.Remove(quotedCodeBlock); return; } } } // special case to prefer SyntaxFactory.IdentifierName("C") to // SyntaxFactory.IdentifierName(Syntax.Identifier("C")) if (parameterName == "name" && parameterType == typeof(string)) { quotedCodeBlock = quotedValues.FirstOrDefault(a => a.Name == "Identifier"); if (quotedCodeBlock == null) { throw new NotImplementedException($"An unsupported factory method was chosen: {factory.ToString()}\r\nPlease add this method to the list of factoryMethodsToExclude."); } var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall; if (methodCall != null && methodCall.Name == SyntaxFactoryMethod("Identifier")) { if (methodCall.Arguments.Count == 1) { factoryMethodCall.AddArgument(methodCall.Arguments[0]); } else { factoryMethodCall.AddArgument(quotedCodeBlock); } quotedValues.Remove(quotedCodeBlock); continue; } } // special case to prefer SyntaxFactory.ClassDeclarationSyntax(string) instead of // SyntaxFactory.ClassDeclarationSyntax(SyntaxToken) if (parameterName == "identifier" && parameterType == typeof(string)) { var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall; if (methodCall != null && methodCall.Name == SyntaxFactoryMethod("Identifier") && methodCall.Arguments.Count == 1) { factoryMethodCall.AddArgument(methodCall.Arguments[0]); quotedValues.Remove(quotedCodeBlock); continue; } } if (quotedCodeBlock != null) { factoryMethodCall.AddArgument(quotedCodeBlock); quotedValues.Remove(quotedCodeBlock); } else if (!factoryMethodParameter.IsOptional) { if (parameterType.IsArray) { // assuming this is a params parameter that accepts an array, so if we have nothing we don't need to pass anything continue; } // if we don't have a value just try passing null and see if it will work later if (!parameterType.IsValueType) { factoryMethodCall.AddArgument("null"); } else { factoryMethodCall.AddArgument( new MethodCall() { Name = "default", Arguments = new List <object> { GetPrintableTypeName(parameterType) } }); } } } }
public void Deletes(ApiCall call) { string strids = call.GetValue("ids"); var sitedb = call.WebSite.SiteDb(); List <Guid> objectids = null; if (!string.IsNullOrEmpty(strids)) { objectids = Lib.Helper.JsonHelper.Deserialize <List <Guid> >(strids); } var type = call.GetValue("type"); IRepository repo = null; if (type.ToLower() == "route" || type.ToLower() == "internal") { repo = sitedb.Routes; } else if (type.ToLower() == "external") { repo = sitedb.ExternalResource; } foreach (var id in objectids) { var siteobject = repo.Get(id); if (siteobject != null) { string oldurl = null; if (siteobject is Route) { var routeobject = siteobject as Route; oldurl = routeobject.Name; } else { var external = siteobject as ExternalResource; oldurl = external.FullUrl; } var referredby = sitedb.Relations.GetReferredByRelations(id); foreach (var by in referredby) { var repofrom = sitedb.GetRepository(by.ConstTypeX); if (repofrom != null) { Sites.Helper.ChangeHelper.DeleteUrl(sitedb, repofrom, by.objectXId, oldurl); } } if (siteobject is Route) { var route = siteobject as Route; if (route.objectId == default(Guid)) { repo.Delete(siteobject.Id); } } else { repo.Delete(siteobject.Id); } } } }
private CmsMenuViewModel SiteBarAdvancedMenu(ApiCall call) { var context = call.Context; var advanceheadline = Hardcoded.GetValue("Advance", context); var advance = new CmsMenuViewModel(advanceheadline, advanceheadline); var system = new CmsMenuViewModel(SideBarSection.System.ToString(), Hardcoded.GetValue("System", context)) { Icon = "icon icon-settings" }; var development = new CmsMenuViewModel(SideBarSection.Development.ToString(), Hardcoded.GetValue("Development", context)) { Icon = "icon fa fa-code" }; var content = new CmsMenuViewModel(SideBarSection.Contents.ToString(), Hardcoded.GetValue("Contents", context)) { Icon = "icon fa fa-files-o" }; var database = new CmsMenuViewModel(SideBarSection.Database.ToString(), Hardcoded.GetValue("Database", context)) { Icon = "icon fa fa-database" }; var commerce = new CmsMenuViewModel(SideBarSection.Commerce.ToString(), Hardcoded.GetValue("Commerce", context)) { Icon = "icon fa fa-database" }; advance.Items.Add(system); advance.Items.Add(development); advance.Items.Add(content); advance.Items.Add(database); // advance.Items.Add(commerce); var sitebarmenus = MenuContainer.SideBarMenus; foreach (var item in sitebarmenus) { if (item.Parent == SideBarSection.Root) { advance.Items.Add(new CmsMenuViewModel(item, context)); } else if (item.Parent == SideBarSection.System) { system.Items.Add(new CmsMenuViewModel(item, context)); } else if (item.Parent == SideBarSection.Development) { development.Items.Add(new CmsMenuViewModel(item, context)); } else if (item.Parent == SideBarSection.Contents) { content.Items.Add(new CmsMenuViewModel(item, context)); } else if (item.Parent == SideBarSection.Database) { database.Items.Add(new CmsMenuViewModel(item, context)); } else if (item.Parent == SideBarSection.Commerce) { // commerce.Items.Add(new CmsMenuViewModel(item, context)); } } MenuManager.VerifySortSideBar(advance.Items, call.Context); return(advance); }
private string Evaluate(ApiCall apiCall, bool normalizeWhitespace = false) { return Evaluate(Print(apiCall), normalizeWhitespace); }
/// <summary> /// Adds information about subsequent modifying fluent interface style calls on an object (like /// foo.With(...).With(...)) /// </summary> private void AddModifyingCalls(object treeElement, ApiCall apiCall, List<ApiCall> values) { var methods = treeElement.GetType() .GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.GetCustomAttribute<ObsoleteAttribute>() == null); foreach (var value in values) { var properCase = ProperCase(value.Name); var methodName = "With" + properCase; if (methods.Any(m => m.Name == methodName)) { methodName = "." + methodName; } else { throw new NotSupportedException("Sorry, this is a bug in Quoter. Please file a bug at https://github.com/KirillOsenkov/RoslynQuoter/issues/new."); } var methodCall = new MethodCall { Name = methodName, Arguments = CreateArgumentList(value) }; AddModifyingCall(apiCall, methodCall); } }
private string Evaluate(ApiCall apiCall, bool normalizeWhitespace = false) { return(Evaluate(Print(apiCall), normalizeWhitespace)); }
public AmigoModel () { WS = new ApiCall (); }
// Modify every API call on construction to use GoogleAdsException partial void Modify_ApiCall <TRequest, TResponse>(ref ApiCall <TRequest, TResponse> call) where TRequest : class, IMessage <TRequest> where TResponse : class, IMessage <TResponse> => call = call.WithExceptionCustomizer(GoogleAdsException.Create);
public override bool IsUniqueName(ApiCall call) { return(base.IsUniqueName(call)); }
private void AddModifyingCall(ApiCall apiCall, MethodCall methodCall) { // TODO: this needs scripting ////if (RemoveRedundantModifyingCalls) ////{ //// var before = Evaluate(apiCall, UseDefaultFormatting); //// apiCall.Add(methodCall); //// var after = Evaluate(apiCall, UseDefaultFormatting); //// if (before == after) //// { //// apiCall.Remove(methodCall); //// } ////} apiCall.Add(methodCall); return; }
public DiskSize Size(ApiCall call) { return(call.WebSite.SiteDb().GetSize()); }
/// <summary> /// The main recursive method that given a SyntaxNode recursively quotes the entire subtree. /// </summary> private ApiCall QuoteNode(SyntaxNode node, string name) { List<ApiCall> quotedPropertyValues = QuotePropertyValues(node); MethodInfo factoryMethod = PickFactoryMethodToCreateNode(node); var factoryMethodCall = new MethodCall() { Name = factoryMethod.DeclaringType.Name + "." + factoryMethod.Name }; var codeBlock = new ApiCall(name, factoryMethodCall); AddFactoryMethodArguments(factoryMethod, factoryMethodCall, quotedPropertyValues); AddModifyingCalls(node, codeBlock, quotedPropertyValues); return codeBlock; }
public void CleanRepository(ApiCall call) { // }
public List <DataSourceViewModel> CenterList(ApiCall call) { return(FilterOut(allmethods(call), call.WebSite)); }
public void CleanLog(ApiCall call) { }
private List <ContentFieldViewModel> GetProperties(ApiCall call, Guid FolderId) { var culture = call.WebSite.DefaultCulture; List <ContentFieldViewModel> result = new List <ContentFieldViewModel>(); var contenttype = call.WebSite.SiteDb().ContentTypes.GetByFolder(FolderId); bool online = true; TextContent textcontentnew = null; if (call.ObjectId != default(Guid)) { textcontentnew = call.WebSite.SiteDb().TextContent.Get(call.ObjectId); online = textcontentnew.Online; } if (textcontentnew == null) { foreach (var item in contenttype.Properties) { if (item.Editable) { ContentFieldViewModel model = new ContentFieldViewModel(); model.Name = item.Name; model.DisplayName = item.DisplayName; model.Validations = item.Validations; model.ControlType = item.ControlType; model.ToolTip = item.Tooltip; model.Order = item.Order; if (item.MultipleLanguage) { foreach (var cultureitem in call.WebSite.Culture.Keys.ToList()) { model.Values.Add(cultureitem, ""); } } else { if (item.DataType == Data.Definition.DataTypes.Bool) { model.Values.Add(call.WebSite.DefaultCulture, "true"); } else { model.Values.Add(call.WebSite.DefaultCulture, ""); } } model.IsMultilingual = item.MultipleLanguage; model.selectionOptions = item.selectionOptions; model.MultipleValue = item.MultipleValue; result.Add(model); } } } else { foreach (var item in contenttype.Properties) { if (item.Editable) { ContentFieldViewModel model = new ContentFieldViewModel(); model.Name = item.Name; model.Validations = item.Validations; model.ControlType = item.ControlType; model.DisplayName = item.DisplayName; model.IsMultilingual = item.MultipleLanguage; model.ToolTip = item.Tooltip; model.Order = item.Order; model.selectionOptions = item.selectionOptions; model.MultipleValue = item.MultipleValue; if (item.MultipleLanguage) { foreach (var lang in textcontentnew.Contents) { var itemvalue = textcontentnew.GetValue(model.Name, lang.Lang); model.Values[lang.Lang] = itemvalue != null?itemvalue.ToString() : string.Empty; } foreach (var sitelang in call.WebSite.Culture.Keys.ToList()) { if (!model.Values.ContainsKey(sitelang)) { model.Values.Add(sitelang, ""); } } } else { var itemvalue = textcontentnew.GetValue(model.Name, culture); model.Values[culture] = itemvalue != null?itemvalue.ToString() : null; } result.Add(model); } } } var onlineitem = result.Find(o => o.Name.ToLower() == "online"); if (onlineitem != null) { result.Remove(onlineitem); onlineitem.ControlType = "boolean"; result.Add(onlineitem); } return(result); }
public virtual TransferResponse ByLevel(ApiCall call) { string RootDomain = call.GetValue("RootDomain"); string SubDomain = call.GetValue("SubDomain"); string fulldomain = SubDomain + "." + RootDomain; string sitename = call.GetValue("SiteName"); if (string.IsNullOrEmpty(sitename) || string.IsNullOrEmpty(fulldomain)) { return(null); } // model.Url, model.TotalPages, model.Depth string url = call.GetValue("url"); if (string.IsNullOrEmpty(url)) { return(null); } if (Kooboo.Sites.SiteTransfer.TransferManager.IsUrlBanned(url)) { string error = Data.Language.Hardcoded.GetValue("Target Url is Protected", call.Context); throw new Exception(error); } url = url.Trim(); if (!url.ToLower().StartsWith("http")) { url = "http://" + url; } if (!Lib.Helper.UrlHelper.IsValidUrl(url, true)) { throw new Exception(Data.Language.Hardcoded.GetValue("Invalid Url", call.Context)); } string strTotalPages = call.GetValue("TotalPages"); string strDepth = call.GetValue("Depth"); int totalpages = 0; int depth = 0; if (string.IsNullOrEmpty(strTotalPages) || !int.TryParse(strTotalPages, out totalpages)) { totalpages = 10; } if (string.IsNullOrEmpty(strDepth) || !int.TryParse(strDepth, out depth)) { depth = 2; } //if (Data.AppSettings.IsOnlineServer) //{ // if (totalpages > 3) // { // totalpages = 3; // } //} WebSite newsite = Kooboo.Sites.Service.WebSiteService.AddNewSite(call.Context.User.CurrentOrgId, sitename, fulldomain, call.Context.User.Id); var transferTask = TransferManager.AddTask(newsite.SiteDb(), url, totalpages, depth, call.Context.User.Id); TransferManager.ExecuteTask(newsite.SiteDb(), transferTask); return(new TransferResponse { SiteId = newsite.Id, TaskId = transferTask.Id, Success = true }); }
public async Task <ActionResult> Index(AddCategoryViewModel model) { try { model.Category.Description = model.Category.Description ?? ""; if (!ModelState.IsValid) { return(View(model)); } MultipartFormDataContent content; bool FileAttached = (Request.RequestContext.HttpContext.Session["AddCategoryImage"] != null); bool ImageDeletedOnEdit = false; var imgDeleteSessionValue = Request.RequestContext.HttpContext.Session["ImageDeletedOnEdit"]; if (imgDeleteSessionValue != null) { ImageDeletedOnEdit = Convert.ToBoolean(imgDeleteSessionValue); } byte[] fileData = null; var ImageFile = (HttpPostedFileWrapper)Request.RequestContext.HttpContext.Session["AddCategoryImage"]; if (FileAttached) { using (var binaryReader = new BinaryReader(ImageFile.InputStream)) { fileData = binaryReader.ReadBytes(ImageFile.ContentLength); } } ByteArrayContent fileContent; JObject response; bool firstCall = true; callAgain : content = new MultipartFormDataContent(); if (FileAttached) { fileContent = new ByteArrayContent(fileData); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = ImageFile.FileName }; content.Add(fileContent); } if (model.Category.Id > 0) { content.Add(new StringContent(model.Category.Id.ToString()), "Id"); } content.Add(new StringContent(model.Category.Name), "Name"); content.Add(new StringContent(model.Category.Store_Id.ToString()), "Store_Id"); content.Add(new StringContent(model.Category.Description), "Description"); content.Add(new StringContent(Convert.ToString(model.Category.ParentCategoryId)), "ParentCategoryId"); content.Add(new StringContent(Convert.ToString(ImageDeletedOnEdit)), "ImageDeletedOnEdit"); response = await ApiCall.CallApi("api/Admin/AddCategory", User, isMultipart : true, multipartContent : content); if (firstCall && response.ToString().Contains("UnAuthorized")) { firstCall = false; goto callAgain; } else if (response.ToString().Contains("UnAuthorized")) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "UnAuthorized Error")); } if (response is Error) { return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, (response as Error).ErrorMessage)); } else { if (model.Category.Id > 0) { TempData["SuccessMessage"] = "The category has been updated successfully."; } else { TempData["SuccessMessage"] = "The category has been added successfully."; } return(Json(new { success = true, responseText = "Success" }, JsonRequestBehavior.AllowGet)); } } catch (Exception ex) { throw; } }
public HashSet <string> GetSubUrl(ApiCall call) { HashSet <string> result = new HashSet <string>(StringComparer.OrdinalIgnoreCase); string url = call.GetValue("url"); string strpage = call.GetValue("pages"); if (string.IsNullOrEmpty(url) && string.IsNullOrEmpty(strpage)) { return(null); } int pagenumber = 10; int setpage = 0; if (int.TryParse(strpage, out setpage)) { pagenumber = setpage; } url = System.Net.WebUtility.UrlDecode(url); result.Add(url); if (result.Count >= pagenumber) { return(result); } var download = Lib.Helper.DownloadHelper.DownloadUrl(url); if (download != null && download.StatusCode == 200 && download.isString) { string content = download.GetString(); var dom = Kooboo.Dom.DomParser.CreateDom(content); foreach (var item in dom.Links.item) { string itemsrc = Sites.Service.DomUrlService.GetLinkOrSrc(item); if (string.IsNullOrEmpty(itemsrc)) { continue; } string absoluteurl = UrlHelper.Combine(url, itemsrc); bool issamehost = Kooboo.Lib.Helper.UrlHelper.isSameHost(url, absoluteurl); if (issamehost) { result.Add(absoluteurl); if (result.Count >= pagenumber) { return(result); } } } } if (result.Count >= pagenumber) { return(result); } return(result); }
/// <summary> /// Enumerating site collections using Graph Search endpoint. Only works when using delegated permissions! /// </summary> internal async static Task <List <ISiteCollection> > GetViaGraphSearchApiAsync(PnPContext context, int pageSize = 500) { string requestBody = "{\"requests\": [{ \"entityTypes\": [\"site\"], \"query\": { \"queryString\": \"contentclass:STS_Site\" }, \"from\": %from%, \"size\": %to%, \"fields\": [ \"webUrl\", \"id\", \"name\" ] }]}"; List <ISiteCollection> loadedSites = new List <ISiteCollection>(); bool paging = true; int from = 0; int to = pageSize; while (paging) { ApiCall sitesEnumerationApiCall = new ApiCall("search/query", ApiType.Graph, requestBody.Replace("%from%", from.ToString()).Replace("%to%", to.ToString())); var result = await(context.Web as Web).RawRequestAsync(sitesEnumerationApiCall, HttpMethod.Post).ConfigureAwait(false); #region Json response /* * { * "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.searchResponse", * "value": [ * { * "searchTerms": [], * "hitsContainers": [ * { * "total": 1313, * "moreResultsAvailable": true, * "hits": [ * { * "hitId": "bertonline.sharepoint.com,b56adf79-ff6a-4964-a63a-ff1fa23be9f8,8c8e101c-1b0d-4253-85e7-c30039bf46e2", * "rank": 1, * "summary": "STS_Site Home {19065987-C276<ddd/>", * "resource": { * "@odata.type": "#microsoft.graph.site", * "id": "bertonline.sharepoint.com,b56adf79-ff6a-4964-a63a-ff1fa23be9f8,8c8e101c-1b0d-4253-85e7-c30039bf46e2", * "createdDateTime": "2018-10-05T19:16:44Z", * "lastModifiedDateTime": "2018-09-29T09:18:41Z", * "name": "prov-1", * "webUrl": "https://bertonline.sharepoint.com/sites/prov-1" * } * }, * */ #endregion var json = JsonSerializer.Deserialize <JsonElement>(result.Json); foreach (var queryResult in json.GetProperty("value").EnumerateArray()) { foreach (var hitsContainer in queryResult.GetProperty("hitsContainers").EnumerateArray()) { paging = hitsContainer.GetProperty("moreResultsAvailable").GetBoolean(); from += pageSize; to += pageSize; if (hitsContainer.TryGetProperty("hits", out JsonElement hits) && hits.ValueKind == JsonValueKind.Array) { foreach (var hit in hits.EnumerateArray()) { GetSiteAndWebId(hit.GetProperty("hitId").GetString(), out Guid siteId, out Guid webId); AddLoadedSite(loadedSites, hit.GetProperty("hitId").GetString(), hit.GetProperty("resource").GetProperty("webUrl").GetString(), siteId, webId, hit.GetProperty("resource").TryGetProperty("name", out JsonElement rootWebDescription) ? rootWebDescription.GetString() : null); } } } } } return(loadedSites); }
public SingleResponse Single(string pageUrl, string name, ApiCall call) { SingleResponse response = new SingleResponse(); var sitedb = call.WebSite.SiteDb(); if (Kooboo.Sites.SiteTransfer.TransferManager.IsUrlBanned(pageUrl)) { string error = Data.Language.Hardcoded.GetValue("Target Url is Protected", call.Context); throw new Exception(error); } if (!pageUrl.ToLower().StartsWith("http")) { pageUrl = "http://" + pageUrl; } if (!Lib.Helper.UrlHelper.IsValidUrl(pageUrl, true)) { throw new Exception(Data.Language.Hardcoded.GetValue("Invalid Url", call.Context)); } if (string.IsNullOrEmpty(name)) { name = UrlHelper.GetPageName(pageUrl); } if (!sitedb.Routes.Validate(name, default(Guid))) { throw new Exception(Data.Language.Hardcoded.GetValue("Url occupied", call.Context)); } if (!string.IsNullOrEmpty(pageUrl)) { var task = TransferManager.AddTask(sitedb, pageUrl, name, call.Context.User.Id); TransferManager.ExecuteTask(sitedb, task).Wait(); response.TaskId = task.Id; response.Finish = true; var transferpages = sitedb.TransferPages.Query.Where(o => o.taskid == task.Id).SelectAll(); if (transferpages == null || transferpages.Count() == 0) { response.Success = false; response.Messages.Add("no page downloaded"); } else { var transferpage = transferpages.Find(o => o.done == true); if (transferpage != null && transferpage.PageId != default(Guid)) { response.Success = true; var sitepage = sitedb.Pages.Get(transferpage.PageId); if (sitepage != null) { response.Model = PageApi.ToPageViewModel(sitedb, sitepage); } } } } else { response.Finish = true; response.Success = false; response.Messages.Add("page url not found"); } return(response); }
private void AddFactoryMethodArguments( MethodInfo factory, MethodCall factoryMethodCall, List <ApiCall> quotedValues) { foreach (var factoryMethodParameter in factory.GetParameters()) { var parameterName = factoryMethodParameter.Name; var parameterType = factoryMethodParameter.ParameterType; ApiCall quotedCodeBlock = FindValue(parameterName, quotedValues); // if we have Block(List<StatementSyntax>(new StatementSyntax[] { A, B })), just simplify it to // Block(A, B) if (quotedCodeBlock != null && factory.GetParameters().Length == 1 && factoryMethodParameter.GetCustomAttribute <ParamArrayAttribute>() != null) { var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall; if (methodCall != null && methodCall.Name.Contains("List") && methodCall.Arguments.Count == 1) { var argument = methodCall.Arguments[0] as ApiCall; var arrayCreation = argument.FactoryMethodCall as MethodCall; if (argument != null && arrayCreation != null && arrayCreation.Name.StartsWith("new ") && arrayCreation.Name.EndsWith("[]")) { foreach (var arrayElement in arrayCreation.Arguments) { factoryMethodCall.AddArgument(arrayElement); } quotedValues.Remove(quotedCodeBlock); return; } } } // special case to prefer SyntaxFactory.IdentifierName("C") to // SyntaxFactory.IdentifierName(Syntax.Identifier("C")) if (parameterName == "name" && parameterType == typeof(string)) { quotedCodeBlock = quotedValues.First(a => a.Name == "Identifier"); var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall; if (methodCall != null && methodCall.Name == SyntaxFactory("Identifier")) { if (methodCall.Arguments.Count == 1) { factoryMethodCall.AddArgument(methodCall.Arguments[0]); } else { factoryMethodCall.AddArgument(quotedCodeBlock); } quotedValues.Remove(quotedCodeBlock); continue; } } // special case to prefer SyntaxFactory.ClassDeclarationSyntax(string) instead of // SyntaxFactory.ClassDeclarationSyntax(SyntaxToken) if (parameterName == "identifier" && parameterType == typeof(string)) { var methodCall = quotedCodeBlock.FactoryMethodCall as MethodCall; if (methodCall != null && methodCall.Name == SyntaxFactory("Identifier") && methodCall.Arguments.Count == 1) { factoryMethodCall.AddArgument(methodCall.Arguments[0]); quotedValues.Remove(quotedCodeBlock); continue; } } if (quotedCodeBlock != null) { factoryMethodCall.AddArgument(quotedCodeBlock); quotedValues.Remove(quotedCodeBlock); } else if (!factoryMethodParameter.IsOptional) { if (parameterType.IsArray) { // assuming this is a params parameter that accepts an array, so if we have nothing we don't need to pass anything continue; } throw new InvalidOperationException( string.Format( "Couldn't find value for parameter '{0}' of method '{1}'. Go to QuotePropertyValues() and add your node type to the exception list.", parameterName, factory)); } } }
public void DeleteUsers(Guid UserId, ApiCall call) { var sitedb = call.Context.WebSite.SiteDb(); sitedb.SiteUser.Delete(UserId); }
private object[] MapParameters(MethodInfo info, ApiCall call) { if (info.Name == "getTopicPage") { int i = 10; int j = i; } var p = new List <object>(); var parameterInfo = info.GetParameters(); if (parameterInfo != null) { foreach (var parameter in parameterInfo) { string strVal; if (!call.Parameters.TryGetValue(parameter.Name, out strVal)) { // Parameter not found! bool isNullable = Nullable.GetUnderlyingType(parameter.ParameterType) != null; if (isNullable) { p.Add(null); } else if (parameter.ParameterType.IsValueType) { throw AutoApiException.ValueTypeParamNull(parameter.Name); } else { p.Add(null); } } else { if (parameter.ParameterType.IsClass) { if (parameter.ParameterType == typeof(string)) { p.Add(strVal); } else { string json = strVal; var genericDeserialse = _deserialiseMethod.MakeGenericMethod(parameter.ParameterType); var obj = genericDeserialse.Invoke(null, new object[] { json }); p.Add(obj); } } else { if (parameter.ParameterType == typeof(int)) { int iVal; if (!int.TryParse(strVal, out iVal)) { throw AutoApiException.ParameterConvertException <int>(parameter.Name); } else { p.Add(iVal); } } else if (parameter.ParameterType == typeof(Nullable <int>)) { int iVal; if (!int.TryParse(strVal, out iVal)) { throw AutoApiException.ParameterConvertException <int>(parameter.Name); } else { p.Add(iVal); } } else if (parameter.ParameterType == typeof(Int64)) { Int64 iVal; if (!Int64.TryParse(strVal, out iVal)) { throw AutoApiException.ParameterConvertException <Int64>(parameter.Name); } p.Add(iVal); } else if (parameter.ParameterType == typeof(float)) { float fVal; if (!float.TryParse(strVal, out fVal)) { throw AutoApiException.ParameterConvertException <float>(parameter.Name); } } else if (parameter.ParameterType == typeof(double)) { double fVal; if (!double.TryParse(strVal, out fVal)) { throw AutoApiException.ParameterConvertException <double>(parameter.Name); } } else { throw AutoApiException.UnsupportedParameterType(parameter.Name, parameter.ParameterType); } } } } } return(p.ToArray()); }
public List <string> Thirdparty(ApiCall call) { return(GlobalDb.DataMethodSettings.Query.Where(o => o.IsThirdPartyType).SelectAll().Select(o => o.MethodSignatureHash.ToString()).ToList()); }
public void registrarFuncionApi(string nombre, ApiCall ac) { registroApi.Add(nombre, ac); }
internal BasicAuthenticationMechanism(ApiCall apiCall, string username, string password) { _apiCall = apiCall; _username = username; _password = password; }
private static string PrintWithDefaultFormatting(ApiCall root) { var sb = new StringBuilder(); Print( root, sb, 0, openParenthesisOnNewLine: false, closingParenthesisOnNewLine: false); var generatedCode = sb.ToString(); return generatedCode; }
public List <Data.Models.Dll> List(ApiCall call) { return(Kooboo.Data.GlobalDb.Dlls.All().OrderBy(o => o.AssemblyName).ToList()); }
/// <summary> /// Adds information about subsequent modifying fluent interface style calls on an object (like /// foo.With(...).With(...)) /// </summary> private void AddModifyingCalls(object treeElement, ApiCall apiCall, List<ApiCall> values) { var methods = treeElement.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (var value in values) { var properCase = ProperCase(value.Name); var methodName = "With" + properCase; if (methods.Any(m => m.Name == methodName)) { methodName = "." + methodName; } else { throw new NotSupportedException(); } var methodCall = new MethodCall { Name = methodName, Arguments = CreateArgumentList(value) }; AddModifyingCall(apiCall, methodCall); } }
public object CheckProuctCount(Guid Id, ApiCall call) { return(call.Context.WebSite.SiteDb().Product.GetByCategory(Id).Count()); }
private ApiCall QuoteList(IEnumerable syntaxList, string name) { IEnumerable<object> sourceList = syntaxList.Cast<object>(); string methodName = "SyntaxFactory.List"; string listType = null; var propertyType = syntaxList.GetType(); if (propertyType.IsGenericType) { var methodType = propertyType.GetGenericArguments()[0].Name; listType = methodType; if (propertyType.GetGenericTypeDefinition() == typeof(SeparatedSyntaxList<>)) { listType = "SyntaxNodeOrToken"; methodName = "SyntaxFactory.SeparatedList"; sourceList = ((SyntaxNodeOrTokenList) syntaxList.GetType().GetMethod("GetWithSeparators").Invoke(syntaxList, null)) .Cast<object>() .ToArray(); } methodName += "<" + methodType + ">"; } if (propertyType.Name == "SyntaxTokenList") { methodName = "SyntaxFactory.TokenList"; } if (propertyType.Name == "SyntaxTriviaList") { methodName = "SyntaxFactory.TriviaList"; } var elements = new List<object>(sourceList .Select(o => Quote(o)) .Where(cb => cb != null)); if (elements.Count == 0) { return null; } else if (elements.Count == 1) { methodName = methodName.Replace(".List", ".SingletonList"); methodName = methodName.Replace(".SeparatedList", ".SingletonSeparatedList"); } else { elements = new List<object> { new ApiCall( "methodName", "new " + listType + "[]", elements, useCurliesInsteadOfParentheses: true) }; } var codeBlock = new ApiCall(name, methodName, elements); return codeBlock; }
public TypeInfoModel Update(ApiCall call) { string json = call.Context.Request.Body; var sitedb = call.Context.WebSite.SiteDb(); DataMethodViewModel viewmodel = Lib.Helper.JsonHelper.Deserialize <DataMethodViewModel>(json); CheckCorrectSampleJson(viewmodel, call); if (viewmodel.Id == default(Guid)) { // TODO: check if it is from the kscript source as well.. var methodhash = viewmodel.MethodSignatureHash; IDataMethodSetting originalSetting; originalSetting = GlobalDb.DataMethodSettings.Query.Where(o => o.MethodSignatureHash == methodhash).FirstOrDefault(); if (originalSetting == null) { originalSetting = Kooboo.Sites.DataSources.ScriptSourceManager.GetByMethodHash(sitedb, methodhash); } if (originalSetting != null) { DataMethodSetting newMethodSetting = new DataMethodSetting { MethodName = viewmodel.MethodName, ParameterBinding = viewmodel.ParameterBinding, Parameters = viewmodel.Parameters, Description = viewmodel.Description, OriginalMethodName = originalSetting.OriginalMethodName, MethodSignatureHash = originalSetting.MethodSignatureHash, DeclareType = originalSetting.DeclareType, ReturnType = originalSetting.ReturnType, DeclareTypeHash = originalSetting.DeclareTypeHash, IsPagedResult = originalSetting.IsPagedResult }; if (!viewmodel.IsPublic) { newMethodSetting.MethodName = System.Guid.NewGuid().ToString(); } newMethodSetting.IsPublic = viewmodel.IsPublic; call.WebSite.SiteDb().DataMethodSettings.AddOrUpdate(newMethodSetting, call.Context.User.Id); var fields = DataSourceHelper.GetFields(call.WebSite.SiteDb(), newMethodSetting); fields.Paras = GetBindingPara(newMethodSetting); return(fields); } } else { var dataMethodSetting = call.WebSite.SiteDb().DataMethodSettings.Get(viewmodel.Id); if (dataMethodSetting == null) { dataMethodSetting = Kooboo.Sites.DataSources.ScriptSourceManager.Get(call.WebSite.SiteDb(), viewmodel.Id); dataMethodSetting.ParameterBinding = viewmodel.ParameterBinding; dataMethodSetting.Description = viewmodel.Description; dataMethodSetting.IsPublic = viewmodel.IsPublic; call.WebSite.SiteDb().DataMethodSettings.AddOrUpdate(dataMethodSetting, call.Context.User.Id); var fields = DataSourceHelper.GetFields(call.WebSite.SiteDb(), dataMethodSetting); fields.Paras = GetBindingPara(dataMethodSetting); return(fields); } else { dataMethodSetting.ParameterBinding = viewmodel.ParameterBinding; dataMethodSetting.Description = viewmodel.Description; dataMethodSetting.IsPublic = viewmodel.IsPublic; call.WebSite.SiteDb().DataMethodSettings.AddOrUpdate(dataMethodSetting, call.Context.User.Id); var fields = DataSourceHelper.GetFields(call.WebSite.SiteDb(), dataMethodSetting); fields.Paras = GetBindingPara(dataMethodSetting); return(fields); } } return(null); }
public DataMethodSetting GetSetting(ApiCall call) { DataMethodSetting settings = GlobalDb.DataMethodSettings.Get(call.ObjectId); return(settings); }
public void btnCallRestAPI_Click(object sender, EventArgs e) { string Day = dayText.Text.ToString(); string Month = monthText.Text.ToString(); string Year = yearText.Text.ToString(); string Hour = hourText.Text.ToString(); string Min = minuteText.Text.ToString(); string Lat = latText.Text.ToString(); string lon = lonText.Text.ToString(); string Tzone = tzoneText.Text.ToString(); Dictionary<string, string> reqObject = new Dictionary<string, string>(); //For other astro api //---------------------------------------------------------------------- reqObject.Add("day", Day); reqObject.Add("month", Month); reqObject.Add("year", Year); reqObject.Add("hour", Hour); reqObject.Add("min", Min); reqObject.Add("lat", Lat); reqObject.Add("lon", lon); reqObject.Add("tzone", Tzone); //For Matching Api //---------------------------------------------------------------------- //reqObject.Add("m_day", "5"); //reqObject.Add("m_month", "2"); //reqObject.Add("m_year", "1986"); //reqObject.Add("m_hour", "3"); //reqObject.Add("m_min", "2"); //reqObject.Add("m_lat", "18.975"); //reqObject.Add("m_lon", "72.8258"); //reqObject.Add("m_tzone", "5.5"); //reqObject.Add("f_day", "3"); //reqObject.Add("f_month", "2"); //reqObject.Add("f_year", "1986"); //reqObject.Add("f_hour", "3"); //reqObject.Add("f_min", "2"); //reqObject.Add("f_lat", "18.975"); //reqObject.Add("f_lon", "72.8258"); //reqObject.Add("f_tzone", "5.5"); //Request Birth Detail. string requestJson = JsonConvert.SerializeObject(reqObject); // Requested Api End Point . Replace end point to call other api string endPoint = @"birth_details/"; // Calling APi from here /** * Change userid and Api Key Before using this. * Replace your userId and ApiKey in this file * App_Code/ApiCalls.cs */ var client = new ApiCall(); var res = client.makeApiCall(endPoint, requestJson); // Converting rturn data into json object var convertObj = JObject.Parse(res); // Display the data where you want dayResponse.Text = (string)convertObj.SelectToken("day"); monthResponse.Text = (string)convertObj.SelectToken("month"); yearResponse.Text = (string)convertObj.SelectToken("year"); hourResponse.Text = (string)convertObj.SelectToken("hour"); minResponse.Text = (string)convertObj.SelectToken("minute"); latResponse.Text = (string)convertObj.SelectToken("latitude"); lonResponse.Text = (string)convertObj.SelectToken("longitude"); tzoneResponse.Text = (string)convertObj.SelectToken("timezone"); sunriseResponse.Text = (string)convertObj.SelectToken("sunrise"); sunsetResponse.Text = (string)convertObj.SelectToken("sunset"); ananResponse.Text = (string)convertObj.SelectToken("ayanamsha"); entireResponse.Text = res; //See return response in console output System.Diagnostics.Debug.WriteLine("response--" + convertObj); }