list files in a silverlight project - silverlight

I'd like to list files in a given folder (which is in another project) in Silverlight. Actually, they are images.
Project A : "/Images/a.png" "/Images/b.png"
Project B : I want to list the files in "Project A/Images/"
I haven't found a way to do it, can you help me ?
Thanks

You can use reflection to perform this at runtime. If you set the build action of your images to "embedded resource", you can enumerate them at runtime.
// locate the assembly
Assembly thisAssembly = Assembly.GetExecutingAssembly();
// list all the resources
string[] resNames = thisAssembly.GetManifestResourceNames();
foreach (string resName in resNames)
{
if (resName.ToLower().EndsWith(".png"))
{
// do something!
}
}
Note, if the images are in a different project / assembly, you may have to navigate to this assembly before enumerating the resources.

Related

Setting file path in imported C function inside Swift Framework

I am trying to use C library source files inside my Cocoa Framework which has function named
void swe_set_ephe_path(char *path);
Which will basically be
swe_set_ephe_path(”C:\\SWEPH\\EPHE”);
for windows.
This library contains other data files which only work after this function is set.
When imported to Swift the function looks like this
swe_set_ephe_path(path: UnsafeMutablePointer<Int8!>)
Since i want to bundle up all the data files in framework and use it in my application, i have done something like this
public class SwissEphemeris {
public init() {
let path = Bundle.main.bundlePath
let swePath = UnsafeMutablePointer<Int8>(mutating: (path as NSString).utf8String)
swe_set_ephe_path(swePath)
}
}
But it seems it's not working and the functions which needs data to be searched in files are not able to operate.
If anybody interested to look into Swiss library documentation, check here for the link,
https://www.astro.com/swisseph/swephprg.htm#_Toc505244836
There are two problems:
First, the resource files are in the “Resources” subdirectory of the framework, not in the top-level framework directory. You can obtain a path to that directory with
let resourcePath = Bundle(identifier: "com.Abhi.SwissFramework")!.resourcePath!
or with
let resourcePath = Bundle(for: type(of: self)).resourcePath!
I suggest to force-unwrap the optionals because you know that the bundle and the resources directory exist. A failure would indicate a build problem which should be detected early.
Second, the C function takes a char * argument even though it does not mutate the passed string. Here you can use the approach from UnsafeMutablePointer<Int8> from String in Swift:
resourcePath.withCString {
swe_set_ephe_path(UnsafeMutablePointer(mutating: $0))
}
Even better: use the dedicated method withUnsafeFileSystemRepresentation() to get the file system representation of the resource path as a C string:
let resourceURL = Bundle(for: type(of: self)).resourceURL!
resourceURL.withUnsafeFileSystemRepresentation {
swe_set_ephe_path(UnsafeMutablePointer(mutating: $0))
}

Can't find file with UserControl but not (in this case) Label

I have a UserControl in a the DLL Controls, a converter in the DLL Base and language resources in the DLL Languages.
When I combine everything the following way, everything works fine:
<Label Content="{Binding FallbackValue='[Design] Name', ConverterParameter='Name', Converter={StaticResource Translate}}"
ContentStringFormat="{}{0}:"/>
No errors and when I run my application the correct word for the parameter Name is loaded (in my case Naam for Dutch).
I also try this on my WatermarkTextBox like this:
<c:WatermarkTextBox Watermark="{Binding FallbackValue='[Design] Name *', ConverterParameter='Name', Converter={StaticResource Translate}}" />
But then I get the following error:
Could not load file or assembly 'file:///C:...\Languages.dll' or one of its dependencies. The system cannot find the file specified.
Why does this happen with my WatermarkTextBox in Controls DLL and not with the Label?
The first step here is to make sure, that the assembly file Languages.dll is actually present in the application directory (usually, bin/Debug/). If it isn't - as the error message says - the system cannot find the file specified... The solution in this case is to reference the assembly Languages.dll in your application project. To avoid this, make sure that every time you add a reference to an assembly, you also add references to this assembly's dependencies. I.e. if you have an application project App which references a library LibA.dll and LibA references a library LibB.dll, you should add a reference to LibB.dll in your App project as well. That way, all required assemblies will always be copied to the output directory.
If the assembly is correctly located in the output directory, but you still get the error message, in 99% of the cases the problem is a mismatch in the building targets, alas the platform for which the assemblies were built. Make sure all projects target the same platform (x86, for example). You can check the target in the projects Properties tabs.
EDIT:
Ok, I just now understood you're talking about the design time error in Visual Studio's XAML Designer :) The issue is the name of the assembly: Noru.Languages.dll. I suppose, the ending .Languages is considered a resource name and Visual Studio prohibits resource names in assembly names. There's a registry entry HKLM\Software\Microsoft\VisualStudio\12.0\Designers\AllowResourcesInFilename, maybe experimenting with that can resolve the issue. Not 100% sure, though. Anyway, if you rename the assembly to Nori.Language.dll in the project's properties and rebuild everything, design time support is back and the controls show up correctly in the designer.
EDIT 2:
Really strange behavior altogether... Well, this line in the Class Language might very well be the cause? Try specifying the full string here... Does this work?
ResourceManager rm = new ResourceManager("Noru.Languages.Language", System.Reflection.Assembly.LoadFrom("Noru.Languages.dll"));
EDIT 3:
Obviously, the problem was the line I mentioned above in Edit 2. I've experimented a bit:
/// <summary>
/// Will return the requested text in the language the application is in. Case sensitive.
/// </summary>
/// <param name="s">Provide a listed String from the language files.</param>
/// <returns>Will return a System.String in the language of the application.</returns>
public static string GetText(string s)
{
//return Culture.ToString();
//return Assembly.GetExecutingAssembly().FullName;
//ResourceManager rm = new ResourceManager("Noru.Lang.Resource1", Assembly.GetAssembly(typeof(Language)));
//ResourceSet rs = rm.GetResourceSet(Culture, true, true);
var rs = LanguageResource.ResourceManager;
try
{
return rs.GetString(s);
}
catch (Exception)
{
return "not found";
}
}
The last version (not commented out) works, because I've generated code for the resource files by setting AccessModifier to public in the resource editor (double click on the resource file, you'll find it in the toolbar).
This version (never mind about the resource name, I tried different versions here):
ResourceManager rm = new ResourceManager("Noru.Lang.Resource1", Assembly.GetAssembly(typeof(Language)));
threw another error, saying it cannot find the resource inside the assembly. I think there was something wrong about the usage of ResourceManager here. I'm not an expert here, so I can't tell why. I just know that the last version seems to work as expected... I hope, you'll find the same ;)

Loading ResourceDictionary resource at runtime from assemblies with the same name

I encountered some problem when trying to load resources from two separate assemblies having the same name but located in a different folder:
C:\folder1\fcl.dll
C:\folder2\fcl.dll
A ResourceDictionary named Resources.xaml is embedded (as a Page) in each of these assemblies.
To load the first ResourceDictionary, I use the following snippet :
// Load the assembly in memory
var assembly = Assembly.LoadFrom(#"c:\folder1\FCL.Dll");
// Get Dictionnary
var uri = string.Format("pack://application:,,,/{0};Component/Resources.xaml", assembly.GetName().Name);
var resourceDictionary = new ResourceDictionary { Source = new Uri(uri) };
This is running !
But when I try to load the second ResourceDictionary with the same snippet of code (just changing Assembly.LoadFrom(#"c:\folder1\FCL.Dll") by Assembly.LoadFrom(#"c:\folder2\FCL.Dll"), it does not load resources from c:\folder2\fcl.dll, but those stored in the previously loaded c:\folder1\fcl.dll :-(
The cause: The shortAssemblyName field of the URI is the same, in may case FCL:
var uri = string.Format("pack://application:,,,/{0};Component/Resources.xaml", assembly.GetName().Name)
Does someone know how to solve this problem?
You can't have two assemblies loaded with the same name, so I think the second Assembly.LoadFrom is just being ignored. You are probably going to have to rename one of the assemblies.

How to make a composite manifest for Microsoft smooth streaming

I am new to Microsoft Smooth Streaming and have questions about the making of composite manifests.
Following the guidance from here.
I was able to make a composite manifest of a single clip element that played in Silverlight player.
However, when I try to add more clips from other videos, the player stopped working and gave out no error information.
And I am doing this all by hand. and when I trying to use the Expression Encoder 4 Pro to create such a video, I got a normal .ismc file instead of a .csm file.
My questions are:
What is the best way of making a composite manifest which contains clips from different videos?
Is there any spec to follow when encoding these videos? or does the support of composite manifest put any restriction on the video format?
And the last one is: Is there an easy way to debug it (like validating my .csm file)?
EDIT my own solution:
Looks like no one cares about this, but since I finally solved this, I am writing this down here to save others' time.
to debug a composite manifest, I built a simple Silverlight app in Visual Studio, and add a simple function to report an error:
MainPage.xaml.cs:
public MainPage()
{
InitializeComponent();
this.SmoothPlayer.SmoothStreamingErrorOccurred += new EventHandler<SmoothStreamingErrorEventArgs>(SmoothPlayer_SmoothStreamingErrorOccurred);
}
public void SmoothPlayer_SmoothStreamingErrorOccurred(object sender,
SmoothStreamingErrorEventArgs e)
{
MessageBox.Show("Error: " + e.ErrorCode + "; " + e.ErrorMessage);
}
And I found this web page useful.
You need to use:
<c t="", d"">
instead of
<c d="">
You have to calculate the ClipBegin and ClipEnd values right.
Below is a sample code in python to convert a .ismc to a .csm(assume that the ism below is an xml.etree.ElementTree object representation of the manifest xml content):
def ism2csm(url, ism):
if ism is None: return csm
csm = xml.Element('SmoothStreamingMedia', {'MajorVersion':'2', 'MinorVersion':'1', 'Duration':ism.attrib.get('Duration')})
clip = xml.Element('Clip', {'Url':url, 'ClipBegin':'0','ClipEnd':'0'})
csm.append(clip)
for stream_index in ism.iter('StreamIndex'):
clip.append(stream_index)
for stream_index in clip.iter('StreamIndex'):
t = 0
last_c = None
for c in stream_index.iter('c'):
c.attrib['t'] = str(t)
t += int(c.attrib.get('d'))
if last_c is not None: del last_c.attrib['d']
last_c = c
if clip.attrib.get('ClipEnd') == '0':
clip.attrib['ClipEnd'] = str(t)
return csm

Reflection error when using F# sprintf "%A" on Windows Phone

I have a set of F# record types like this:
type Course =
{ Id : int
Title : string
Instructor : string
Duration : string
StartDate : string
IconUrl : string
Url : string
LectureSections : LectureSection list }
and LectureSection =
{ Title : string
Completed : bool
Lectures : Lecture list }
and Lecture =
{ Title : string
VideoUrl : string }
and at some point I call
sprintf "%A" course
where course is an instance of the Course record
On a regular .NET project this works fine, but on a Windows Phone 7.1 / Silverlight 4 F# project (I'm using Daniel Mohl's templates), I get this error:
Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
The problem seems to be the lists. Does anyone know of any way around this problem?
The templates should come with a custom built FSharp.Core.dll that disable features that are not available on Windows Phone. Are you sure you are compiling against this dll, and not the Windows PC one?
I had similar problems with Xbox360 and XNA. The F# team sent me a dll suitable for use for the Xbox360, along with some brief instructions on the settings used to build the dll.
Here is the propertygroup we've used to compile FSharp.Core:
<PropertyGroup Condition="'$(TargetFramework)'=='Xbox360\CompactFramework\3.7'">
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<XnaFrameworkVersion>v4.0</XnaFrameworkVersion>
<XnaPlatform>Xbox 360</XnaPlatform>
<XnaProfile>HiDef</XnaProfile>
<XnaCrossPlatformGroupID>a8d70e6b-9a75-4aec-80f8-62cf373f7368</XnaCrossPlatformGroupID>
<XnaOutputType>Game</XnaOutputType>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DefineConstants>$(DefineConstants);FX_NO_ARRAY_LONG_LENGTH;FX_NO_DEBUG_PROXIES;FX_NO_EXIT;FX_FSLIB_IOBSERVABLE;FX_NO_WEB_CLIENT;FX_NO_WEB_REQUESTS;FX_NO_CHAR_PARSE;FX_NO_DEFAULT_DEPENDENCY_TYPE;FX_SIMPLE_SECURITY_PERMISSIONS;FX_NO_TRUNCATE;FX_NO_CULTURE_INFO_ARGS;FX_NO_REFLECTION_MODULE_HANDLES;FX_NO_OPERATION_CANCELLED;FX_NO_TO_LOWER_INVARIANT;FX_NO_EXIT_CONTEXT_FLAGS;FX_NO_BASED_ARRAYS;FX_NO_DOUBLE_BIT_CONVERTER;FX_NO_BINARY_SERIALIZATION;FX_NO_ASCII_ENCODING;FX_NO_DEFAULT_ENCODING;FX_NO_FILE_OPTIONS;FX_NO_NONBLOCK_IO;FX_NO_COMMAND_LINE_ARGS;FX_NO_ENVIRONMENT;FX_NO_PROCESS_START;FX_NO_APP_DOMAINS;FX_NO_PROCESS_DIAGNOSTICS;FX_FSLIB_STRUCTURAL_EQUALITY;FX_FSLIB_LAZY;FX_FSLIB_TUPLE;FX_NO_REFLECTION_EMIT</DefineConstants>
<Tailcalls>false</Tailcalls>
<!-- It would be better to use MSBuild resolution here, but the TargetFrameworkIdentifier etc. aren't set up quite correctly as yet -->
<OtherFlags>$(OtherFlags) --simpleresolution -r:"C:\Program Files\Microsoft XNA\XNA Game Studio\v4.0\References\Xbox360\mscorlib.dll"</OtherFlags>
</PropertyGroup>
and the new .targets we use:
<Import Project="$(MSBuildExtensionsPath)\Microsoft\XNA Game Studio\Microsoft.Xna.GameStudio.targets" Condition="'$(TargetFramework)'=='Xbox360\CompactFramework\3.7'"/>
The dll they sent me was working fine, and I never had to use these instructions, but they might be useful to someone who wants to build an FSharp.Core.dll for a new platform. Note in particular the DefineConstants part.

Resources