Read XML files in deployed app to Windows Store - c#

I have a simple service which let me read XML file.
public class SetService : ISetService
{
private const string FilesPath = "Data/Sets.xml";
private string xmlPath = Path.Combine(Package.Current.InstalledLocation.Path, FilesPath);
public async Task<IList<Set>> GetAll()
{
XDocument loadedData = XDocument.Load(xmlPath);
var data = from query in loadedData.Descendants("set")
select new Set
{
Id = (int)query.Element("id"),
Name = (string)query.Element("name"),
IsActive = (bool)query.Element("isactive"),
IsPassed = (bool)query.Element("ispassed"),
};
return (IList<Set>)data.ToList();
}
}
Everything works fine when I am using this method, on my local machine or on emulator provided with Microsoft Visual Studio 2013 but after I published this app to the Windows Store I am not able to see these data from XML files.
What am I doing wrong?

Related

Using XML document as DataSource for DataTable

I have a program which gets data from a database and uses that information to create a XML document.
The program works as intended, but there are issues when the program is used during the nightshift, as the database is usually under maintenance, so the program stops working as intended.
What I want to achieve here is, when the program cant connect to the database, to use a XML document (created with the same data as the database), so the program can work properly during the maintenance periods, basically, using a XML document to create another XML
Here is how the program is connected to the database:
namespace Cotas.Class
{
public class CData
{
static string S_Connection = "ConnectionString";
public static BDMINIAPPS.SP_MINIAPPS SPMINIAPPS = new BDMINIAPPS.SP_MINIAPPS(S_Connection);
public static BDMINIAPPS.D_CGeometricas CCGeometricos = new BDMINIAPPS.D_CGeometricas(S_Connection);
public static BDMINIAPPS.D_CGParametros CCGParametros = new BDMINIAPPS.D_CGParametros(S_Connection);
}
}
Method
private void LoadConfiguration()
{
DataTable DTCGeometricas = CData.SPMINIAPPS.SP_GetCGeometricas();
D_Tolerancia = decimal.Parse(CData.CCGParametros.SelectCGParametros("Tolerancia").Parametro);
S_Descripcion = CData.CCGParametros.SelectCGParametros("Descripcion").Parametro;
S_Encoding = CData.CCGParametros.SelectCGParametros("Encoding").Parametro;
S_PathOrigen = CData.CCGParametros.SelectCGParametros("PathOrigen").Parametro;
S_PathDestino = CData.CCGParametros.SelectCGParametros("PathDestino").Parametro;
S_PathProcesados = CData.CCGParametros.SelectCGParametros("PathProcesados").Parametro;
S_PathErrores = CData.CCGParametros.SelectCGParametros("PathErrores").Parametro;
S_ArchivoLOGs = CData.CCGParametros.SelectCGParametros("ArchivoLOGs").Parametro;
S_Operacion = CData.CCGParametros.SelectCGParametros("Operacion").Parametro;
foreach (DataRow DRCGeometrica in DTCGeometricas.Rows)
L_CGeometricas.Add(DRCGeometrica["CGeometrica"].ToString());
}
And this is the command I used to export the data from the Database to a XML document
SELECT ( SELECT * From CGeometricas
FOR
XML PATH('Row'), ROOT('CGeometricas'),
TYPE),
(SELECT * From CGParametros
FOR
XML PATH('Row'), ROOT('CGParametros'),
TYPE)
FOR XML PATH('') ,
ROOT('Root')

How can I get the BPM property of an MP3 file in a Windows Forms App

I am trying to get the BPM property from an MP3 file:
I can see how to do this in a Windows Store App as per this question:
How to read Beats-per-minute tag of mp3 file in windows store apps C#?
but can't see how to use Windows.Storage in a Windows Forms app. (If I understand it correctly it's because Windows.Storage is specific to UWP.)
How can I read this in a Forms app? Happy to use a (hopefully free) library if there is nothing native.
You can use Windows' Scriptable Shell Objects for that.
The item object has an ShellFolderItem.ExtendedProperty method
The property you're after is an official Windows property named System.Music.BeatsPerMinute
So, here is how you can use it (you don't need to reference anything, thanks to the cool dynamic C# syntax for COM objects):
static void Main(string[] args)
{
string path = #"C:\path\kilroy_was_here.mp3";
// instantiate the Application object
dynamic shell = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
// get the folder and the child
var folder = shell.NameSpace(Path.GetDirectoryName(path));
var item = folder.ParseName(Path.GetFileName(path));
// get the item's property by it's canonical name. doc says it's a string
string bpm = item.ExtendedProperty("System.Music.BeatsPerMinute");
Console.WriteLine(bpm);
}
There is a version TagLib that was ported to a portable class library (PCL) version that can be referenced by a Windows Forms and used to extract that information.
I referenced the PCL version TagLib#.Portable which is available via Nuget at TagLib.Portable
From there is was a simple matter of opening the file and reading the desired information.
class Example {
public void GetFile(string path) {
var fileInfo = new FileInfo(path);
Stream stream = fileInfo.Open(FileMode.Open);
var abstraction = new TagLib.StreamFileAbstraction(fileInfo.Name, stream, stream);
var file = TagLib.File.Create(abstraction);//used to extrack track metadata
var tag = file.Tag;
var beatsPerMinute = tag.BeatsPerMinute; //<--
//get other metadata about file
var title = tag.Title;
var album = tag.Album;
var genre = tag.JoinedGenres;
var artists = tag.JoinedPerformers;
var year = (int)tag.Year;
var tagTypes = file.TagTypes;
var properties = file.Properties;
var pictures = tag.Pictures; //Album art
var length = properties.Duration.TotalMilliseconds;
var bitrate = properties.AudioBitrate;
var samplerate = properties.AudioSampleRate;
}
}

Save data in a Visual Studio WPF aplication without a database

I'm developing a WPF app using C#.
The first thing my app does is trying to connect to the database, so I ask for some data to connect to the database like the name of the server (could be the IP too), the name of the database, the name of MySQL instance user and password, and the port (3306 for default). But I want to save this info in the app because I don't have the database yet to save there.
I want to save this strings in the application without using a database:
Computer Name
Name of the database backup
MySql Instance User
MySql Instance Pass
Port
I don't want to save this data in the database because I need this info for the first use of the application.
With first use I mean before the database backup is even restored to the server from the installer.
You can save file with registry. Try this :
Microsoft.Win32.RegistryKey RegistryKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("WPF APPLICATION");
RegistryKey.SetValue(SET THE VALUE);
RegistryKey.Close();
best practice is to store these values in configuration file. like a .ini file or xml file.
if your data is sensitive and you don't wish to see this details directly you can encrypt this data with any convenient encryption method.
so your ini file structure will look like this,
[port]=3306
[ip]=111.222.1.2
hope this will help.
Try using the app.Config.
The main benefit of the app.config is that It's directly attached to your executable. Once you build your solution, the app.config gets copied together with the executable.
From What is App.config in C#.NET? How to use it?:
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Source for app.config in msdn: How to: Add an Application Configuration File to a C# Project
.NET Applications are compiled with a .config file like "YourApp.exe.config" next to the .exe.
This file should be used for such purposes, and can be accessed in code with the ConfigurationManager.
/You can Save Data in XML file/
//You can Save and load time by this method but it's slow process,
it may crash if data is large and system is slow, it stores data runtime
so takes RAM, its ok to use for few rows without any problem
//use the collection for storing data runtime
List<Person> pers = new List<Person>();
public class Person
{
public string id { get; set; }//1
public string name { get; set; }//2
public string bilno { get; set; }//3
public string mob { get; set; }//4
public DateTime dt { get; set; }//5
}
string path=#"c:\.....";
void save()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path + #"\data.xml");
XmlNode xnode = xdoc.SelectSingleNode("Items");
xnode.RemoveAll();
foreach (Person i in pers)
{
XmlNode xtop = xdoc.CreateElement("Item");
XmlNode x1 = xdoc.CreateElement("a");
XmlNode x2 = xdoc.CreateElement("b");
XmlNode x3 = xdoc.CreateElement("c");
XmlNode x4 = xdoc.CreateElement("d");
XmlNode x5 = xdoc.CreateElement("e");
x1.InnerText = i.id;
x2.InnerText = i.name;
x3.InnerText = i.bilno;
x4.InnerText = i.mob;
x5.InnerText = i.dt.ToFileTime().ToString();
xtop.AppendChild(x1);
xtop.AppendChild(x2);
xtop.AppendChild(x3);
xtop.AppendChild(x4);
xtop.AppendChild(x5);
xdoc.DocumentElement.AppendChild(xtop);
}
xdoc.Save(path + #"\data.xml");
}
void load()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path + #"\data.xml");
foreach (XmlNode xnode in xdoc.SelectNodes("Items/Item"))
{
Person p = new Person();
p.id = xnode.SelectSingleNode("a").InnerText;
p.name = xnode.SelectSingleNode("b").InnerText;
p.bilno = xnode.SelectSingleNode("c").InnerText;
p.mob = xnode.SelectSingleNode("d").InnerText;
p.dt = DateTime.FromFileTime(Convert.ToInt64(xnode.SelectSingleNode("e").InnerText));
}
}

Programmatically access SharePoint lists and subsites?

How can I iterate SharePoint lists and subsites from a C# program? Is the SharePoint.dll from a SharePoint installation required for this, or is there a "Sharepoint client" dll available for remotely accessing that data?
Use the Sharepoint web services; in particular the Webs and Lists webservices do what you ask.
For Sharepoint 2007:
http://msdn.microsoft.com/en-us/library/bb862916(v=office.12).aspx
For Sharepoint 2007 you will need to access the web services. In Sharepoint 2010, there is a sharepoint client object model.
http://msdn.microsoft.com/en-us/library/ee857094%28office.14%29.aspx
I happen to be dealing with this very thing now... this works. I've dumbed down the code a bit to focus on just the mechanics. It's rough around the edges, but hopefully you get the idea. It's working for me.
Also, be sure to set up a web reference using the URL of your Sharepoint site. Use that as your "web reference" below.
private <web reference> _Service;
private String _ListGuid, _ViewGuid;
private Initialize()
{
_Service = new <web reference>.Lists();
_Service.Credentials = System.Net.CredentialCache.DefaultCredentials;
_Service.Url = "https://sharepointsite/_vti_bin/lists.asmx";
}
private String SpFieldName(String FieldName, Boolean Prefix)
{
return String.Format("{0}{1}", Prefix ? "ows_" : null,
FieldName.Replace(" ", "_x0020_"));
}
private String GetFieldValue(XmlAttributeCollection AttributesList,
String AttributeName)
{
AttributeName = SpFieldName(AttributeName, true);
return AttributesList[AttributeName] == null ?
null : return AttributesList[AttributeName].Value;
}
public void GetList()
{
string rowLimit = "2000"; // or whatever
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
System.Xml.XmlElement queryOptions =
xmlDoc.CreateElement("QueryOptions");
queryOptions.InnerXml = "";
System.Xml.XmlNode nodes = _Service.GetListItems(_ListGuid, _ViewGuid,
query, viewFields, rowLimit, null, null);
foreach (System.Xml.XmlNode node in nodes)
{
if (node.Name.Equals("rs:data"))
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].Name.Equals("z:row"))
{
XmlAttributeCollection att =
node.ChildNodes[i].Attributes;
String title = GetFieldValue("Title");
String partNumber = GetFieldValue("Part Number");
}
}
}
}
}
}
Also, the SpFieldName method is not iron-clad. It's just a good guess, for most field names in a list. This, unfortunately, is a journey of discovery. You need to expose the XML to find the actual field names if they don't match.
Good hunting.

"Feed is read only" error with Google Maps API

I am beginning to use the google data API (specifically for the finance app). I can read my portfolio's just fine, so I am authenticating correctly (or so I think). However, when I try and create a portfolio, I get a 'feed is read-only' error. The constructor for the service:
public class FinanceService : Service, IService
{
public FinanceService(string applicationName)
: base ("finance", applicationName)
{
this.RequestFactory = new GDataGAuthRequestFactory("finance", applicationName) { ProtocolMajor = 3 };
}
}
and saving it is
private const string _schema = "http://schemas.google.com/finance/2007";
private const string _feed = "http://finance.google.com/finance/feeds/default/portfolios";
AtomFeed atomFeed = new AtomFeed(new Uri(_feed), this.FinanceService);
return this.FinanceService.Insert(atomFeed, this as AtomEntry) as PortfolioEntry;
Any idea why the atomFeed would come back ReadOnly? The credentials are legit, and I can get my current portfolios without a problem.

Categories

Resources