I'm having some trouble with the following. I'm a beginner, which is probably why.
I have a listbox that displays some pictures, it gets the paths of these pictures from an XML file. This XML file is defined as a resource in XAML. If a picture is selected and the user presses enter, I want to launch an external app with some parameters, including a path found in another node of that XML file (appath in the example below).
XML layout:
<picture>
<path></path>
<appath></appath>
</picture>
I can't seem to find the way to access the node from C#.
Any pointers greatly appreciated!
Thanks in advance,
J.
If you don't have any attributes in the picture node (an id of some sort) you, have to first match up on the path which you should already have in your listbox, then return the appath.
static string GetAppath(string xmlString, string picPath)
{
string appath = String.Empty;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlString);
XmlNodeList xList = xDoc.SelectNodes("/picture");
foreach (XmlNode xNode in xList)
{
if (xNode["path"].InnerText == picPath)
{
appath = xNode["appath"].InnerText;
break;
}
}
return appath;
}
Assuming your xml file looks something like:
<?xml version="1.0" encoding="ISO-8859-1"?>
<pictures>
<picture>
<path></path>
<appath></appath>
</picture>
</pictures>
If your resource name is Pictures:
XElement resource = XElement.Parse(Properties.Resources.Pictures);
Using these extensions: (just copy the class/file into your root directory of your project) http://searisen.com/xmllib/extensions.wiki
public class PicturesResource
{
XElement self;
public PicturesResource()
{ self = XElement.Parse(Properties.Resources.Pictures); }
public IEnumerable<Picture> Pictures
{ get { return self.GetEnumerable("picture", x => new Picture(x)); } }
}
public class Picture
{
XElement self;
public Pictures(XElement self) { this.self = self; }
public string Path { get { return self.Get("path", string.Empty); } }
public string AppPath { get { return self.Get("apppath", string.Empty); } }
}
You could then bind the Pictures or do a look up on them:
PicturesResource pictures = new PicturesResource();
foreach(Picture pic in pictures.Pictures)
{
string path = pic.Path;
string apppath = pic.AppPath;
}
Or searching for a particular picture:
Picture pic = pictures.FirstOrDefault(p => p.Path = "some path");
if(pic != null)
{
// do something with pic
}
Related
I'm trying to list the content of a folder in SharePoint 2010 by using its web service.
This is what I have so far, tell me if I'm over complicating this if so.
XNamespace z = "#RowsetSchema";
string lId = this.GetListID("Account");
string vId = this.GetViewID("All Documents", lId);
//this below, works, I'm getting the unique ID of folder...
string folderId = this.GetListData(lId, vId).Descendants(z + "row").
Where(x => x.Attribute("ows_LinkFilename").Value.Equals("FolderName")).
Select(x => x.Attribute("ows_UniqueId").Value).SingleOrDefault().ToString();
private string GetListID(string listName)
{
string listID;
try
{
XDocument doc = XDocument.Parse(_listClient.GetListCollection().ToString());
listID = (from x in doc.Elements().First().Elements()
where x.Attribute("Title").Value.Equals(listName)
select x.Attribute("ID").Value).FirstOrDefault();
}
catch
{
throw;
}
return listID;
}
private string GetViewID(string viewName, string listID)
{
string viewID = null;
try
{
XDocument doc = XDocument.Parse(_viewClient.GetViewCollection(listID).ToString());
viewID = (from x in doc.Elements().First().Elements()
where x.Attribute("DisplayName").Value.Equals(viewName)
select x.Attribute("Name").Value).FirstOrDefault();
}
catch
{
throw;
}
return viewID;
}
private XDocument GetListData(string listID, string viewID)
{
XDocument list_data = null;
try
{
list_data = XDocument.Parse(_listClient.GetListItems(listID, viewID, null, null, "10000", null, null).ToString());
var q = (from x in list_data.Elements().First().Elements().First().Elements()
select new
{
Title = x.Attribute("ows_LinkTitle").Value,
Field1 = x.Attribute("ows_Field1").Value,
Field2 = x.Attribute("ows_Field2").Value
});
}
catch
{
throw;
}
return list_data;
}
As you can see, I'm able to get the unique ID of the folder in question. But then what? Is there any other SharePoint web service I need to use with the folder ID to get its contents ?
Here is an example of the structure of the URL for which I'm trying to get the contents of:
https://spsite.domain.ca/testenv/account/000001
The code above retrieves me the unique ID for the folder 000001 but then I'm stuck there... I don't see any GetFolderItems or something like that in lists.asmx or other SP web services.
I saw some examples out there but they use the assembly Microsoft.Sharepoint.dll to do so, which I'm trying to avoid.
Thank you!
I will be using Microsoft.Sharepoint.Client for this. I had no idea SP2010+ offered such a feature.
I am building a project and I need to make it very customizable. I am trying to build it to support 4 languages. And the user will have an admin panel where he/she can change a label's text or a button's text. I want the user to go to that admin panel and change a button's text without calling me :)
I have used old but good style of localization which is .resx files. I have sample code below.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString().Equals("en-GB"))
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
label1.Text= FormLabels.test1;
label2.Text = FormLabels.test2;
}
else if (comboBox1.SelectedItem.ToString().Equals("de-DE"))
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
label1.Text = FormLabels.test1;
label2.Text = FormLabels.test2;
}
}
If I let user to change a button's text in "FormLabels.en-GB.resx" file. the project must be recompiled to see the changes.
I need to find a solution where the user can change the button's text with recompiling. how can I do that?
The only thing I can think about it to have the localization in external files.
Create a xml file like:
ex: languagesSupported.xml
<Languages>
<language name="English" file="en.dat" />
<language name="French" file="fr.dat" />
<language name="Japanese" file="jp.dat" />
</Languages>
Like this you can actually add more languages later on.
Now in each file you will need to do something like:
(ex: en.dat)
<Language name="English">
<Localized name="hello" value="Hello">
<Localized name="goodbye" value="Goodbye">
</Language>
(ex: fr.dat)
<Language name="French">
<Localized name="hello" value="Bonjour">
<Localized name="goodbye" value="Au revoir">
</Language>
In your code you would do something like that:
private Dictionary<string, Dictionary<string, string>> _localizations = new Dictionary<string, Dictionary<string, string>>();
private string _currentLocalization = "English";
private bool LoadLocalizations()
{
try
{
if (File.Exists("languagesSupported.xml") == false)
{
return false;
}
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load("languagesSupported.xml");
XmlNodeList nodeList = xmldoc.SelectNodes("languages/language");
if (nodeList.Count > 0)
{
foreach (XmlNode node in nodeList)
{
LoadLocalization(node.Attributes["name"].Value, node.Attributes["file"].Value);
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private bool LoadLocalization(string pLang, string pFile)
{
try
{
if (File.Exists(pFile) == false)
{
return false;
}
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(pFile);
XmlNodeList nodeList = xmldoc.SelectNodes("language/localized");
_localizations.Add(pLang, new Dictionary<string,string>());
if (nodeList.Count > 0)
{
foreach (XmlNode node in nodeList)
{
_localizations[pLang].Add(node.Attributes["name"].Value, node.Attributes["value"].Value);
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private void SetLocalization()
{
labelHello.text = _localizations[_currentLocalization]["hello"];
labelGoodbye.text = _localizations[_currentLocalization]["goodbye"];
}
After that, each time your user changes the language, you simply update _currentLocalization and call SetLocalization();
You can even populate your dropdownlist of language using the keys from _localizations.
That way you make the localization completely dynamic.
If you really want to use the CultureInfo, simply map the culture to the language name.
The ResourceManager only works with embeded resources.
You would have to write the ResourceManager yourself.
You could use the ResXResouceSet (http://msdn.microsoft.com/en-us/library/system.resources.resxresourceset.aspx) and then write your own ResourceManager around it.
It's not that hard to do.
You could then read the resx files and prepend the culture before the resx extension yourself.
Good luck
Could someone tell me how to parse a XML-String that i receive from a wcf-rest service?
my webserive XML-String looks like
<WS>
<Info>
<Name>Beta</Name>
<Description>Prototyps</Description>
</Info>
<Pages>
<Page>
<Name>Custom</Name>
<Description>toDo</Description>
</Page>
...many other pages...
</Pages>
</WS>
an my phone sourcecode:
public void DownloadCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
var answer = XElement.Parse(e.Result).Descendants("WS"); // null
...
}
}
if i try to parse it through XDocument.Load(e.Result) then i get the exception: File not Found.
i just want the "unique" information of the Info-Node and a list of all Page-Nodes with their values
Update
Even if i try to load the Root-Element via var item = xdoc.Root.Descendants(); item will be assigned to the whole xml-file.
Update 2 it seems the problem occurs with the namespaces in the root-element. with namespaces xdocument will parse the webservice output not correctly. if i delete the namespaces it works fine. could someone explain me this issue? and is there a handy solution for deleting all namespaces?
update 3 A Handy way for removing namespaces1
With really simple XML if you know the format wont change, you might be interested in using XPath:
var xdoc = XDocument.Parse(e.Result);
var name = xdoc.XPathSelectElement("/WS/Info/Name");
but for the multiple pages, maybe some linq to xml
var xdoc = XDocument.Parse(xml);
var pages = xdoc.Descendants("Pages").Single();
var PagesList = pages.Elements().Select(x => new Page((string)x.Element("Name"), (string)x.Element("Description"))).ToList();
Where Page is a simple class:
public class Page
{
public string Name { get; set; }
public string Descrip { get; set; }
public Page(string name, string descrip)
{
Name = name;
Descrip = descrip;
}
}
Let me know if you need more explanation.
Also to select the Info without XPath:
var info = xdoc.Descendants("Info").Single();
var InfoName = info.Element("Name").Value;
var InfoDescrip = info.Element("Description").Value;
Viktor - XDocument.Load(string) attempts to load an XDocument by the supplied filename, not a string representation of an XML element.
You say var answer = XElement.Parse(e.Result).Descendants("WS"); // null, but which part is null? The parsed XElement or the attempt to grab a descendant? If <WS>...</WS> is your root element, would the .Descendents("WS") call return the root element? Based on the documentation for XElement.DescendantsAndSelf(), I'm guessing not. Have you instead tried calling:
var answer = XElement.Parse(e.Result).Descendants("Info");
A quick test on my end showed that, with WS as the root element, calling XElement.Parse(e.Result).Descendants("WS"); yielded no results, while XElement.Parse(e.Result).Descendants("Info"); yielded the <Info>...</Info> element.
I have a Xml file with values for the dropdown.I want to provide the path in Web.config and bind the values to drop down from web.config.
Firstly to read the location from web.config use System.Configuration class, something like the following should work
string filePath = ConfigurationManager.AppSettings["FilePath"];
to access a file on the server use Server.MapPath e.g.
Server.MapPath(filepath);
to bind an xml file to the dropdown you could use the following, there are easier ways but this will allow for any other manipulation you need to do
1: Get the list of items
public static List<string> GetFamiliesList()
{
List<string> families = new List<string>();
try
{
using (StreamReader streamreader = new StreamReader(Server.MapPath(filepath)))
{
XElement xe = XElement.Load(streamreader);
foreach (XElement children in xe.Elements("Family"))
{
families.Add(children.Attribute("Name").Value);
}
}
}
catch
{
}
return families;
}
2: bind to dropdown
dropdownList.DataSource = GetFamiliesList();
Okay so, I have read that .INI files have become obsolete now and the .NET Framework creators want us to use .XML files. However, I feel that it would be difficult for some of my users to use .XML files so I thought of creating a custom config file.
I have a list string which has 3 parameters (it is actually the snippet function in Scintilla), like this:
Snippet.Insert("Name", "Code", 'char');
Now I want to insert all snippets from a files which the user can add himself, including the name, code and character but I have no clue about how I would do this. Maybe something like:
[Snippet1] [Snippet1Code] [Snippet1Char]
[Snippet2] [Snippet2Code] [Snippet2Char]
[Snippet3] [Snippet3Code] [Snippet3Char]
However I don't know how I would read the values that way. If someone can tell me an efficient way to read snippets from a file I would be really grateful.
As others have suggested, and similar to #gmcalab's approach, here is a quick example using Linq To XML.
public class Snippet
{
public string Name { get; set; }
public string Code { get; set; }
public char Character { get; set; }
}
XDocument doc = XDocument.Parse(#"<snippets>
<snippet name='snippet1' character='a'>
<![CDATA[
// Code goes here
]]>
</snippet>
<snippet name='snippet2' character='b'>
<![CDATA[
// Code goes here
]]>
</snippet>
</snippets>");
List<Snippet> snippetsList = (from snippets in doc.Descendants("snippet")
select new Snippet
{
Name = snippets.Attribute("name").Value,
Character = Convert.ToChar(snippets.Attribute("character").Value),
Code = snippets.Value
}).ToList();
snippetsList.ForEach(s => Console.WriteLine(s.Code));
If you prefer ini files, I've read good things about Nini
Why not just set up your snippets in the xml you talked about then read it with XMLTextReader?
Pretty straight forward...
<snippets>
<snippet name="Name1" char="a">
<snippetCode>
for(int i = 0; i < 10; i++) { // do work }
</snippetCode>
</snippet>
<snippet name="Name2" char="b">
<snippetCode>
foreach(var item in items) { // do work }
</snippetCode>
</snippet>
</snippets>
C#
public class Snippet
{
public string Name {get;set;}
public char Char { get; set;}
public string Value { get; set;}
}
List<Snippet> Snippets = new List<Snippet>();
XmlTextReader reader = new XmlTextReader ("snippets.xml");
Snippet snippet = new Snippet();
while (reader.Read())
{
// Do some work here on the data.
switch (reader.NodeType)
{
case XmlNodeType.Element:
if(reader.Name == "snippet"){
while (reader.MoveToNextAttribute())
{
if(reader.Name == "Name"){
// get name attribute value
snippet.Name = reader.Value;
}
else if(reader.Name == "Char"){
// get char attribute value
snippet.Char = Char.Parse(reader.Value);
}
}
}
break;
case XmlNodeType.Text: //Display the text in each element.
//Here we get the actual snippet code
snippet.Value = reader.Value;
break;
case XmlNodeType. EndElement:
if(reader.Name == "snippet"){
// Add snippet to list
Snippets.Add(snippet);
// Create a new Snippet object
snippet = new Snippet();
}
break;
}
}