SelectSingleNode is giving compilation error in dnx core 5.0 - selectsinglenode

I am getting this error with SelectSingleNode method:
DNX Core 5.0 error CS1061: 'XmlDocument' does not contain a definition for 'SelectSingleNode' and no extension method 'SelectSingleNode' accepting a first argument of type 'XmlDocument' could be found (are you missing a using directive or an assembly reference?)
Is it not supported yet? What are my alternatives?

In .Net Core 1.0 and .Net Standard 1.3 SelectSingleNode is an extenstion method
https://github.com/dotnet/corefx/issues/17349
Add a reference to make it available again:
<PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />

You need to use XDocument
const string xml = "<Misc><E_Mail>email#domain.xyz</E_Mail><Fax_Number>111-222-3333</Fax_Number></Misc>";
const string tagName = "E_Mail";
XDocument xDocument = XDocument.Parse(xml);
XElement xElement = xDocument.Descendants(tagName).FirstOrDefault();
if (xElement == null)
{
Console.WriteLine($"There is no tag with the given name '{tagName}'.");
}
else
{
Console.WriteLine(xElement.Value);
}

I have this problem too. To solve that, I'm using XDocument and so far so good.
Example:
XDocument xdoc = XDocument.Parse(xmlText);
var singleNode = xdoc.Element("someAttr");
var listOfNodes = singleNode.Elements("someAttrInnerText");
foreach (XElement e in listOfNodes)
{
string someAttr = e.Attribute("code").Value;
string someAttrInnerText = e.Value;
}
Don't forget to include "System.Xml.XDocument" inside your project.json.

Related

FSharp.Core FSharpFunc.FromConverter in netstandard20

In converting a project to .NET Standard 2.0, FSharpFunc<T, TResult>. FromConverter method from the FSharp.Core library is not available anymore. Is there a way to convert this code to a .NET Standard 2.0 FSharp.Core implementation?
async Task<Unit> RunProcess(FSharpMailboxProcessor<T> mailbox, Func<T, Task> process) { ... }
public BaseMailboxProcessor(Func<TFuncInput, Task> process, Action<Exception, TFuncInput> errorHandler = null, CancellationToken? cancellationToken = null)
{
m_ErrorHandler = errorHandler;
m_TokenSource = cancellationToken.HasValue ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken.Value) :
new CancellationTokenSource();
var cancellationOption = FSharpOption<CancellationToken>.Some(m_TokenSource.Token);
Converter<FSharpMailboxProcessor<TMailboxInput>, FSharpAsync<Unit>> converter = (mailbox) =>
{
return FSharpAsync.AwaitTask<Unit>(RunProcess(mailbox, process));
};
m_Mailbox = new FSharpMailboxProcessor<TMailboxInput>(FSharpFunc<FSharpMailboxProcessor<TMailboxInput>, FSharpAsync<Unit>>.FromConverter(converter), cancellationOption);
m_Mailbox.Start();
}
You should be able to use FuncConvert.ToFSharpFunc, this appears to still be present in the netstandard version of FSharp.Core.
You can trivially define your own:
let ToFSharpFunc (converter: System.Func<_, _>) = fun t -> converter.Invoke t
Also, if you need to use an FSharpFunc in C# you can simply call .Invoke on it where .Invoke on the FSharpFunc object is a Func.

How to get Sqlite Connection in Xamarin Forms in iOS?

I've created a Xamarin.Forms PCL project and trying to access the local data stored in sqlite database which is working file in Android but not working in iOS. Whenever I'm trying to call the iOS specific code using DependencyService it throws System.NullReferenceException: Object reference not set to an instance of an object.
Here is my calling statement
var db = DependencyService.Get<IDBPath>().GetDBPath();
Here is my iOS specific code for getting Sqlite Connection
using SQLite.Net;
using SQLite.Net.Async;
using SQLite.Net.Platform.XamarinIOS;
using SwachhParyatanApp.iOS;
using System;
using System.IO;
[assembly: Xamarin.Forms.Dependency(typeof(DBPath_iOS))]
namespace SwachhParyatanApp.iOS
{
class DBPath_iOS
{
public SQLiteAsyncConnection GetDBPath()
{
var sqliteFilename = "localData.db";
string folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string libraryPath = Path.Combine(folder, "..", "Library");
var path = Path.Combine(libraryPath, sqliteFilename);
var platform = new SQLitePlatformIOS();
var param = new SQLiteConnectionString(path, false);
var connection = new SQLiteAsyncConnection(() => new SQLiteConnectionWithLock(platform, param));
return connection;
}
}
}
I don't think the calling method is going to reach the iOS specific code because I used the break point in iOS specific code but it never came to the break point and it immediately gives the error. I've also tried going to the exception for details but there is no inner exception and in stacktrace it only points to the line which called the method.
Using SQLite.Net PCL below is a working example of an iOS dependency injection recipient for SQLite. A couple of differences I noticed are your db extension .db instead of .db3 and your 'assembly' header does not implement the full namespace. I am not sure if that matters.
[assembly: Dependency(typeof(NameSpace.iOS.SQLiteUtility.SQLite_iOS))]
namespace NameSpace.iOS.SQLiteUtility
{
class SQLite_iOS : ISQLite
{
public SQLiteConnection GetConnection()
{
try
{
var sqliteFilename = "MyDB.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
var path = Path.Combine(libraryPath, sqliteFilename);
var plat = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
var conn = new SQLite.Net.SQLiteConnection(plat, path,
SQLite.Net.Interop.SQLiteOpenFlags.ReadWrite |
SQLite.Net.Interop.SQLiteOpenFlags.Create |
SQLite.Net.Interop.SQLiteOpenFlags.FullMutex, true);
return conn;
}
catch (SQLiteException ex)
{
Helpers.Helper_ErrorHandling.SendErrorToServer(ex);
return null;
}
catch (System.Exception ex)
{
Helpers.Helper_ErrorHandling.SendErrorToServer(ex);
return null;
}
}
}
If it must be the async version you may want to look at How to use SQLiteAsyncConnection from the async PCL version of SQLite?

ASP MVC setting defining images folder

I am a newbie in asp mvc, and would like to define links in views to image/content folder in a way so I don't have to change each link if a image folder changes.
Is is possible using ActionLink and routing, bundling or there is a better way to achieve this.
I could not find a good example anywhere so I did not try anything any coding far.
I am thinking of storing a fixed path somewhere, but is that really a mvc type solution?
There are a number of ways you could do this. Here's one approach to extend the Url.Content() method.
1. Create an extension method
We'll called it Virtual().
namespace TestApp.Extensions
{
public static class UrlHelperExtensions
{
private const string _settingPattern = "path:{0}";
private const string _regexPattern = #"\{\w+\}";
public static string Virtual(this UrlHelper helper, string url)
{
Regex r = new Regex(_regexPattern);
var matches = r.Matches(url);
if (matches.Count == 0) return url;
var sb = new StringBuilder(url);
var keys = WebConfigurationManager.AppSettings.AllKeys;
foreach (var match in matches)
{
string key = match.ToString().TrimStart('{').TrimEnd('}');
string pattern = string.Format(_settingPattern, key);
foreach (var k in keys)
{
if (k == pattern)
{
sb.Replace(match.ToString(), WebConfigurationManager.AppSettings.Get(k));
}
}
}
return helper.Content(sb.ToString());
}
}
}
2. Add settings to the main Web.config
Freely add any paths you want.
<add key="path:images" value="~/Content/images" />
<add key="path:scripts" value="~/scripts" />
3. Add the namespace to the Web.config of your views directory
<namespaces>
<add namespace="TestApp.Extensions"/>
</namespaces>
4. Use the new method
#Url.Virtual("{images}/mypic.png")
Output:
/Content/images/mypic.png
You can now use Virtual() where you would Content().
This solution is arguably excessive, but it is comprehensive.

Localization in MonoDroid

My app is localized using the standard .NET RESX methods (ie. String.fr.resx, Strings.de.resx etc.) works great under Windows Phone.
I am porting to Android using MonoDroid and I do not see the localized UI when I switch locales on the phone. If I rename the APK file to ZIP and open it I see that it has not packaged up the locale DLLs produced during the build (ie. the intermediate \.Resources.dll files are under the bin directory but are not packaged into the APK).
What am I missing? I have tried changing the build action on the RESX files from "Embedded Resource" to "Android Resource" and even "Android Asset" but to no avail.
Thanks in advance for any help!
Cheers
Warren
I asked about this on the monodroid irc channel and the official answer was "not supported yet but we do have plans to do it".
You need to convert the resx files to android xml format (see below) and add them to your project as shown here: http://docs.xamarin.com/android/tutorials/Android_Resources/Part_5_-_Application_Localization_and_String_Resources
In my app (game) I needed to look up the localised strings by name. The code to do this was simple but not immediately obvious. Instead of using ResourceManager I swapped in this for android:
class AndroidResourcesProxy : Arands.Core.IResourcesProxy
{
Context _context;
public AndroidResourcesProxy(Context context)
{
_context = context;
}
public string GetString(string key)
{
int resId = _context.Resources.GetIdentifier(key, "string", _context.PackageName);
return _context.Resources.GetString(resId);
}
}
Since I'm not a XSLT guru I made a command line program for converting resx to Android string XML files:
/// <summary>
/// Conerts localisation resx string files into the android xml format
/// </summary>
class Program
{
static void Main(string[] args)
{
string inFile = args[0];
XmlDocument inDoc = new XmlDocument();
using (XmlTextReader reader = new XmlTextReader(inFile))
{
inDoc.Load(reader);
}
string outFile = Path.Combine(Path.GetDirectoryName(inFile), Path.GetFileNameWithoutExtension(inFile)) + ".xml";
XmlDocument outDoc = new XmlDocument();
outDoc.AppendChild(outDoc.CreateXmlDeclaration("1.0", "utf-8", null));
XmlElement resElem = outDoc.CreateElement("resources");
outDoc.AppendChild(resElem);
XmlNodeList stringNodes = inDoc.SelectNodes("root/data");
foreach (XmlNode n in stringNodes)
{
string key = n.Attributes["name"].Value;
string val = n.SelectSingleNode("value").InnerText;
XmlElement stringElem = outDoc.CreateElement("string");
XmlAttribute nameAttrib = outDoc.CreateAttribute("name");
nameAttrib.Value = key;
stringElem.Attributes.Append(nameAttrib);
stringElem.InnerText = val;
resElem.AppendChild(stringElem);
}
XmlWriterSettings xws = new XmlWriterSettings();
xws.Encoding = Encoding.UTF8;
xws.Indent = true;
xws.NewLineChars = "\n";
using (StreamWriter sr = new StreamWriter(outFile))
{
using (XmlWriter writer = XmlWriter.Create(sr, xws))
{
outDoc.Save(writer);
}
}
}
}

ASP.net mvc, generic/dynamic controllers and Type.GetType: how can I keep my URLs pretty?

Using information from some of the questions here on generic views, I have created an MVC app that reads .dlls from its own /bin directory and builds the UI on the fly. InputBuilder partial views helped a lot. I also made a ControllerFactory, after the advice from here and elsewhere.
My problem is, while everything is working OK and reflection is recognizing the types I'm passing around, GetType() requires the full assembly qualified name ('scuse the code, still prototyping):
public IController CreateController(RequestContext requestContext, string controllerName)
{
Type controllerType = null;
Type genericType;
//controllerName coming in as full assembly-qualified path
Type baseControllerType = typeof(CoreDataController<>);
genericType = Type.GetType(controllerName);
if (genericType != null)
{
controllerType = baseControllerType.MakeGenericType(genericType);
}
if (controllerType != null)
{
return Activator.CreateInstance(controllerType) as IController;
}
return controllerType;
}
This makes my urls look like this:
http://localhost:1075/CoreData.Plans,%20PlansLib,%20Version=1.0.0.0,%20Culture=neutral,%20PublicKeyToken=null/Create
Obviously sub-optimal.
What I'd like is http://localhost:1075/CoreData.Plans/Create
or even better:
http://localhost:1075/Plans/Create
Should I store a dictionary accessible to my controller on Application_Start() mapping short names to fully-qualified names? Is there a feature of Reflection I'm missing that would solve this problem?
I think your idea of a dictionary mapping pretty names to types would be good. You may want to try putting attributes on your classes, then at startup, you can use reflection to extract out the attributes for building the dictionary:
[UrlName("my-class-name")]
public class MyClassName
{
// ...
}
I had this problem with long and even inconsistant type names across different platforms that i was using and came up with a way to search for the type in the dlls loaded in the current appdomain.
public static Type GetTypeFromName(string TypeNameStr, Assembly[] Asms)
{
Type VarType = null;
string TypeStr = TypeNameStr.Split(',')[0];
foreach (Assembly Dll in Asms)
{
VarType = Dll.GetType(TypeNameStr);
if (VarType == null)
VarType = Dll.GetType(TypeStr);
if (VarType != null)
break;
}
return VarType;
}
All that you need to do is pass the function a list of assemblies that you can get from the current appdomain and it will try to find the Type from there you can create a dictionary using the name and the type to cache this so that you don't have to do this over and over again.

Resources