I'm reading data from remote MongoDB realm which syncs to my local realm, but it seems I can't read from my local realm after sync.
This is the message I get when I try to read from my local realm:
Unable to open a realm at path '/data/user/0/com.companyname.appname/files/default.realm': Incompatible histories. Expected a Realm with no or in-realm history, but found history type 3 Path:Exception backtrace:\n<backtrace not supported on this platform>.
Here is my code:
private async Task<Realm> OpenRealm()
{
try
{
var user = App.realmApp.CurrentUser;
//if user is not logged on yet log on the user and sync
if (user == null)
{
var CurrentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
var config = new SyncConfiguration("Hirschs", CurrentUser);
_realm = await Realm.GetInstanceAsync(config);
return _realm;
}
else
{
return _realm = Realm.GetInstance();
}
}
catch (Exception ex)
{
await UserDialogs.Instance.AlertAsync(new AlertConfig
{
Title = "An error has occurred",
Message = $"An error occurred while trying to open the Realm: {ex.Message}"
});
// Try again
return await OpenRealm();
}
}
The problem here is that you are trying to create a new local realm in the same path where the synced realm already is.
I suppose that you would like to open the same realm synchronously (that is necessary if the device is offline). In this case you would just need to use the same configuration for both the sync and async calls, as reported in the documentation here.
You could do something like:
private async Task<Realm> OpenRealm()
{
try
{
var currentUser = App.realmApp.CurrentUser;
if (currentUser == null)
{
var currentUser = await App.realmApp.LogInAsync(Credentials.Anonymous());
var config = new SyncConfiguration("Hirschs", currentUser);
_realm = await Realm.GetInstanceAsync(config);
return _realm;
}
else
{
var config = new SyncConfiguration("Hirschs", currentUser);
_realm = Realm.GetInstance(config);
return _realm;
}
}
catch (Exception ex)
{
await UserDialogs.Instance.AlertAsync(new AlertConfig
{
Title = "An error has occurred",
Message = $"An error occurred while trying to open the Realm: {ex.Message}"
});
}
}
Related
I am running .net application which fetches data from SQL database and displays on the form screen.
When I run the application in UAT, it works fine but in PROD, I am getting below exception
Query run fine on database but I am getting this exception.
PricingClinet.cs -
public async Task<SaveResponse> SaveAsync(Sheet sheet)
{
SaveResponse result = null;
try
{
var response = await _client.PostAsJsonAsync("Pricing/Save", sheet);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonResult = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<SaveResponse>(jsonResult);
}
else
{
var errorMessage = string.Format("StatusCode: {0}\r\n{1}", response.StatusCode.ToString(), response.ReasonPhrase);
Logger.LogError(errorMessage);
result = new SaveResponse()
{
Success = false,
ErrorMessage = errorMessage
};
}
}
catch (Exception error)
{
Logger.LogError(error);
result = new SaveResponse()
{
Success = false,
ErrorMessage = ExceptionManager.RenderErrorMessage(error)
};
}
return result;
}
This error is hapenning in PROD only, not in UAT.
This is a timeout in a await _client.PostAsJsonAsync.
You need to confirm that your PROD configuration is correct e.g. points to the correct server.
If your configuration is correct then you need to either increase the timeout
(e.g. _client.Timeout = ...) or make the remote call faster (if it's in your control obviously).
I have used the aws-samples example named aws-cognito-dot-net-desktop-app in C# and Android:
aws-cognito-dot-net-desktop-app
It works very well and correctly registers the user in Cognito.
To register a user, do the following:
bool success = await helper.SignUpUser(etUserName.Text, etPasswordUser.Text, etEmailUser.Text, etPhoneUser.Text);
That way the user is created, but a code needs to be entered that is sent to the user's email. The code entry is as follows:
CognitoHelper cognitoHelper = new CognitoHelper();
return await cognitoHelper.VerifyAccessCode(userName, codeSentToMail);
and the user registers without problems, that is to say, it works correctly:
Now I want to delete any user created, for which I am creating a task as follows:
internal async Task<bool> DeleteUser(string username)
{
try
{
AmazonCognitoIdentityProviderClient provider =
new Amazon.CognitoIdentityProvider.AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast1);
DeleteUserPoolRequest request = new DeleteUserPoolRequest();
request.UserPoolId = username;
DeleteUserPoolResponse deleteUserPoolClientResponse = await provider.DeleteUserPoolAsync(request);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
When executing DeleteUserPoolRequest, an exception is thrown indicating an error of type Amazon.Runtime.ErrorType.Unknown
Any idea what I'm doing wrong?
Any comments or suggestions are welcome.
public static async Task<bool> DeleteUserFromAws(string emailId)
{
try
{
AmazonCognitoIdentityProviderClient cognito =
new AmazonCognitoIdentityProviderClient(awsAccessKeyId, awsSecretAccessKey, Region1);
CognitoUserPool cognitoUserPool = new CognitoUserPool(poolId, appClienId, cognito);
AdminGetUserRequest adminGetUserRequest = new AdminGetUserRequest();
adminGetUserRequest.Username = emailId;
adminGetUserRequest.UserPoolId = poolId;
AdminGetUserResponse adminGetUserResponse = await cognito.AdminGetUserAsync(adminGetUserRequest);
var getUserNameByEmaliID = adminGetUserResponse.Username;
AmazonCognitoIdentityProviderClient provider =
new AmazonCognitoIdentityProviderClient(awsAccessKeyId, awsSecretAccessKey, Region1);
AdminDeleteUserRequest request = new AdminDeleteUserRequest();
CancellationToken cancellationToken = default;
request.Username = getUserNameByEmaliID;
request.UserPoolId = poolId;
await provider.AdminDeleteUserAsync(request,cancellationToken);
return true;
}
catch (Exception ex)
{
Logger.log(ex, (Int32)Category.Fatal, (Int32)Priority.High);
throw;
}
}
I need to trigger some computation on an IotEdge module from an Administration-Backend Application.
On https://learn.microsoft.com/en-us/azure/iot-edge/module-development it says
Currently, a module cannot receive cloud-to-device messages
So it seems that calling direct methods seems to be the way to go. How can I implement a direct method and trigger it from within a .NET Core App?
In Main or Init Method of your IotEdge module you have to create a ModuleClient and connect it to a MethodHandler:
AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
ITransportSettings[] settings = { amqpSetting };
ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await ioTHubModuleClient.OpenAsync();
await ioTHubModuleClient.SetMethodHandlerAsync("MyDirectMethodName", MyDirectMethodHandler, null);
Then you have to add the DirectMethodHandler to your IotEge module:
static async Task<MethodResponse> MyDirectMethodHandler(MethodRequest methodRequest, object userContext)
{
Console.WriteLine($"My direct method has been called!");
var payload = methodRequest.DataAsJson;
Console.WriteLine($"Payload: {payload}");
try
{
// perform your computation using the payload
}
catch (Exception e)
{
Console.WriteLine($"Computation failed! Error: {e.Message}");
return new MethodResponse(Encoding.UTF8.GetBytes("{\"errormessage\": \"" + e.Message + "\"}"), 500);
}
Console.WriteLine($"Computation successfull.");
return new MethodResponse(Encoding.UTF8.GetBytes("{\"status\": \"ok\"}"), 200);
}
From within your .Net core Application you can then trigger the direct method like this:
var iotHubConnectionString = "MyIotHubConnectionString";
var deviceId = "MyDeviceId";
var moduleId = "MyModuleId";
var methodName = "MyDirectMethodName";
var payload = "MyJsonPayloadString";
var cloudToDeviceMethod = new CloudToDeviceMethod(methodName, TimeSpan.FromSeconds(10));
cloudToDeviceMethod.SetPayloadJson(payload);
ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
try
{
var methodResult = await serviceClient.InvokeDeviceMethodAsync(deviceId, moduleId, cloudToDeviceMethod);
if(methodResult.Status == 200)
{
// Handle Success
}
else if (methodResult.Status == 500)
{
// Handle Failure
}
}
catch (Exception e)
{
// Device does not exist or is offline
Console.WriteLine(e.Message);
}
I use RestSharp to pass data between the clien-side (Xamarin android app) and my server.
When there is an error (usually because the server is down) the method that execute the request throw an exception.
I want the exception to go back all the way to the method who called it, so I can throw an error to the user.
For example, I want to login, but lets say the server is down.
A - The method that execute the request
public Task<T> ExecuteAsync<T>(RestRequest request) where T : new()
{
var client = new RestClient
{
BaseUrl = new Uri(BaseUrl),
Authenticator = new HttpBasicAuthenticator(_accountName, _password)
};
var taskCompletionSource = new TaskCompletionSource<T>();
client.ExecuteAsync<T>(request, restResponse =>
{
if (restResponse.ErrorException != null)
{
throw (new Exception("Server returned an error"));
}
taskCompletionSource.SetResult(restResponse.Data);
});
return taskCompletionSource.Task;
}
B - Method that uses method A to execute a request
public static async Task<LoginObject> Login(string accessNumber, string password, string token)
{
var request = new RestRequest
{
Method = Method.POST,
Resource = "Login"
};
request.AddJsonBody(
new
{
accessNumber = accessNumber,
password = password,
token = token
});
var isDone = await Api.ExecuteAsync<LoginObject>(request);
return isDone;
}
C - The method where I want to handle the exception
public async Task Login(string PhoneNumber, string Password)
{
try
{
LoginObject login = await LoginServices.Login(PhoneNumber, Password, Token);
if (login.IsOk)
{
// Move to next activity
}
else
{
Toast.MakeText(this, "Login Error", ToastLength.Short).Show();
}
}
catch (Exception ex) // Here I want to throw the server error
{
Toast.MakeText(this, "Server Error", ToastLength.Short).Show();
return null;
}
}
Now when I run the code, the error is being thrown in A, and the app crash,
I want it to go from A to B and from B to C, and then I'll show an error to the user.
Edit: I tried to put a try/catch block but it still throws the exception in A.
Change method A to have async in the signature and then change your last line to return await taskCompletionSource.Task;
In your A-method, please use taskCompletionSource.SetException like this:
if (restResponse.ErrorException != null)
{
//throw new Exception("Server returned an error");
taskCompletionSource.SetException(new Exception("Server returned an error"));
}
else
{
taskCompletionSource.SetResult(restResponse.Data);
}
In your B-method replace this line:
var isDone = await Api.ExecuteAsync<LoginObject>(request);
with this to re-throw the exception to you C-method:
LoginObject isDone=null;
try
{
isDone = await Api.ExecuteAsync<LoginObject>(request);
}
catch (Exception e)
{
throw e;
}
This article is talking about TaskCompletionSource
Here Is My method where I am getting userdetails who logging my application.I want to check the request is coming from desktop or mobile,using User agent.How can I do this?
public UserDetails Authenticate()
{
try
{
_logger.Info("authenticating...");
var message = OperationContext.Current.RequestContext.RequestMessage;
var request = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];
string token = request.Headers[HttpRequestHeader.Authorization];
var base64decodedtoken = this.Base64Decode(token);
UserBLL user = new UserBLL();
var userdetails = user.GetUserDetails(base64decodedtoken, true);
if (userdetails.UserId > 0)
{
_logger.Info("authentication successfull... for user id" + userdetails.UserId);
int i = user.AuditUserLogin(userdetails.Email);
}
else
{
_logger.Info("Unauthorised Access" + userdetails.Email);
}
return userdetails;
}
catch (Exception ex)
{
_logger.Error("Error Occured in Authentication Service", ex);
ErrorData errorData = new ErrorData("Error Occured ", ex.Message);
throw new WebFaultException<ErrorData>(errorData, HttpStatusCode.Unauthorized);
}
}
Please refer to this MDN article for your answer.
Basically, the mobile/desktop detection by user-agent is not suggested, but if you have to get your work sorted in this way, you can also refer to this link