How to get google app engine logs in C#? - c#

I am trying to retrieve app engine logs the only result I get is "# next_offset=None", below is my code:
internal string GetLogs()
{
string result = _connection.Get("/api/request_logs", GetPostParameters(null));
return result;
}
private Dictionary<string, string> GetPostParameters(Dictionary<string, string> customParameters)
{
Dictionary<string, string> parameters = new Dictionary<string, string>() {
{ "app_id", _settings.AppId },
{ "version", _settings.Version.ToString() }
};
if (customParameters != null)
{
foreach (string key in customParameters.Keys)
{
if (parameters.ContainsKey(key))
{
parameters[key] = customParameters[key];
}
else
{
parameters.Add(key, customParameters[key]);
}
}
}
return parameters;
}

This method requires version parameter to be version.1

Related

Avoid the root element while serializing Dictionary with DataContractJsonSerializer

I have a Dictionary like this which I want to serialize in Json:
xrmParentPluginContextProperties = new Dictionary<string, string> {
{ "source", className },
{ "correlationId", executionContext.ParentContext.CorrelationId.ToString() },
{ "depth", executionContext.ParentContext.Depth.ToString() },
{ "initiatingUserId", executionContext.ParentContext.InitiatingUserId.ToString() },
{ "isInTransaction", executionContext.ParentContext.IsInTransaction.ToString() },
{ "isolationMode", executionContext.ParentContext.IsolationMode.ToString() },
{ "message", executionContext.ParentContext.MessageName },
{ "mode", getModeName(executionContext.ParentContext.Mode) },
{ "operationId", executionContext.ParentContext.OperationId.ToString() },
{ "orgId", executionContext.ParentContext.OrganizationId.ToString() },
{ "orgName", executionContext.ParentContext.OrganizationName },
{ "requestId", executionContext.ParentContext.RequestId.ToString() },
{ "userId", executionContext.ParentContext.UserId.ToString() },
{ "entityId", executionContext.ParentContext.PrimaryEntityId.ToString() },
{ "entityName", executionContext.ParentContext.PrimaryEntityName },
{ "type", "Plugin" },
{ "stage", getStageName(executionContext.Stage) }
};
Then I have a helper class holding the dictionary for serialization:
public class DictionarySerializationHelperClass
{
public Dictionary<string, string> dictionary;
public DictionarySerializationHelperClass()
{
}
public DictionarySerializationHelperClass(Dictionary<string, string> dict)
{
this.dictionary = dict;
}
}
I call the serialization like this:
DictionarySerializationHelperClass dictionaryClass = new DictionarySerializationHelperClass(XrmProperties.currentPluginContext);
return SerializationHelper.JsonSerialize(dictionaryClass);
And the serialization itself:
public static string JsonSerialize<T>(T objectToSerialize) where T : class, new()
{
string serialisedJson = null;
DataContractJsonSerializer serializer;
try
{
using (MemoryStream serializationStream = new MemoryStream())
{
if (typeof(T) == typeof(Dictionary<string, string>))
{
serializer = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true,
RootName = string.Empty
});
}
else
{
serializer = new DataContractJsonSerializer(typeof(T));
}
serializer.WriteObject(serializationStream, objectToSerialize);
serializationStream.Position = 0;
var reader = new StreamReader(serializationStream);
serialisedJson = reader.ReadToEnd();
}
}
catch (Exception ex)
{
string error = $"Error on Serializing JSON: \r\n\r\n{objectToSerialize}";
throw new JsonException(error, ex);
}
return serialisedJson;
}
The problem with the result is that I always get the following json which includes the root element "dictionary":
{
"dictionary":{
"source":"asdasdasd",
"correlationId":"asdasdasd",
"depth":"1",
"initiatingUserId":"asdasdasd",
"isInTransaction":"False",
"isolationMode":"2",
"message":"Retrieve",
"mode":"Synchronus",
"operationId":"asdasd",
"orgId":"esdfsdf",
"orgName":"asdasdasd",
"requestId":"asdasdasd",
"userId":"asdasdasd",
"entityId":"asdasdasd",
"entityName":"incident",
"type":"Plugin",
"stage":"Pre-operation"
}
}
How can I remove this root element to have finally the json looking like this?
{
"source":"asdasdasd",
"correlationId":"asdasdasd",
"depth":"1",
"initiatingUserId":"asdasdasd",
"isInTransaction":"False",
"isolationMode":"2",
"message":"Retrieve",
"mode":"Synchronus",
"operationId":"asdasd",
"orgId":"esdfsdf",
"orgName":"asdasdasd",
"requestId":"asdasdasd",
"userId":"asdasdasd",
"entityId":"asdasdasd",
"entityName":"incident",
"type":"Plugin",
"stage":"Pre-operation"
}
I've tried to set
Root = string.Empty
in the DataContractJsonSerializerSettings but it seems not to help.
Any hint is highly appreciated.

How to create custom validation based on xml in .net 6

I am trying to perform validation using custom class attributes. I have to keep my model validation rules inside XML files. Custom Class attribute specifies the path to the XML file and custom attributes will contain the logic to read XML files and get the validation rules for that class. When I will call Model.Isvalidate() that time Validation will get executed. I already have this working in .Net 4.5 MVC application. The same thing I am trying in .Net 6 its not working.
public class CustomDynamicModelValidatorProvider : DataAnnotationsModelValidatorProvider,IModelValidatorProvider
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
{
string resourceKeyPath = string.Empty;
IList<Attribute> newAttributes = new List<Attribute>(attributes);
CustomDynamicValidatorsAttribute resourceMapperAttr = attributes.FirstOrDefault(a => a is CustomDynamicValidatorsAttribute) as CustomDynamicValidatorsAttribute;
if (resourceMapperAttr == null)
{
System.Reflection.MemberInfo classInfo = metadata.ContainerType;
if (classInfo != null)
{
var resourceMapperRootAttr = classInfo.GetCustomAttributes(typeof(ResourceMappingRootAttribute), false).FirstOrDefault() as ResourceMappingRootAttribute;
if (resourceMapperRootAttr != null)
{
resourceKeyPath = resourceMapperRootAttr.Path + "." + metadata.PropertyName;
}
}
}
else
{
resourceKeyPath = resourceMapperAttr.ResourceKeyPath;
}
if (!string.IsNullOrEmpty(resourceKeyPath))
{
string[] validators = ResourceManager.GetValidators(resourceKeyPath).Replace(" ", "").Split(',');
var maxLength = ResourceManager.GetMaxLength(resourceKeyPath);
if (!string.IsNullOrEmpty(maxLength))
{
var required = new MaxLengthAttribute(maxLength.ToInteger());
required.ErrorMessage = string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.MaximumLengthExceeded"), maxLength);
newAttributes.Add(required);
}
for (int i = 0; i < validators.Length; i++)
{
if (string. Equals(validators[i], "required", StringComparison.OrdinalIgnoreCase))
{
var required = new CustomRequiredAttribute();
newAttributes.Add(required);
}
else if (validators[i].StartsWith("email", StringComparison.OrdinalIgnoreCase))
{
var email = new CustomEmailAttribute();
newAttributes.Add(email);
}
}
}
return base.GetValidators(metadata,validatorProviders);
}
public static IDictionary<string, object> GetValidatorAttributes(string validators)
{
IDictionary<string, object> attributes = new Dictionary<string, object>();
string[] validatorList = !string.IsNullOrEmpty(validators) ? validators.Replace(" ", "").Split(',') : new string[] { };
foreach (var item in validatorList)
{
if (!attributes.Keys.Contains("data-val"))
{
attributes.Add("data-val", "true");
}
if (string.Equals(item, "required", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-required", CustomAttributeHelper.GetResourceText("Shared.Messages.Mandatory"));
}
else if (item.StartsWith("email", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-email", CustomAttributeHelper.GetResourceText("Shared.Messages.vEmailField"));
}
else if (item.StartsWith("phone", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-phone", CustomAttributeHelper.GetResourceText("Shared.Messages.vPhoneField"));
}
else if (item.StartsWith("zipcode", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-zipcode", CustomAttributeHelper.GetResourceText("Shared.Messages.vZipCodeField"));
}
else if (item.StartsWith("mark", StringComparison.OrdinalIgnoreCase))
{
string min = string.Empty;
string max = string.Empty;
string rangeValidatorMessage = string.Empty;
if (item.Contains("-"))
{
var rangeArray = item.Split('-');
if (rangeArray.Length > 2)
{
min = rangeArray[1];
max = rangeArray[2];
rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange");
}
else
{
max = rangeArray[1];
rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.vNumericLimited");
}
}
else
{
max = "10000";
}
if (!string.IsNullOrWhiteSpace(min))
{
attributes.Add("data-val-range-min", min);
}
attributes.Add("data-val-range-max", max);
attributes.Add("data-val-range", rangeValidatorMessage);
}
else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-number", CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange"));
}
else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-decimal", string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.DecimalRange"), CustomAttributeHelper.GetResourceText("Shared.Limits.Decimal")));
}
else if (item.StartsWith("file-", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-filetype", item.Split('-')[1]);
}
}
return attributes;
}
public void CreateValidators(ModelValidatorProviderContext context)
{
}
}

IOS 14 request limited photo access

I'm trying to use PHPickerController and access PHAsset to get file name and file size but the PHAsset are null
var config = new PHPickerConfiguration(PHPhotoLibrary.SharedPhotoLibrary) {
Filter = PHPickerFilter.ImagesFilter,
SelectionLimit = 1
};
var picker= new PHPickerViewController(config) {
ModalPresentationStyle = UIModalPresentationStyle.Popover,
Delegate = new ImagePickerDelegate((fileSize, fileName, url) => {
})
};
ViewController.PresentViewController(picker, true, null);
public class ImagePickerDelegate : PHPickerViewControllerDelegate
{
public ImagePickerDelegate(Action<int, string, string> action)
{
Action = action;
}
public Action<int, string, string> Action { get; }
public override void DidFinishPicking(PHPickerViewController picker, PHPickerResult[] results)
{
picker.DismissViewController(true, null);
foreach (var result in results)
{
var asset = PHAsset.FetchAssets(result.AssetIdentifier, null)?.firstObject as PHAsset;
// The asset are null
var fileSize = asset.ValueForKey((NSString)"fileSize");
}
}
}
As you can see in the image the request dialog show and code are not pause on following line
var asset = PHAsset.FetchAssets(result.AssetIdentifier, null)?.firstObject as PHAsset;
and return null
You could use FetchAssetsUsingLocalIdentifiers method to get PHAsset object, then it will return value.
Sample code as follows:
public override void DidFinishPicking(PHPickerViewController picker, PHPickerResult[] results)
{
picker.DismissViewController(true, null);
foreach (var result in results)
{
var refID = result.AssetIdentifier;
string[] refIDs = new string[] { refID };
var asset = PHAsset.FetchAssetsUsingLocalIdentifiers(refIDs, null)?.firstObject as PHAsset;
// var fileSize = asset.ValueForKey((NSString)"fileSize");
}
}
Also could have a look at this native code link.

c# pattern to avoid using switch statement for repeated similar logic

I have a c# application where I need to return translated keypair value for different views.
For example, these are some of my views:
login
admin account
admin settings
admin employee
admin holiday
and so on.
Then every view call the same method for returning a dictionary of translation strings.
public ActionResult GetTranslations(string viewName)
{
// THIS IS A SAMPLE OF HOW TO GET THE TRANSLATIONS
Dictionary<string, string> translations = new Dictionary<string, string>
{
{ "usernamerequired", HttpContext.GetText("The user name is required","") },
{ "passrequired", HttpContext.GetText("The password is required", "") },
};
string json = JsonConvert.SerializeObject(points, Formatting.Indented);
var response = new JsonResponse
{
data = translations ,
message = "",
num = 0,
success = true,
code = null
};
return Json(response, JsonRequestBehavior.AllowGet);
}
So in order to avoid using "n" amount of Switch statements like:
Dictionary<string, string> translations = null;
switch(viewName)
{
case "login":
// specific translation for login
translations = new Dictionary<string, string>
{
{ "usernamerequired", HttpContext.GetText("The user name is required","") },
{ "passrequired", HttpContext.GetText("The password is required", "") },
};
break;
// HERE OTHER CASES FOR THE OTHER VIEWS
}
Instead I would like to use a cleaner way, I was thinkin on having an interface like:
// Interface
interface ITranslation
{
Dictionary<string, string> GetViewTranslations();
}
// Login translation class
class LoginTranslation: ITranslation
{
public Dictionary<string, string> GetViewTranslations()
{
// here the dictrionary generation code..
}
}
// Admin Settings translation class
class AdminSettingsTranslation: ITranslation
{
public Dictionary<string, string> GetViewTranslations()
{
// here the dictrionary generation code..
}
}
Of maybe there is a better and cleaner way, any advice or clue?

How to make a request asynchronously in c# (xamarin)?

I used to work with browser-based applications. for example Angular simple repository.
function getSomeData(params) {
...
return $http({
url: conf.urlDev + 'some/rest-url',
method: "GET",
params: params,
cache: true
}).then(getDataComplete);
function getDataComplete(response) {
return response.data;
}
}
How it will look the same in c# (XAMARIN for example)?
i try :
public class BaseClient
{
protected Http _client = null;
protected string _urlObj;
protected string _basePath;
public BaseClient ()
{
_client = new Http(new HttpClientHandler());
}
public string Path
{
set
{
_urlObj = value;
}
}
public async Task<Result<IList<T>>>getList<T>(Dictionary<string,object> parametrs = null)
{
if (parametrs != null)
{
foreach(KeyValuePair<string, object> keyValue in parametrs)
{
_urlObj = _urlObj.SetQueryParam(keyValue.Key, keyValue.Value);
}
}
var response = await _client.GetAsync(_urlObj.ToString());
if (response.IsSuccessStatusCode)
{
return new Result<IList<T>>()
{
Success = true,
Value = JsonConvert.DeserializeObject<IList<T>>(await response.Content.ReadAsStringAsync())
};
}
else
{
var error = new Result<IList<T>>()
{
Error = response.StatusCode.ToString(),
Message = response.ReasonPhrase,
Success = false
};
return error;
}
}
in my service:
public async Task<IList<News>> GetAllNewsByParams(DateTime from,
string orderBy = "-published",
DateTime to = new DateTime(),
int page = 1, int category = 0)
{
_client.Path = _config.NewsPath;
var dict = new Dictionary<string, object> {
{"from", from.ToString("s")},
{"order_by", orderBy.ToString()},
{"to", to.ToString("s")},
{"page", page.ToString()}
};
if (category != 0)
{
dict.Add("category", category.ToString());
}
var res = await _client.getList<News>(dict);
return res.Value;
}
and im ny viewmodel
foreach (var item in await _newsService.GetAllNewsByParams(
_To,
_OrderBy,
_From, _Page,
selectedTag == null ? _SeletedNewsTagId : selectedTag.Id))
{
NewsList.Add(item);
}
Is his query executed synchronously ?
How do I make it an asynchronous?
First of all I would really encourage you to use RestSharp, it really simplifies making HTTP requests and deserialise them. Add a RestSharp nuget package to your project. Here is how your code will look like using RestSharp.
public class BaseClient
{
protected IRestClient _client = null;
protected string _urlObj;
protected string _basePath;
public BaseClient()
{
_client = new RestClient();
}
public async Task<Result<IList<T>>> GetList<T>(string path, Dictionary<string, object> parametrs = null)
{
var request = new RestRequest(path, Method.GET);
if (parametrs != null)
{
foreach (var keyValue in parametrs)
{
request.AddQueryParameter(keyValue.Key, keyValue.Value);
}
}
var response = await _client.Execute<List<T>>(request);
if (response.IsSuccess)
{
return new Result<IList<T>>()
{
Success = true,
Value = response.Data
};
}
else
{
var error = new Result<IList<T>>()
{
Error = response.StatusCode.ToString(),
Message = response.StatusDescription,
Success = false
};
return error;
}
}
}
In your service
public async Task<IList<News>> GetAllNewsByParams(DateTime from,
string orderBy = "-published",
DateTime to = new DateTime(),
int page = 1, int category = 0)
{
var dict = new Dictionary<string, object> {
{"from", from.ToString("s")},
{"order_by", orderBy.ToString()},
{"to", to.ToString("s")},
{"page", page.ToString()}
};
if (category != 0)
{
dict.Add("category", category.ToString());
}
var res = await _client.GetList<News>(_config.NewsPath, dict);
return res.Value;
}
And in your viewmodel
var news = await _newsService.GetAllNewsByParams(
_To,
_OrderBy,
_From, _Page,
selectedTag == null ? _SeletedNewsTagId : selectedTag.Id);
foreach (var item in news)
{
NewsList.Add(item);
}
This will be 100% asynchronous.

Categories

Resources