best way to handle conditional statement - c#

I have the following condition using in my code but that doesn't look very efficient,is this any better way to handle ?
if (ic = filename.Contains(".wmv"))
{
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
}
if (ic = filename.Contains(".wmv"))
{
if (bitnumber < 400)
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
}
if (ic = filename.Contains(".m4v"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mp4"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".flv"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mpg"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".aac"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mp3"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}

Break it up in other classes like:
public class AudioFileValidator
{
private List<string> _extensions = new List<string>{".aac", ".mp3"};
public bool IsValid(string filename)
{
if (!_extensions.Contains(Path.GetExtension(filename))
return false;
//validate bitrate etc
}
}
Usage:
var audioValidator = new AudioFileValidator();
if (audioValidator.IsValid(filename))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
var videoValidator = new VideoFileValidator();
if (videoValidator.IsValid(filename))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
By doing so you'll get classes with a single responsibility which can be reused in other places and which are easy to unit test.
You could even take it further and introduce a new interface called IMediaFileValidator which all validators implement. and do something like:
foreach (var validator in validators)
{
if (validator.IsValid(filename))
{
// use info from the validator to build the path
var mediaName = validator.MediaName;
path = "ftp://" + ftpServerIP + "/" + mediaName + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
break;
}
}
Which would also make your code adhere to Open/Closed principle.

You will need a lot of refactoring. Here are couple of ideas to get you started:
Use String.Format and passed in only value that changed to save you all the repeating the text
Build a dictionary of Extension/Ext-Combination key and set the value to the the destination path. You will then only require one lookup than big nesting if - else statements
Use Path.GetExtension rather than Contains to be more accurate
Eg.
string formatStringNews = "ftp://{0}/news/{1}/";
string formatStringMedia = "ftp://{0}/media/{1}/";
dictionary["wmv"] = formatStringMedia;
dictionary["mp3"] = formatStringNews;
....
string key = Path.GetExtension(filename);
path = string.Format(dictionary[key], serverName, programName);

Something like this is a nice short solution to your problem and I believe it handles all of the cases your if statements are handling.
String[] videoExtensions = { "wmv", "m4v", "mp4", "flv" };
String[] audioExtensions = { "aac", "mp3" };
String ext = Path.GetExtension(filename).ToLower();
String path = "ftp://" + ftpServerIP + "/";
if (-1 != Array.IndexOf(videoExtensions, ext)) {
if ("wmv".equals(ext) && bitnumber > 400)
path += "media/lib/" + programName + "/" + date + "/";
else
path += "mpegmedia/news/" + programName + "/video/podcast/";
}
else if (-1 != Array.IndexOf(audioExtensions, ext)) {
path += "mpegmedia/news/" + programName + "/audio/podcast/";
}​​​​​​​​​​​
else {
// handle unknown extension types as desired
}
UploadCondition(path, filename);

Use a switch statement and System.IO.Path.GetExtension.
select (System.IO.Path.GetExtension(filename))
{
case ".wmv":
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
else
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
break;
case ".m4v":
case ".mp4":
case ".flv":
case ".mpg":
case ".mp3":
default:
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
break;
}
}
I'm guessing you'll want variations for the last block, but this should be easy enough to modify.

At the very least you could convert it into an if/elseif statement:
if (ic....)
{
...
} else if (ic...) {
...
}

I assume, at a time your filename will be either be .m4v, .flv,.mp4 etc...so here goes the code..
if (ic = filename.Contains(".wmv"))
{
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
else
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
}
else if (ic = filename.Contains(".m4v"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mp4"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".flv"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mpg"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".aac"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mp3"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else
{
//No Match found
}
and the best approach would be to use Switch(fileExtn)

You could perhaps make it a bit simpler like
if (filename.Contains(".wmv"))
// path = set the path as you require
and after all the ifs end call your method
UploadCondition(path, filename);
Better would be to extract the extension .wmv, .m4v from filename and make this into a switch whereby you set the path.

Related

How to archive file from folder using ZipFile c#

I have to take a file from a folder and make a archive in another folder.
I use this code but get an error:
************** Exception Text **************
System.IO.IOException: The directory name is invalid.
I use this code:
private void button1_Click(object sender, EventArgs e)
{
string Info = "";
string startPath = #"D:\dosfiles\SYNOPD\SYNOPD$$.PD\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\" + station;
string zipPath = #"D:\dosfiles\SYNOPD\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "_" + comboBox3.SelectedItem.ToString() + ".zip";
if (File.Exists(zipPath))
{
File.Delete(zipPath);
ZipFile.CreateFromDirectory(startPath, zipPath);
Info += "Вашият архив е създаден в папка D:\\dosfiles\\SYNOPD\\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "." + comboBox3.SelectedItem.ToString() + ".zip" + Environment.NewLine;
}
else
{
ZipFile.CreateFromDirectory(startPath, zipPath);
Info += "Вашият архив е създаден в папка D:\\dosfiles\\SYNOPD\\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "." + comboBox3.SelectedItem.ToString() + ".zip" + Environment.NewLine;
}
this.Hide();
Form1 frm = new Form1();
frm.Show();
}

how to make objects using an index number

I want to make my program that i made way shorter then it is right now.
I make 8 different objects and do things with them but I want to make it with something like a for loop and an index number.
Is there a way to do this, because i've looked it up but don't seem to find anything.
The objects and such are in Dutch sorry for that.
private void AankomstButton_Click(object sender, EventArgs e)
{
if (welkKind == 1)
{
if (File.Exists(#"Bestanden/" + kind1.Naam + "_" + DateTime.Now.ToString("Y") + ".txt") == false)
{
using (StreamWriter sw = new StreamWriter(#"Bestanden/" + kind2.Naam + "_" + DateTime.Now.ToString("Y") + ".txt")) ;
}
else
{
using (StreamWriter sw = File.AppendText(#"Bestanden/" + kind2.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
}
if (welkKind == 2)
{
if (File.Exists(#"Bestanden/" + kind2.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
using (StreamWriter sw = File.AppendText(#"Bestanden/" + kind2.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
else
{
using (StreamWriter sw = new StreamWriter(#"Bestanden/" + kind2.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
}
if (welkKind == 3)
{
if (File.Exists(#"Bestanden/" + kind3.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
using (StreamWriter sw = File.AppendText(#"Bestanden/" + kind3.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
else
{
using (StreamWriter sw = new StreamWriter(#"Bestanden/" + kind3.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
}
if (welkKind == 4)
{
if (File.Exists(#"Bestanden/" + kind4.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
using (StreamWriter sw = File.AppendText(#"Bestanden/" + kind4.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
else
{
using (StreamWriter sw = new StreamWriter(#"Bestanden/" + kind4.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
}
if (welkKind == 5)
{
if (File.Exists(#"Bestanden/" + kind5.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
using (StreamWriter sw = File.AppendText(#"Bestanden/" + kind5.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
else
{
using (StreamWriter sw = new StreamWriter(#"Bestanden/" + kind5.Naam + "_" + DateTime.Now.ToString("Y") + ".txt"))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
}
If you keep an array of children (kind), you can access the array by index.
Kind[] children = new Kind[] { kind1, kind2 };
if (welkKind >= 0 && welkKind < children.Length)
{
Kind kind = children[welkKind];
string fileName = #"Bestanden/" + kind.Naam + "_" + DateTime.Now.ToString("Y") + ".txt";
if (File.Exists(fileName))
{
using (StreamWriter sw = new StreamWriter(fileName))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
else
{
using (StreamWriter sw = File.AppendText(fileName))
{
sw.WriteLine(DateTime.Now.ToString("d") + " Aangekomen: " + DateTime.Now.ToString("t"));
}
}
}
Another option would be a list, which would have similar syntax in its usage, but you can dynamically add and remove items from the list:
List<Kind> children = new List<Kind>();
children.Add(kind1);
children.Add(kind2);
children.Add(new Kind() { Naam = "John" });
if (welkKind >= 0 && welkKind < children.Count)
{
Kind kind = children[welkKind];
}

how to know whether compatibility is on or off using asp.net(c#)

I have to do if user's browser compatibility is on then need to show message to user that your browser's compatibility is on.
I have searched this a lot on google but yet not found a proper answer.
I have tried below code but HttpContext.Current.Request.UserAgent always contains MSIE 7.0
string isOn = string.Empty;
if (HttpContext.Current.Request.UserAgent.IndexOf("MSIE 7.0") > -1)
{
isOn = "IE8 Compatibility View";`
}
else
{
isOn = "IE8";
}
}
You may try like this
if (Request.Browser.Type.ToUpper().Contains("IE"))
{
if (Request.Browser.MajorVersion < 7)
{
//Show the message here
}
...
}
else if (Request.Browser.Type.Contains("Firefox"))
{
//code to show message
}
else if (Request.Browser.Type.Contains("Chrome"))
{
//code to show message
}
Also check this MSDN which has its own way of detecting the browser
Query the Browser property, which contains an HttpBrowserCapabilities
object. This object gets information from the browser or client device
during an HTTP request, telling your application the type and level of
support the browser or client device offers. The object in turn
exposes information about browser capabilities using strongly typed
properties and a generic name-value dictionary.
private void Button1_Click(object sender, System.EventArgs e)
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n"
+ "Supports JavaScript Version = " +
browser["JavaScriptVersion"] + "\n";
TextBox1.Text = s;
}

GitHub API update file

I'm trying to update a file via the GitHub API.
I've got everything setup, and in the end the actual file is updated, which is a good thing.
However, let's say I've got these 2 files in my repo
FileToBeUpdated.txt
README.md
And then I run my program
The FileToBeUpdated.txt is updated, like it should, however the README.md is deleted.
This is the code with the 5 steps to update the file:
private static void Main()
{
string shaForLatestCommit = GetSHAForLatestCommit();
string shaBaseTree = GetShaBaseTree(shaForLatestCommit);
string shaNewTree = CreateTree(shaBaseTree);
string shaNewCommit = CreateCommit(shaForLatestCommit, shaNewTree);
SetHeadPointer(shaNewCommit);
}
private static void SetHeadPointer(string shaNewCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"sha\":" + "\"" + shaNewCommit + "\", " +
// "\"force\":" + "\"true\"" +
"}";
// TODO validate ?
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "refs/heads/master", "PATCH", contents);
}
private static string CreateCommit(string latestCommit, string shaNewTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"parents\" :[ \"" + latestCommit + "\" ], " +
"\"tree\":" + "\"" + shaNewTree + "\", " +
"\"message\":" + "\"test\", " +
"\"author\": { \"name\": \""+ Constants.Username +"\", \"email\": \""+ Constants.Email+"\",\"date\": \"" + DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "\"}" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "commits", contents);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.sha;
}
private static string CreateTree(string shaBaseTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"tree\" :" +
"[ {" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "trees", contents);
var foo = JsonConvert.DeserializeObject<TreeRootObject>(downloadString);
return foo.sha;
}
private static string GetShaBaseTree(string latestCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "commits/" + latestCommit);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.tree.sha;
}
private static string GetSHAForLatestCommit()
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "refs/heads/master");
var foo = JsonConvert.DeserializeObject<HeadRootObject>(downloadString);
return foo.#object.sha;
}
private static WebClient GetMeAFreshWebClient()
{
var webClient = new WebClient();
webClient.Headers.Add(string.Format("Authorization: token {0}", Constants.OAuthToken));
return webClient;
}
Which part am I missing? Am I using the wrong tree to start from?
It seems that in the function CreateTree I should set the base_tree at the root level, not at the level of each tree I create.
So in the function CreateTree the contents become this:
string contents = "{" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," + // IT'S THIS LINE!
"\"tree\" :" +
"[ {" +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
Updated GitHub documentation: https://github.com/Snakiej/developer.github.com/commit/2c4f93003703f68c4c8a436df8cf18e615e293c7

WCF Data Services | How to handle nullable property with nested properties?

When I have changed BarCodeId FK to allows null in ContactDocument. After that I start get errors in client if any entities in ContactDocument has null BarCodeId. If I remove the last three expands all will be work, but I will not get entities related to BarCode object. Any Help?
IQueryable<ScanDocument> result = Context.CreateQuery<ScanDocument>("DocumnetsWithNotRemovedContacts")
.Expand(ScanDocument.ScanDocumentDetailsPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ScanDocumentPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.BarCodePropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.ContactDocumentsPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ScanDocumentDetailPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.ContactSourcePropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.ElectionDistrictPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.ContactTypePropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.ContactSalutationPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.ContactGroupsPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.ContactPropertyName + "/" + Contact.CategoryInterestsPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.BarCodePropertyName + "/" + BarCode.ContactDocumentsPropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.BarCodePropertyName + "/" + BarCode.BarCodeActionTypePropertyName)
.Expand(ScanDocument.ScanDocumentDetailsPropertyName + "/" + ScanDocumentDetail.ContactDocumentsPropertyName + "/" + ContactDocument.BarCodePropertyName + "/" + BarCode.ScanDataTypePropertyName)
.OrderByDescending(document => document.ID);
on the server side I started to use something like this to get nested properties.
CurrentDataSource.ScanDocumentDetails
.Include(ScanDocumentDetail.ScanDocumentPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.BarCodePropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.ContactDocumentsPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ScanDocumentDetailPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.ContactSourcePropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.ElectionDistrictPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.ContactTypePropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.ContactSalutationPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.ContactGroupsPropertyName)
.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.ContactPropertyName + "." + Contact.CategoryInterestsPropertyName)
//.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.BarCodePropertyName + "." + BarCode.ContactDocumentsPropertyName)
//.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.BarCodePropertyName + "." + BarCode.BarCodeActionTypePropertyName)
//.Include(ScanDocumentDetail.ContactDocumentsPropertyName + "." + ContactDocument.BarCodePropertyName + "." + BarCode.ScanDataTypePropertyName)
.Where(c => ids.Contains(c.ScanDocumentID ?? 0)).ToList();
foreach (var scanDocumentDetail in y)
{
foreach (var contactdocuments in scanDocumentDetail.ContactDocuments)
{
if (contactdocuments.BarCode != null)
{
int barCodeActionTypeId = contactdocuments.BarCode.BarCodeActionTypeId;
contactdocuments.BarCode.BarCodeActionType =
CurrentDataSource.BarCodeActionTypes.FirstOrDefault(p => p.ID == barCodeActionTypeId);
if (contactdocuments.BarCode.ScanDataTypeID.HasValue)
{
int scanDataTypeId = contactdocuments.BarCode.ScanDataTypeID.Value;
contactdocuments.BarCode.ScanDataType =
CurrentDataSource.ScanDataTypes.FirstOrDefault(p => p.ID == scanDataTypeId);
}
}
}
}
UPD
exception:
"Error processing response stream. Server failed with following message:\r\nAn error occurred while processing this request."
Source:System.Data.Services.Client
Status Code:500
StackTrace:
at System.Data.Services.Client.Xml.XmlAtomErrorReader.Read()
at System.Xml.XmlSubtreeReader.Read()
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XElement.ReadElementFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XElement.Load(XmlReader reader, LoadOptions options)
at System.Data.Services.Client.AtomParser.XElementBuilderCallback(XmlReader reader)
at System.Data.Services.Client.AtomParser.ParseCurrentEntry(AtomEntry& targetEntry)
at System.Data.Services.Client.AtomParser.Read()
at System.Data.Services.Client.AtomMaterializer.Read()
at System.Data.Services.Client.MaterializeAtom.MoveNextInternal()
at System.Data.Services.Client.MaterializeAtom.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ClientDataServices.MailProcessingManagmentService.GetDocuments(Expression`1 filter) in D:\...\MailProcessingManagmentService.cs:line 41
at ClientDataServices.MailProcessingManager.GetEntries(Expression`1 predicate) in D:\...\MailProcessingManager.cs:line 24
at MailProcessingModule.ViewModels.MailProcessingViewModel.RefreshEntityHandler() in D:\...\MailProcessingViewModel.cs:line 113
at BaseModule.BaseGridViewModel`1.<>c__DisplayClass1a.<ListEntities>b__d(Object e) in D:\...\BaseGridViewModel.cs:line 178
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
WCF Data Services has a server side limit on the number of expansions allowed. I think it's 14, so your query above will probably fail.
If you would place post the exact error message you get it might help to confirm the root cause of the problem.
Expanding properties which are null should work just fine, there won't be any results but that's to be expected.

Categories