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)
{
}
}
}
Have a quote application, which we fill the data and send from source system to receiver system. That receiver system will be sending status of that quote(Success/Failed) as Acknowledgement to source system. We have an option to revise the same quote. whenever we revise the quote, the Status is inherited from previous quote. we need to clear the latest revision's status. which is not happening. but it clears previous revision's status. Could anyone help me.
if (plm == "PLM")
{
if (id.Revision != 0)
{
var javascriptSerializer = new JavaScriptSerializer();
var urn = line.CustomProperties?.FirstOrDefault(k => k.Key.ToLower() == "urn")?.Value;
oRecordLog.WriteToLogFile("Updating DBValue");
//initilizing document store object to query the documents from database.
IDocumentStore ravenDB = new DocumentStore { Url = "http://localhost:8072", DefaultDatabase = "Configit.Quote" }.Initialize();
try
{
List<Document> docs;
using (var session = ravenDB.OpenSession())
{
oRecordLog.WriteToLogFile("Opened RavenDB session");
//getting the URN value.
var javaScriptSerializer = new JavaScriptSerializer();
string urnString = urn;
ModelKeyValuePair urnKeyValue = new ModelKeyValuePair();
urnKeyValue.Key = "URN";
urnKeyValue.Value = javaScriptSerializer.Serialize(urnString);
//wait for 5 seconds before the next query
docs = session.Query<Document>().Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(5))).Where(x => x.Lines.Any(l => l.Properties.Any(ID => ID == urnKeyValue))).ToList();
try
{
oRecordLog.WriteToLogFile("docs " + docs.Count);
//processing one by one document from RavenDB.
foreach (var doc in docs)
{
string quoteGuid = null;
if (doc.LinesCount > 0)
{
int lineCnt = doc.LinesCount;
// processing each line in the docuement getting the quoteID
foreach (var quoteline in doc.Lines)
{
if ((quoteline.Properties.ContainsKey("Urn")) || (quoteline.Properties.ContainsKey("URN")) || (quoteline.Properties.ContainsKey("urn")))
{
Guid lGuid = quoteline.LineId;
var quote_ForID = _quoteStorage.GetQuote(new QuoteRevisionId(id.QuoteId, id.Revision));
var urn_ForQuoteId = quoteline.Properties?.FirstOrDefault(k => k.Key == "URN")?.Value;
if (GetUniqueRefnum(quote_ForID, quoteline) == urn_ForQuoteId)
{
quoteGuid = doc.DocumentId.ToString();
oRecordLog.WriteToLogFile("quoteGuid " + quoteGuid);
var TransferStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "TransferStatus");
var PLMDetailedStatus = quoteline.Properties?.FirstOrDefault(p => p.Key == "PLMDetailedStatus");
TransferStatus.Value = "";
PLMDetailedStatus.Value = "";
}
}
}
}
else
{
oRecordLog.WriteToLogFile("Quote ID not found");
}
}
session.SaveChanges();
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
}
}
catch (Exception e)
{
//printing error logs in Acknowledgement.txt.
oRecordLog.WriteToLogFile(" exception caught main Stacktrace-----" + e.StackTrace);
oRecordLog.WriteToLogFile(" exception caught main Message-----" + e.Message);
oRecordLog.WriteToLogFile(" exception caught main Inner Exception-----" + e.InnerException);
return null;
}
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
else
{
oRecordLog.WriteToLogFile("This is new quote");
orderupdateservice.BeginUpload(lineCount, linid, TargetSystem.Plm);
}
}
I can't figure this out why I keep getting the compilation error: "not all code paths return a value". I am writing a simple class method that is supposed to return true if the account is available to use and false if the account is not available or is null/empty. The code for the method is below:
public static bool AccountAvailable(int AccountId)
{
try
{
bool accountavailable;
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
return accountavailable;
}
catch
{
}
}
Any help or advice on this would be appreciated. Thanks!!
If an exception is thrown in your code before you return a value then control moves to the catch block. It then reaches the end of the method without returning anything.
Either return something within, or after, the catch block.
In your catch block, add a return:
catch (Exception ex)
{
// your code
return null;
}
The suggest to try this code
public static bool AccountAvailable(int AccountId)
{
bool accountavailable = false;
try
{
string queryTransaction = "Select Count(AccountID) FROM Accounts WHERE AccountID = " + AccountId.ToString() + " AND AccountUsed = 0";
//grab a connection to the database
Database database = DatabaseFactory.CreateDatabase();
//create an instance of the command
DbCommand command = database.GetSqlStringCommand(queryTransaction);
object dataobject = command.ExecuteScalar();
if (dataobject == null || string.IsNullOrEmpty(Convert.ToString(dataobject)))
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) == 0)
{
accountavailable = false;
}
else if (Convert.ToInt32(dataobject) > 0)
{
accountavailable = true;
}
else
{
accountavailable = true;
}
}
catch
{
}
return accountavailable;
}
I am new to ExtJS,i used in asp.net,C# in VS2008.. i simply added comboBox control with static data in aspx page,
but i need to know how to bind the value from sql DB , can any one provide any sample application which explains, how to get the value from the control and bind to the controls
Thanks in advance
Create a generic HTTP handler, for example our agency list uses this code:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
context.Response.ContentEncoding = Encoding.UTF8;
// Get User ID
int user_id;
try {
user_id = int.Parse(context.Session["user_id"].ToString());
} catch {
WriteErrorObject(context,"Could not find required user in the session.");
return;
}
// Get Query
string query;
try {
query = context.Request.QueryString["query"];
if (String.IsNullOrEmpty(query)) throw new Exception();
} catch {
query = "";
}
// Get Revision
int revision;
try {
revision = int.Parse(ConfigurationManager.AppSettings["reportingRevision"]);
} catch {
revision = -1;
}
// Check for our connection string
try {
if (ConfigurationManager.ConnectionStrings["reportInstance"] == null) throw new Exception();
} catch {
WriteErrorObject(context,"Cannot find the database connection string.");
return;
}
// Get our connection string
string connectionstring = ConfigurationManager.ConnectionStrings["reportInstance"].ConnectionString;
// Create our sproc caller
StoredProc proc;
try {
proc = new StoredProc("usp_rep2_agency_list",connectionstring,30);
} catch (Exception ex) {
WriteErrorObject(context,"There was an exception creating the stored procedure caller: " + ex.Message);
return;
}
// Set up sproc
if (revision != -1) proc.AddParameter("#revision",revision,SqlDbType.Int);
proc.AddParameter("#user_id",user_id,SqlDbType.Int);
if (query != null && query.Length > 0) proc.AddParameter("#query",query,SqlDbType.NVarChar);
// Execute sproc
DataSet results;
try {
results = (DataSet)proc.Execute(StoredProc.ExecuteTypes.ReturnDataset);
} catch (Exception ex) {
WriteErrorObject(context,"There was an exception calling the stored procedure: " + ex.Message);
return;
}
// Check we have results
if (results == null) {
WriteErrorObject(context,"There was no dataset returned from the stored procedure.");
return;
}
// Check we have a table
if (results.Tables.Count < 1) {
WriteErrorObject(context,"There was no tables found in the returned dataset from the stored procedure.");
return;
}
// Get the table
DataTable table = results.Tables[0];
// Begin JSON
StringWriter writer = new StringWriter();
JsonWriter json = new JsonWriter(writer);
json.WriteStartObject();
json.WritePropertyName("success");
json.WriteValue(true);
json.WritePropertyName("count");
json.WriteValue(table.Rows.Count);
json.WritePropertyName("list");
json.WriteStartArray();
// Process table rows
for (int i = 0; i < table.Rows.Count; i++) {
// Get row
DataRow row = table.Rows[i];
// ID
if (row["agency_id"] == null || row["agency_id"] == DBNull.Value) {
WriteErrorObject(context,"There was an error processing the agency id value from row " + i.ToString() + ".");
return;
}
int agency_id;
if (!int.TryParse(row["agency_id"].ToString(),out agency_id)) {
WriteErrorObject(context,"Could not parse the agency id value from row " + i.ToString() + ".");
return;
}
// Name
if (row["agency_name"] == null || row["agency_name"] == DBNull.Value) {
WriteErrorObject(context,"There was an error processing the agency name value from row " + i.ToString() + ".");
return;
}
string agency_name = row["agency_name"].ToString();
// Write out JSON for this row
json.WriteStartObject();
json.WritePropertyName("agency_id");
json.WriteValue(agency_id);
json.WritePropertyName("agency_name");
json.WriteValue(agency_name);
json.WritePropertyName("icon");
json.WriteValue("iq-reporting-dropdowns-agency");
json.WriteEndObject();
}
// End JSON
json.WriteEndArray();
json.WriteEndObject();
string text = writer.GetStringBuilder().ToString();
context.Response.Write(text);
context.Response.Flush();
}
In Ext we then do:
this.ddlAgency = new Ext.form.ComboBox({
fieldLabel: "Agency",
mode: "remote",
triggerAction: "all",
forceSelection: true,
displayField: "agency_name",
valueField: "agency_id",
iconField: "icon",
typeAhead: true,
minChars: 1,
allowBlank: false,
anchor: "100%",
emptyText: "Select an Agency...",
store: new Ext.data.Store({
autoLoad: false,
proxy: new Ext.data.HttpProxy({
method: "GET",
url: "whatever.ashx"
}),
reader: new Ext.data.JsonReader(
{root: "list", totalProperty: "count"},
[{name: "agency_id", type: "int"},{name: "agency_name", type: "string"},{name: "icon", type: "string"}]
),
baseParams: {
action: "agencylist",
level: 1
}
})
});
Note, we use the 'Json.NET' library to handle JSON output and a custom class, 'StoredProc' to do the database interaction. You also won't have the WriteErrorObject() method that simply serializes out an error, but you get the idea.