XElement NullReferenceException - linq

I have the following code.
XElement opCoOptOff = doc.Descendants(ns + "OpCoOptOff").FirstOrDefault();
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
Now if the element I return is null, I am getting a NullReferenceException since the XElement is null. So I changed it to the following.
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
if(opCoOptOff != null)
{
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
I am hoping there has to be a more elegant way to do this since this scenario comes up often and I would like to avoid doing this type of check every time there is an issue. Any assistance would be greatly appreciated

You can write an extension method and use it anywhere:
public static class XDocumentExtension
{
public static string GetSubElementValue(this XElement element, string item)
{
if(element != null && element.Value != null)
{
if (element.Element(item) != null)
{
return element.Element(item).Value;
}
}
return null;
}
public static XElement GetElement(this XElement element, string item)
{
if (element != null)
return element.Element(item);
return null;
}
public static XElement GetElement(this XDocument document, string item)
{
if (document != null)
return document.Descendants("item").FirstOrDefault();
return null;
}
}
Use it as :
String opCo = opCoOptOff.Element(ns + "strOpCo").GetSubElementValue(ns + "strOpCo");
Also you can add other extensions for your purpose.
Edit: I'd updated answer but if you read it carefully before I wrote you can add other extensions for your purpose. I wrote this because I guess you may be want to call on null objects Element, I don't know what's exact situation of yours but I add some code for more clarification, depend on your situation complete the XDocumentExtension class, and one note extension methods can work on null objects.

You can actually cast the XElement directly to a string:
http://msdn.microsoft.com/en-us/library/bb155263.aspx
so
String opCo = opCoOptOff.Element(ns + "strOpCo").Value;
could be
string opCo = (string) opCoOptOff.Element(ns + "strOpCo");

Related

CrmServiceClient cannot be instantiated

We have a situation where the CrmServiceClient class cannot be instantiated, with an 'Object reference not set to an object' error coming from deep within the bowels of the constructor. I've also received a Collection was modified; enumeration operation may not execute error in a few situations.
This does not happen all the time, but we seem to be able to reproduce it when we trigger multiple requests very quickly.
We create the object as follows:
var ctx = new CrmServiceClient(ConfigurationManager.ConnectionStrings["Xrm"].ConnectionString);
The connection string is valid and we have set RequireNewInstance to true
We were originally using the ctx in a using block but we were advised that we shouldn't be disposing of the CrmServiceClient, so we've removed the using block, but this has not resolved the problem.
The stack trace is below - i've only pasted the relevant part. The stack leading up to this point can be any piece of code that attempts to connect to the CRM to retrieve data
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at Microsoft.Xrm.Tooling.Connector.Utilities.GetOrgnameAndOnlineRegionFromServiceUri(Uri serviceUri, String& onlineRegion, String& organizationName, Boolean& isOnPrem)
at Microsoft.Xrm.Tooling.Connector.CrmConnection.SetOrgnameAndOnlineRegion(Uri serviceUri)
at Microsoft.Xrm.Tooling.Connector.CrmConnection..ctor(String serviceUri, String userName, String password, String domain, String homeRealmUri, String authType, String requireNewInstance, String clientId, String redirectUri, String tokenCacheStorePath, String loginPrompt, String certStoreName, String certThumbprint, String skipDiscovery)
at Microsoft.Xrm.Tooling.Connector.CrmConnection..ctor(IDictionary`2 connection)
at Microsoft.Xrm.Tooling.Connector.CrmConnection.Parse(String connectionString)
at Microsoft.Xrm.Tooling.Connector.CrmServiceClient.ConnectToCrmWebService(String crmConnectionString)
at Microsoft.Xrm.Tooling.Connector.CrmServiceClient..ctor(String crmConnectionString)
I believe I've tracked down the issue. I used DotNetPeek to look at the underlying code that was failing. The static method GetOrgnameAndOnlineRegionFromServiceUriwas where the error was occurring.
I tracked it down to a static list (discoSvcs) that was being set to null before the method returns. Other threads that call this method are also trying to do things with this list. It ends up that there is a race condition where one thread could check to see if it isn't null.
The only way I can get around it now is making sure only one CrmServiceClient is being instantiated at any time, by using a lock. This isn't ideal but I am running out of time
Static list definition
namespace Microsoft.Xrm.Tooling.Connector
{
public class Utilities
{
private static CrmOnlineDiscoveryServers discoSvcs;
private static List<string> _autoRetryRetrieveEntityList;
private Utilities()
{
}
Problem Function
The static list variable is checked at the beginning of this function and if it is null, it is populated with some values. It is then used later in the method before being set to null in the finally block.
public static void GetOrgnameAndOnlineRegionFromServiceUri(
Uri serviceUri,
out string onlineRegion,
out string organizationName,
out bool isOnPrem)
{
isOnPrem = false;
onlineRegion = string.Empty;
organizationName = string.Empty;
if (serviceUri.Host.ToUpperInvariant().Contains("DYNAMICS.COM") || serviceUri.Host.ToUpperInvariant().Contains("MICROSOFTDYNAMICS.DE") || (serviceUri.Host.ToUpperInvariant().Contains("MICROSOFTDYNAMICS.US") || serviceUri.Host.ToUpperInvariant().Contains("DYNAMICS-INT.COM")))
{
if (Utilities.discoSvcs == null)
Utilities.discoSvcs = new CrmOnlineDiscoveryServers();
try
{
List<string> stringList = new List<string>((IEnumerable<string>) serviceUri.Host.Split(new string[1]
{
"."
}, StringSplitOptions.RemoveEmptyEntries));
organizationName = stringList[0];
stringList.RemoveAt(0);
StringBuilder stringBuilder = new StringBuilder();
foreach (string str in stringList)
{
if (!str.Equals("api"))
stringBuilder.AppendFormat("{0}.", (object) str);
}
string crmKey = stringBuilder.ToString().TrimEnd('.').TrimEnd('/');
stringBuilder.Clear();
if (!string.IsNullOrEmpty(crmKey))
{
CrmOnlineDiscoveryServer onlineDiscoveryServer = Utilities.discoSvcs.OSDPServers.Where<CrmOnlineDiscoveryServer>((Func<CrmOnlineDiscoveryServer, bool>) (w =>
{
if (w.DiscoveryServer != (Uri) null)
return w.DiscoveryServer.Host.Contains(crmKey);
return false;
})).FirstOrDefault<CrmOnlineDiscoveryServer>();
if (onlineDiscoveryServer != null && !string.IsNullOrEmpty(onlineDiscoveryServer.ShortName))
onlineRegion = onlineDiscoveryServer.ShortName;
}
isOnPrem = false;
}
finally
{
Utilities.discoSvcs.Dispose();
Utilities.discoSvcs = (CrmOnlineDiscoveryServers) null;
}
}
else
{
isOnPrem = true;
if (((IEnumerable<string>) serviceUri.Segments).Count<string>() < 2)
return;
organizationName = serviceUri.Segments[1].TrimEnd('/');
}
}

C# Sort array of Objects by object type (Icomparable?)

I want to sort anarray by the object type. So all songs are together, all book are together, and all movies are together.
I am reading a file and determine what each object should be. then creating the object and adding it to the array.
EDIT: Here is the actual code.
static Media[] ReadData()
{
List<Media> things = new List<Media>();
try
{
String filePath = "resources/Data.txt";
string Line;
int counter = 0; // used to check if you have reached the max
number of allowed objects (100)
using (StreamReader File = new System.IO.StreamReader(filePath))
{
while ((Line = File.ReadLine()) != null)
{
This is where each object is created. The file
search for a key word in the beginning of the line, then
creates the corresponding object. It will split the
information on the first line of the object and will
read each line until a "-" character is found and
pass each line into the summary. The summary is then
decrypted and the created object is passed into an
array List. Finally if the array list reaches 100, it
will print "You have reach max number of objects" and
stop reading the file.
if (Line.StartsWith("BOOK"))
{
String[] tempArray = Line.Split('|');
//foreach (string x in tempArray){Console.WriteLine(x);} //This is used
for testing
Book tempBook = new Book(tempArray[1],
int.Parse(tempArray[2]), tempArray[3]);
while ((Line = File.ReadLine()) != null)
{
if (Line.StartsWith("-")){break;}
tempBook.Summary = tempBook.Summary + Line;
}
tempBook.Summary = tempBook.Decrypt();
things.Add(tempBook);
counter++;
}
else if (Line.StartsWith("SONG"))
{
String[] tempArray = Line.Split('|');
//foreach (string x in tempArray)
{Console.WriteLine(x);} //This is used for testing
Song tempSong = new Song(tempArray[1],
int.Parse(tempArray[2]), tempArray[3], tempArray[4]);
things.Add(tempSong);
counter++;
}
else if (Line.StartsWith("MOVIE"))
{
String[] tempArray = Line.Split('|');
//foreach (string x in tempArray)
{Console.WriteLine(x);} //This is used for testing
Movie tempMovie = new Movie(tempArray[1],
int.Parse(tempArray[2]), tempArray[3]);
while ((Line = File.ReadLine()) != null)
{
if (Line.StartsWith("-")) { break; }
tempMovie.Summary = tempMovie.Summary + Line;
}
tempMovie.Summary = tempMovie.Decrypt();
things.Add(tempMovie);
counter++;
}
if (counter == 100)
{
Console.WriteLine("You have reached the maximum number of media
objects.");
break;
}
}
File.Close();
}
}
return things.ToArray(); // Convert array list to an Array and return the
array.
}
In the main code, I have this:
Media[] mediaObjects = new Media[100];
Media[] temp = ReadData();
int input; // holds the input from a user to determin which action to take
for (int i = 0; i<temp.Length;i++){ mediaObjects[i] = temp[i]; }
I want the array of mediaObjects to be sorted by the what type of objects.
I have also used Icomparable to do an arrayList.sort() but still no luck.
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
Song temp = obj as Song;
if (temp != null)
{
//Type is a string
return this.Type.CompareTo(temp.Type);
}
else
{
return 1;
}
}
So I see you have BOOK, SONG and MOVIE types.
This is a classic case of implementing the IComparable interface - although you are correct with the interface name to implement, you are not using this correctly.
Create a base class by the name MediaObject - this will be the main one for your other types of objects you create.
Add the correct properties you need. In this case, the media type is the one in need.
Let this class implement IComparable to help you with the comparison.
override the CompareTo() method in the PROPER way
public class MediaObject : IComparable
{
private string mediaType;
public string MediaType
{
get {return mediaType;}
set {mediaType=value;}
}
public MediaObject(string mType)
{
MediaType = mType;
}
int IComparable.CompareTo(object obj)
{
MediaObject mo = (MediaObject)obj;
return String.Compare(this.MediaType,mo.MediaType); //implement a case insensitive comparison if needed (for your research)
}
}
You can now compare the MediaObject objects In your main method directly.
Thank for the advice. I ended up just reformating how I was creating the list while reading it. I made multiple lists for each object then just happened each one on to the master list so It showed up sorted. I wish I figured that out before I made this long post.
As far as I could find, you can't sort by the type of object in a generic array. If anyone has a better solution feel free to post it.

How to reduce the if-else depth?

I have this example code
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
String actionKey;
if(userAction != null){
if(currentTaskType != null){
actionKey = buildKey(currentTaskType, userAction);
if(dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
actionKey = buildKey(anyTaskType(), userAction);
if(dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
return new NullActionProcessor();
}
In this logic i have a map to store the ActionProcessable by combined-key TaskType and UserAction. This method will return ActionProcessable with input taskType and action. TaskType can be null so in that case we only need to get by userAction.
When i check this code by sonar, it say the third if is "Nested if-else depth is 2 (max allowed is 1)"
But i don't know how to make it better.
Does anyone suggest me something?
You can move "if containsKey" part out of condition to remove code duplication:
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
if (userAction != null) {
String actionKey = currentTaskType != null
? buildKey(currentTaskType, userAction)
: buildKey(anyTaskType(), userAction);
if (dossierActions.containsKey(actionKey)){
return dossierActions.get(actionKey);
}
}
return new NullActionProcessor();
}
Now, intent of the code looks more clear (at least, for me).
You can also make the first condition short-circuit and\or use ternary if for containsKey, it will remove even more ifs, but can make code more complex for some people.
public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
if (userAction == null) {
return new NullActionProcessor();
}
String actionKey = currentTaskType != null
? buildKey(currentTaskType, userAction)
: buildKey(anyTaskType(), userAction);
return dossierActions.containsKey(actionKey)
? dossierActions.get(actionKey);
: new NullActionProcessor();
}
Choose the one you like, they are technically similar.
Since you haven't specified specific programming language, one more thing to say: your code is a good example of use case of null-coalsecing operator. Sadly, AFAIK, there is none in Java. In C#, the code could look like this:
public static ActionProcessable GetActionProcessor(TaskType currentTaskType, UserAction userAction) {
if (userAction == null) {
return new NullActionProcessor();
}
var actionKey = BuildKey(currentTaskType ?? anyTaskType(), userAction);
return dossierActions[actionKey] ?? new NullActionProcessor();
}

How do I pass int array to RouteValueDictionary

I need generate this url: http://localhost:3178/Reports/?GroupId=1211&GroupId=1237
I'm trying:
var routeData = new RouteValueDictionary();
routeData.Add("GroupId", "1, 2");
getting: GroupId=1,%202
or
routeData.Add("GroupId", "1");
routeData.Add("GroupId", "2");
getting: An item with the same key has already been added
and even
routeData.Add("GroupId[0]", "1");
routeData.Add("GroupId[1]", "2");
getting: ?GroupId%5B0%5D=1&GroupId%5B1%5D=2
it's possible to somehow fix my issue?
The RouteValueDictionary is meant to provide information to routes. As such, I don't think it has the capability you're asking for. I've been using a custom helper to populate query string data based on what I pass into it:
public static string BuildPath(RequestContext context, string routeName, RouteValueDictionary routeValues, object additionalParams)
{
var vpd = RouteTable.Routes[routeName].GetVirtualPath(context, routeValues);
if (vpd == null)
return string.Empty;
var virtualpath = vpd.VirtualPath;
var addparams = BuildAdditionalParams(additionalParams);
if (!virtualpath.Contains("?") && addparams.Length > 0)
virtualpath = virtualpath + "?" + addparams;
else if (virtualpath.Contains("?") && addparams.Length > 0)
virtualpath = virtualpath + "&" + addparams;
return "/" + virtualpath;
}
protected static string BuildAdditionalParams(object additionalParams)
{
if (additionalParams == null)
return string.Empty;
StringBuilder sb = new StringBuilder();
Type type = additionalParams.GetType();
PropertyInfo[] props = type.GetProperties();
Action<string, string> addProperty = (name, value) =>
{
if (sb.Length > 0)
sb.Append("&");
sb.Append(name);
sb.Append("=");
sb.Append(value);
};
foreach (PropertyInfo prop in props)
{
var simplevalue = prop.GetValue(additionalParams, null);
if (simplevalue != null)
{
Type propertyType = prop.PropertyType;
if (Nullable.GetUnderlyingType(propertyType) != null)
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
if (propertyType.IsEnum)
{
addProperty(prop.Name, ((int)simplevalue).ToString());
}
else if (propertyType.IsArray && propertyType != typeof(string))
{
foreach (var val in prop.GetValue(additionalParams, null) as IEnumerable)
addProperty(prop.Name, val.ToString());
}
else
{
if (!string.IsNullOrEmpty(simplevalue.ToString()))
addProperty(prop.Name, simplevalue.ToString());
}
}
}
return sb.ToString();
}
This function will build a full path to your route and append the values in the additionalParams object as query string data. This can handle arrays, enums, nullable values, and other types that by executing their ToString method.
Hope this helps!

Dynamic Order (SQL ORDERBY) in LINQ CompiledQuery

how can I create a dynamic ORDERBY in my LINQ CompiledQuery (e.g. supply Order Field and Direction as parameters for the compiled query)?
I would do it this way, first all you really need is a way to access the property value by string on an object. You could use reflection, but its slow. So use this helper class approach which is based on the tests of http://stefan.rusek.org/Posts/LINQ-Expressions-as-Fast-Reflection-Invoke/3/
public static class LINQHelper
{
public static IComparable OrderByProperty<TClass>(TClass item,
string propertyName)
{
var t = Expression.Parameter(typeof(TClass), "t");
var prop = Expression.Property(t, propertyName);
var exp = Expression.Lambda(prop, t).Compile();
return (IComparable)exp.DynamicInvoke(item);
}
}
The in your code where you want your order by string of property name, in this example col1, you just do the following.
var myQuery = from i in Items
select i;
myQuery.OrderBy(i=>LINQHelper.OrderByProperty(i,"col1"));
Hope this helps.
I think I found it:
Check out this link. It will point you to the VS2008 code samples which contains a Dynamic Linq Query Library which contains the extension method below. This will allow you to go:
Object.OrderBy("ColumnName");
Here is the extension methods, but you may want the whole library.
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) {
return (IQueryable<T>)OrderBy((IQueryable)source, ordering, values);
}
public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) {
if (source == null) throw new ArgumentNullException("source");
if (ordering == null) throw new ArgumentNullException("ordering");
ParameterExpression[] parameters = new ParameterExpression[] {
Expression.Parameter(source.ElementType, "") };
ExpressionParser parser = new ExpressionParser(parameters, ordering, values);
IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering();
Expression queryExpr = source.Expression;
string methodAsc = "OrderBy";
string methodDesc = "OrderByDescending";
foreach (DynamicOrdering o in orderings) {
queryExpr = Expression.Call(
typeof(Queryable), o.Ascending ? methodAsc : methodDesc,
new Type[] { source.ElementType, o.Selector.Type },
queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters)));
methodAsc = "ThenBy";
methodDesc = "ThenByDescending";
}
return source.Provider.CreateQuery(queryExpr);
}

Resources