IoT modules can be created from the environment using :
ModuleClient.CreateFromEnvironmentAsync(settings)
However, there does not seem to be an equivalent method for devices. For now, I am setting the device connection string in the program to test it out, but is there a better way to read teh connection string from iotedge/config.yaml for all the edge devices deployed out there?
Methods to do so for .NET and python would be appreciated.
You can use a yaml parse library to deserialize the document, such as YamlDotNet. In fact, you can refer to YamlDocument in iot edge. But in the class, it does not provide a method to get the key value. Please refer to following code.
public class YamlDocument
{
readonly Dictionary<object, object> root;
public YamlDocument(string input)
{
var reader = new StringReader(input);
var deserializer = new Deserializer();
this.root = (Dictionary<object, object>)deserializer.Deserialize(reader);
}
public object GetKeyValue(string key)
{
if(this.root.ContainsKey(key))
{
return this.root[key];
}
foreach(var item in this.root)
{
var subItem = item.Value as Dictionary<object, object>;
if(subItem != null && subItem.ContainsKey(key))
{
return subItem[key];
}
}
return null;
}
}
And then you can get the device connection string from the config.yaml. If you use python, you can import yaml library to analysis the file.
StreamReader sr = new StreamReader(#"C:\ProgramData\iotedge\config.yaml");
var yamlString = sr.ReadToEnd();
var yamlDoc = new YamlDocument(yamlString);
var connectionString = yamlDoc.GetKeyValue("device_connection_string");
Console.WriteLine("{0}", connectionString);
To get the config file from the host, add the following to the docker deployment file. Note that the source file is config1.yaml which is the same as config.yaml except that it has read permissions for everyone not just root.
"createOptions": "{\"HostConfig\":{\"Binds\":[\"/etc/iotedge/config1.yaml:/app/copiedConfig.yaml\"]}}"
With the above line in place, the copiedConfig.yaml file can be used in the container, along with #Michael Xu's parsing code to derive teh connection string.
Long term, one may want to use the device provisioning service anyway but hope this helps for folks using device conenction strings for whatever reason..
Related
I'm using SimpleFileVisitor to search for a file. It works fine on Windows and Linux. However when I try using it on Unix like operating systems It doesn't work as expected. I would get errors like this:
java.nio.file.NoSuchFileException:
/File/Location/MyFolder/\u0082\u0096\u0096âĜu0099\u0081\u0097K
\u0097\u0099\u0096\u0097\u0085\u0099Ĝu0089\u0085
It looks like the obtained name is in different character encoding and maybe that is what causing the issue. It looks like in between the obtaining the name and trying to obtain the access to the file, the encoding is getting missed up. This result in calling preVisitDirectory once then visitFileFailed for every file it tries to visit. I'm not sure why the walkFileTree method is doing that. Any idea?
My using for SimpleFileVisitor code looks like this:
Files.walkFileTree(serverLocation, finder);
My SimpleFileVisitor class:
public class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private final List<Path> matchedPaths = new ArrayList<Path>();
private String usedPattern = null;
Finder(String pattern) {
this.usedPattern = pattern;
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void match(Path file) { //Compare pattern against file or dir
Path name = file.getFileName();
if (name != null && matcher.matches(name))
matchedPaths.add(file);
}
// Check each file.
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
match(file);
return CONTINUE;
}
// Check each directory.
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
match(dir);
return CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
System.out.println("Issue: " + e );
return CONTINUE;
}
Try using "Charset.defaultCharset()" when you create those "file" and "dir" strings you pass around. Otherwise, you could very likely mangle the names in the process of creating those strings to pass them to your visit methods.
You might also check your default encoding on the JVM your are running, if it is out of sync with the file system you are reading, your results will be, err, unpredictable.
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);
}
}
}
}
Is there a way to set the timeout for CreateSprocAccessor(...) in Enterprise Library 5.0?
Cause the default timeout is not working for long stored procedures.
First thing: adding a timeout in the connection string doesn't solve the problem.
I found a workaround: You can modify the source code of EL 5.0 and generate a new custom DLL.
in ...\EntLib50Src\Blocks\Data\Src\Data\SprocAccessor.cs
in Execute(...) method
add this code just before return: command.CommandTimeout = 120; // 2 mins
Compile and use the new Microsoft.Practices.EnterpriseLibrary.Data.dll that you can find in ...\EntLib50Src\Blocks\bin\Debug
actually, I think there is no need to have your own copy of EL. In order to keep original EL binaries unchanged, you just can do the follow:
inherit from SprocAccessor class
overwrite Execute() method, put here the same code as in SprocAccessor.Execute() but adding the timeout part
you will need also to keep in local variable (in your new class) procedureName as this variable is private in SprocAccessor class
some thing like this:
public class SprocAccessorWithTimeout<T> : SprocAccessor<T>
{
readonly string procedureName;
public SprocAccessorWithTimeout(Database database, string procedureName, IRowMapper<T> rowMapper) : base(database, procedureName, rowMapper)
{
this.procedureName = procedureName;
}
public override IEnumerable<T> Execute(params object[] parameterValues)
{
using (var command = Database.GetStoredProcCommand(this. procedureName))
{
command.CommandTimeout = MaxSpExecutionTimeout;
if (parameterValues.Length > 0)
{
Database.AssignParameters(command, parameterValues);
}
return base.Execute(command);
}
}
}
I am using Castle to create my database context based on a given interface. I have the following code in my Installer class and this works fine at the moment.
private ConfigureDelegate ConfigureContext()
{
return p => p.Named(p.ServiceType.Name)
.LifeStyle.PerWebRequest
.DependsOn(new { connectionString = ConfigurationManager.ConnectionStrings["conStringName"].ConnectionString });
}
However i now have a scenario where this installer will find more than one concrete implementation of my interface, where each one should have a different connection string supplied.
Is this possible - if so, could someone point me in the right direction.
TIA
Yes, it's possible if you can write a piece of code that provides the connection string name for the service. Perhaps something like this:
private ConfigureDelegate ConfigureContext()
{
return p => p.Named(p.ServiceType.Name)
.LifeStyle.PerWebRequest
.DependsOn(new
{
connectionString =
ConfigurationManager
.ConnectionStrings[GetConnectionName(p.ServiceType.Name)]
.ConnectionString
});
}
private string GetConnectionName(string serviceName)
{
// return the connection name
}
Here is the code that I am using. I have spent some time looking at the Redemption objects, but, nothing jumps out at me:
public static bool PopEmail(string domainUserName, string mSubject, string mBody, string mTo, string mCc = "", string mBcc = "", List<String> fileAttachments = null)
{
log.Info("Starting to Pop Outlook Email Message");
RDOSession oSession = new RDOSession();
try
{
oSession.LogonExchangeMailbox(domainUserName, string.Empty);
if (oSession.LoggedOn)
{
RDOMail oMail = oSession.GetDefaultFolder(rdoDefaultFolders.olFolderOutbox).Items.Add("IPM.Note");
oMail.Subject = mSubject;
oMail.Body = mBody;
oMail.To = mTo;
oMail.CC = mCc;
oMail.BCC = mBcc;
if (fileAttachments != null)
{
foreach (string file in fileAttachments)
{
object newFile = file;
oMail.Attachments.Add(newFile, Type.Missing, Type.Missing, Type.Missing);
newFile = null;
}
}
oMail.Display();
Marshal.FinalReleaseComObject(oMail);
oMail = null;
}
oSession.Logoff();
Marshal.FinalReleaseComObject(oSession);
oSession = null;
GC.Collect();
GC.WaitForPendingFinalizers();
log.Info("Outlook Email has been Popped.");
return true;
}
catch (Exception)
{
log.Error("Outlook Pop Email Failed.");
throw;
}
}
Thank you,
The signature is actually inserted by the Outlook inspector object on instantiation, so if your code is running inside an Outlook addin you could probably try saving the item and then reopening it from the OOM as a _MailItem via _Namespace.GetItemFromId and then calling its GetInspector method (you don't actually have to do anything with the returned inspector reference).
Note that I haven't tried this with an item initially created via RDO. I usually create the items in OOM and then create an RDO wrapper.
If your code is running outside of Outlook you'd have to use OLE to get a reference to its _Application object and then pull the _Namespace object from there. If you are using standalone MAPI without Outlook installed the signature functionality is completely unavailable.
I have added code to append to the oMail.HTMLBody which reads the signature from the C:\Users\UserName\AppData\Roaming\Microsoft\Signatures folder. This file is generated via a plug in written by one of our developers that reads information from Exchange to determine User Name, Title, Phone, Fax, etc.