I have this issue in production with MySQL connections where the connection is either being used or it's not opened error comes up frequently. I think when multiple requests hit the method then this issue is happening. I got stats from production were 80 different instances hit the Graphql method. I am using Sqlkata to make DB calls. When there are no parallel calls then it works fine.
ConnectionManager.cs
public IDbConnection GetConnection
{
get
{
if (_iDbConnection != null)
{
if (_iDbConnection.State != ConnectionState.Open)
{
_iDbConnection.Open();
return _iDbConnection;
}
}
if (_iDbConnection != null && _iDbConnection.State == ConnectionState.Open)
{
// close the previous connection
_iDbConnection.Close();
// open new connection
_iDbConnection.Open();
return _iDbConnection;
}
try
{
string connectionString = Configuration.GetConnectionString("seasonal");
// Register the factory
DbProviderFactories.RegisterFactory("MySqlConnector", MySqlConnectorFactory.Instance);
// Get the provider invariant names
IEnumerable<string> invariants = DbProviderFactories.GetProviderInvariantNames();
var factory = DbProviderFactories.GetFactory(invariants.FirstOrDefault());
var conn = factory.CreateConnection();
if (conn != null)
{
conn.ConnectionString = connectionString;
conn.Open();
_iDbConnection = conn;
}
}
catch (Exception e)
{
throw;
}
return _iDbConnection;
}
}
Service (constructor)
public OutboundRecordService(IConnectionManager connectionManager) : base(connectionManager)
{
IDbConnection connection = connectionManager.GetConnection;
if (connection.State != ConnectionState.Open)
{
_logger.Error($"Connection is not open, current state: {connection.State}");
}
_queryFactory = new QueryFactory(connection, new MySqlCompiler());
_logger = LogManager.GetLogger(typeof(OutboundRecordService<T>));
}
public async Task<CareMetx.Service.Models.PaginationResult<OutboundRecord>> GetAllByCriteria(OutboundRecordSearchCriteria searchCriteria)
{
try
{
// START - Test code
var arrayTask = new List<Task>();
int i = 10;
for (int c = 0; c < i; c++)
{
arrayTask.Add(Task.Factory.StartNew(() => GetDataFromDB(searchCriteria)));
}
Task.WaitAll(arrayTask.ToArray());
Console.WriteLine("All threads complete");
return await Task.FromResult<CareMetx.Service.Models.PaginationResult<OutboundRecord>>(null);
// END - Test code
}
catch (Exception ex)
{
var message = ex.Message;
}
return null;
}
private async Task<List<OutboundRecord>> GetDataFromDB(OutboundRecordSearchCriteria searchCriteria)
{
Query dbQuery = _queryFactory.Query("SELECT * FROM OutboundRecords Where BatchId = 1");
// Clone the query and get the total count
var totalCountQuery = dbQuery.Clone();
totalCountQuery = totalCountQuery.AsCount();
// Log Record Count SQL
LogSqlQuery(totalCountQuery);
// Get the total record count
var totalRecords = await totalCountQuery.FirstOrDefaultAsync<int>();
}
Exception
I am trying to fetch data from CRM using this API. I get an error
Runtime binding on a null reference
whenever I try to get value from data.fullname. Is there any way I can fix it?
Thanks
var response = httpClient.GetAsync("contacts?$select=fullname,emailaddress1").Result;
if (response.IsSuccessStatusCode)
{
var accounts = response.Content.ReadAsStringAsync().Result;
var jRetrieveResponse = JObject.Parse(accounts);
dynamic collContacts = JsonConvert.DeserializeObject(jRetrieveResponse.ToString());
try
{
foreach (var data in collContacts.value)
{
// You can change as per your need here
if (data.fullname.Value != null)
{
success[i] = data.fullname.Value;
}
i ++;
}
}
catch (Exception)
{
throw;
}
}
Replace
if (data.fullname.Value != null)
with this
if (!String.IsNullOrWhiteSpace(data.fullname.Value))
OR Replace
try
{
foreach (var data in collContacts.value)
{
// You can change as per your need here
if (data.fullname.Value != null)
{
success[i] = data.fullname.Value;
}
i ++;
}
}
catch (Exception)
{
throw;
}
With
try
{
foreach (var data in collContacts.value)
{
success[i] = data?.fullname?.Value;
i ++;
}
}
catch (Exception)
{
throw;
}
I am trying to Get EventMessage from Message in MS Graph API with C# but every time it is showing type as a message instead of EventMessage. Below are the code:-
public static Graph.MailFolderMessagesCollectionPage ReadInbox()
{
GetAuthenticatedClient();
var result = new Graph.MailFolderMessagesCollectionPage();
List<Graph.QueryOption> options = new List<Graph.QueryOption>
{
new Graph.QueryOption("$expand","microsoft.graph.eventMessage/event"),
new Graph.QueryOption("$filter","isread eq false")
};
try
{
var response = graphClient.Me.MailFolders.Inbox.Messages.Request(options).OrderBy("receivedDateTime DESC").GetAsync();
result = response.Result as Graph.MailFolderMessagesCollectionPage;
}
catch (Exception ex)
{ }
Call the above method ReadInbox to get type and perform some action.
var appointments = ReadInbox();
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (request.GetType().Name.Contains("EventMessage"))
{
}
else if (request.GetType().Name == "Message")
{
}
}
catch (Exception ex)
{
}
}
}
Use the IsInstanceOfType method to identify if its an eventMessage. You can also remove the expand option from the query option since eventMessages are fetched anyway as part of the get Messages call.
if (appointments != null)
{
foreach (dynamic request in appointments)
{
try
{
if (typeof(EventMessage).IsInstanceOfType(request))
{
Console.WriteLine("Is an event");
Console.WriteLine(request);
}
}
catch (Exception ex)
{
}
}
}
The code below is not working. (no exceptions thrown). Totally clueless why is not changed When I check in the GUI, there is a new version, with no changes!
public static void SetEntityWebName(ProcessEntity entity, SPWeb entityWeb)
{
try
{
entityWeb.AllowUnsafeUpdates = true;
var welcomePageListItem = entityWeb.GetFile(entityWeb.RootFolder.WelcomePage).Item;
var welcomePage = entityWeb.GetFile(entityWeb.RootFolder.WelcomePage);
welcomePage.CheckOut();
if (entity.Type == Entity.Job)
{
entityWeb.Title = ((SyncJobs_Result)entity.Entity).JobName;
welcomePageListItem["Title"] = ((SyncJobs_Result)entity.Entity).JobName;
welcomePage.Update();
}
if (entity.Type == Entity.Client)
{
entityWeb.Title = ((SyncClients_Result)entity.Entity).ClientName;
welcomePageListItem["Title"] = ((SyncClients_Result)entity.Entity).ClientName;
welcomePage.Update();
}
if (entity.Type == Entity.Opportunity)
{
entityWeb.Title = ((SyncOpportunities_Result)entity.Entity).OpportunityName;
welcomePageListItem["Title"] = ((SyncOpportunities_Result)entity.Entity).OpportunityName;
welcomePage.Update();
}
welcomePage.CheckIn(string.Empty);
welcomePage.Publish(string.Empty);
entityWeb.Update();
}
catch (Exception ex)
{
}
}
I think you also have to update the welcomePageListItem list item .
I am not sure but , give it a try
I'm new in these things and I've been testing the api ...
and came to me a situation that is:
if the user changes the password of Facebook
the Access token is renewed ... and try to post the API Launches
an exception and the application crashes...
how to resolve this situation?
try {
FacebookApp app = new FacebookApp(FacebookToken);
var args = new Dictionary<string, object>();
args["message"] = "hi";
args["caption"] = "appcaption";
args["description"] = "appdescription";
args["name"] = "appname";
args["picture"] = "apppicture";
args["link"] = "applink";
app.ApiAsync((X) => { calback(X); }, null, "/me/feed", args, HttpMethod.Post);
}
catch (Exception ex) {
Uri url = new Uri("/MyFacebook.xaml", UriKind.Relative);
NavigationService.Navigate(url);
}
this is Api code, and it's crashing when throwing the OAuthExcepion at the line marked with "Exception HERE"
private static void ResponseCallback(IAsyncResult asyncResult, FacebookAsyncCallback callback, object state)
{
object result = null;
FacebookApiException exception = null;
try
{
var request = (HttpWebRequest)asyncResult.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream responseStream = response.GetResponseStream())
{
result = JsonSerializer.DeserializeObject(responseStream);
}
}
catch (FacebookApiException)
{
// Rest API Errors
throw;
}
catch (WebException ex)
{
// Graph API Errors or general web exceptions
exception = ExceptionFactory.GetGraphException(ex);
if (exception != null)
{
// Thow the FacebookApiException
throw exception;
}
throw; //Exception HERE
}
finally
{
// Check to make sure there hasn't been an exception.
// If there has, we want to pass null to the callback.
object data = null;
if (exception == null)
{
data = result;
}
#if SILVERLIGHT
callback(new FacebookAsyncResult(data, state, null, asyncResult.CompletedSynchronously, asyncResult.IsCompleted, exception));
#else
callback(new FacebookAsyncResult(data, state, asyncResult.AsyncWaitHandle, asyncResult.CompletedSynchronously, asyncResult.IsCompleted, exception));
#endif
}
}
thanks
The behavior of the SDK is intended. An exception is not "crashing" the application, but rather telling you when an error state has occurred. You are basically doing it correctly, but instead of catching Exception you should only catch FacebookOAuthException like this:
try {
FacebookApp app = new FacebookApp(FacebookToken);
var args = new Dictionary<string, object>();
args["message"] = "hi";
args["caption"] = "appcaption";
args["description"] = "appdescription";
args["name"] = "appname";
args["picture"] = "apppicture";
args["link"] = "applink";
app.ApiAsync("/me/feed", args, (X) => { calback(X); }, HttpMethod.Post);
}
catch (FacebookOAuthException) {
// This is where you would reauthorize the user or send them to a 'login' page
Uri url = new Uri("/MyFacebook.xaml", UriKind.Relative);
NavigationService.Navigate(url);
}
I would also suggest reading up on .Net exception handling to give you a better understanding of when and why they are used. http://msdn.microsoft.com/en-us/library/ms229005.aspx
Using the FacebookAuthenticationResult you can check if there was an error and then avoid to do the request:
private void FacebookLoginBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookAuthenticationResult authResult;
if (FacebookAuthenticationResult.TryParse(e.Uri, out authResult))
{
if (authResult.ErrorReason == "user_denied")
{
// Do something knowing that this failed (cancel). }
else
{
fbApp.Session = authResult.ToSession();
loginSucceeded();
}
}
}
Have you seen this post? http://dotnetslackers.com/articles/net/wFace-windows-phone-7-facebook-integration-part-1.aspx
Specifically, take a look at part 3 - http://dotnetslackers.com/articles/net/wp7Gesicht-windows-phone-7-facebook-integration-part-3.aspx
Could you store the access token, and then on error, show the login page again?