Why does the WP8 Tiles example use reflection? - c#

Use of the new WP8 Tiles uses reflection instead of instantiating and calling the methods directly as shown below.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj720574(v=vs.105).aspx
Type shellTileType = Type.GetType("Microsoft.Phone.Shell.ShellTile, Microsoft.Phone");
shellTileType.GetMethod("Update").Invoke(tileToUpdate, new Object[] { UpdateTileData });
I'm wondering if there is a specific reason reflection is being used this situation. Is it cause the WP < 7.8 won't have a reference to the ShellTile Type and thus the VM will error? If the VM never accesses this part of the code wouldn't that be good enough?

You can target your app for one of WP7 or WP8 platfroms.
In WP7 SDK there is no FlipTileData class, so you won't be able to compele code wich uses this class.
But you can run your WP7 app on WP8 device, so you can create Wilde Tiles using reflection.
You just need to check the OS version before:
private static Version TargetedVersion = new Version(8, 0);
public static bool IsTargetedVersion
{
get
{
return Environment.OSVersion.Version >= TargetedVersion;
}
}
Otherwise, if you target your app for WP8 platform only - feel free to use FlipTileData and other classes without reflection. Here you can find the example.

In WP7 SDK there is no API for these new Tile types, they are only available in WP7.8 and WP8. So if you want to use new tile sizes on WP7.8 devices or in WP7 application running on WP8 device, you have to use reflection.
Of course in WP8 app you can use the API directly with no problems.

Related

C# UI Automation API with multiple virtual desktops on Windows 10

Warning, I'm coming into this problem as someone who had never used C# before a couple of days ago...
I'm trying to write a "simple" program that scrapes text from a targeted window and displays it on a 2x20 VFD display. I've learned about using the Microsoft UI Automation API, and have had some success in using it to accomplish my goal.
However, if the target window is on a different virtual desktop it seems that using TreeWalker on the AutomationElement.RootElement will not find the target.
The code I'm using now to get my target window (while it's on the same virtual desktop):
public static AutomationElementCollection FindByMultipleConditions(AutomationElement anElement)
{
if (anElement == null)
{
throw new ArgumentException();
}
Condition conditions = new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane),
new PropertyCondition(AutomationElement.IsContentElementProperty, true),
new PropertyCondition(AutomationElement.IsControlElementProperty, true),
new PropertyCondition(AutomationElement.IsKeyboardFocusableProperty, false),
new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ClassNameProperty, "Chrome_WidgetWin_0")
);
AutomationElementCollection elementCollection =
anElement.FindAll(TreeScope.Children, conditions);
return elementCollection;
}
An AutomationElement.RootElement is passed to this method, and this seems to be granular enough to always target the specific window I'm interested in, but it returns nothing if my target window is moved to a different virtual desktop.
Is this a limitation of using the UI Automation API to accomplish my task? Is there a way to iterate through each virtual desktop while searching for my target window or should I try a different way of approaching this?
Thanks!
The managed "System.Windows.Automation" library is old and predates multiple desktops being implemented in Windows as far as I know.
You should try to use the new automation api introduced in Windows 8. Sadly it's not managed, but there is great library called FlaUI that makes it as easy to use as the managed library (be sure to use FlaUI.UIA3 not FlaUI.UIA2 when using it to use the new api).
If you don't want a full library then there is a nuget wrapper for the new com api (from the same guys behind FlaUI I think).
Good luck.

Access MacBook camera using C# and Xamarin.Mac forms on Visual Studio?

I need to integrate a video stream from my Macbook camera using a Xamarin.Mac form. However, all of the documentation that I find only tells you how to do so in iOS and Android platforms.
How would you go at getting a video stream from a Macbook then? Any libraries I should look at?
You will want to review the AVFoundation APIs (QTKit is deprecated).
You can create a custom Xamarin.Forms View renderer based on a NSView and assign the AVCaptureVideoPreviewLayer as the control's layer to stream the camera output to this control.
Store class level references to following and make sure you Dispose them when your control goes out of scope otherwise there will be leaks:
AVCaptureDevice device;
AVCaptureDeviceInput input;
AVCaptureStillImageOutput output;
AVCaptureSession session;
In your capture setup, you can grab the default AV device assuming you want to use the build-in FaceTime Camera (also known as iSight).
macOS/Forms Example:
device = AVCaptureDevice.GetDefaultDevice(AVMediaTypes.Video);
input = AVCaptureDeviceInput.FromDevice(device, out var error);
if (error == null)
{
session = new AVCaptureSession();
session.AddInput(input);
session.SessionPreset = AVCaptureSession.PresetPhoto;
var previewLayer = AVCaptureVideoPreviewLayer.FromSession(session);
previewLayer.Frame = Control.Bounds;
Control.Layer = previewLayer;
output = new AVCaptureStillImageOutput();
session.AddOutput(output);
session.StartRunning();
}
Note: A lot of the AVFoundation framework is shared between iOS and MacOS, but there are some differences so if you end up looking at iOS sample code be aware you might need to alter it for macOS.
https://developer.apple.com/documentation/avfoundation

Referencing WinRT/UWP libraries in a .NET desktop application while maintaining support for Windows 7

I am trying to reference "Windows.Networking.Connectivity" classes in my desktop application. I am basically interested in handling metered connections in my app.
Basically what I am trying to do is simple:
var connectionCost = NetworkInformation.GetInternetConnectionProfile().GetConnectionCost();
if (connectionCost.NetworkCostType == NetworkCostType.Unknown
|| connectionCost.NetworkCostType == NetworkCostType.Unrestricted)
{
//Connection cost is unknown/unrestricted
}
else
{
//Metered Network
}
The only method I know of that allows a desktop application to reference UWP assemblies is by manually editing the project file and adding the following line to the csproj file:
<TargetPlatformVersion>8.0</TargetPlatformVersion>
Applying the code and "hack" works fine but the problem is that doing so will prevent my app from running on Windows 7 which I need to support.
I was wondering if there is a way to reference UWP assemblies in a desktop application without having to drop support for Windows 7.
And since for the time being I only want to check if a connection is metered, I am open to suggestions about how to get this information without referencing Windows assemblies.
I found a way to use reflection and call UWP methods without having to specify a target platform. For my case this is what I did:
var networkInfoType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profileType = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");
var profileObj = networkInfoType.GetTypeInfo().GetDeclaredMethod("GetInternetConnectionProfile").Invoke(null, null);
dynamic profDyn = profileObj;
var costObj = profDyn.GetConnectionCost();
dynamic dynCost = costObj;
var costType = (NetworkCostType)dynCost.NetworkCostType;
if (costType == NetworkCostType.Unknown
|| costType == NetworkCostType.Unrestricted)
{
//Connection cost is unknown/unrestricted
}
else
{
//Metered Network
}

Recommended way to test for iOS Version specific feature at runtime

I'm targetting IOS 4.3 and 5.0 with an app built against the 5.0 SDK and would like to add support for the Twitter functionality introduced in iOS5 only when the app runs on a iOS5 device. What is the recommended way to reliably test for the availability of these OS features at runtime without having your app crash?
I know you do this using respondsToSelector in Objective-C but how is it done in C#?
With recent MonoTouch versions you can use the following code:
if (UIDevice.CurrentDevice.CheckSystemVersion (5, 0)) {
window.RootViewController = navigation;
} else {
window.AddSubview (navigation.View);
}
Otherwise you can get a string from UIDevice.CurrentDevice.SystemVersion and do some checks with your own code.
Follow up to comments, including mine...
If you want to check by feature you can do something like:
MonoTouch.Twitter.TWRequest req = new MonoTouch.Twitter.TWRequest ();
if (req.Handle == IntPtr.Zero) {
Console.WriteLine ("No Twitter support before iOS5");
}
What happens is that the selector to create the TWRequest instance will return null and the .NET object will be created in an invalid (unusable) state that you can query with the Handle property. Again YMMV, testing is key :-)

Playing Audio in .Net / C#

I'm an experienced MFC programmer of many years, who for the more recent years has been developing commercial apps in Objective C for Mac and iOS - I'm trying to get up to speed with .Net and C# (as I'm soon going to be required to convert one of my commercial apps from Mac to PC).
I've now worked my way through a couple of books and as an exercise to get more familiar with .Net (and C#) I've decided to have a go at converting one of my none commercial apps to .Net as a learning exercise and all is going well (interface is working, data structures all good) but I need to be able to play audio.
My Mac app generates audio from a series of mathematical formula - imagine a wave generator - not quite the same but similar. On the Mac I generate the audio as 16 bit signed raw audio, use Core Audio to setup audio output routing and then get a callback whenever a new buffer of audio is required for the audio routing (so I can generate the audio on the fly).
I need to do the same on the PC. Unfortunately I find MSDN documentation to be a case of "Can't see the wood for the trees" as there is such a vast amount of documentation. I can find classes that will let me load and play mp3/wav etc files, but I need to generate the audio realtime. Can anyone point me in the right direction to find something that will allow me to fill buffers on the fly as it plays them?
Thx
I have used this sample in several projects with good results. It is basically a .Net wrapper for Windows Waveform Audio API using P/Invoke.
Other choices:
NAudio
Sound Player class from .Net framework
I have created a class that can play audio given Stream derivate as an input. So if you are able to pack your sound-generator into the Stream compatible interface, it could be suitable for you.
How I did it - I used unmanaged waveOut* methods from old Windows multimedia API, and handled the playback from there.
Other options - that I am aware of - use waveOut directly, from this: http://windowsmedianet.sourceforge.net/ or write your own DirectShow source filter, but that might be too complicated, since it has to be written in c++.
If you are interested in giving my component a try, I can make it available to you at no charge, since I need it beta tested (I only used it in several of my projects).
EDIT:
Since there are 6 upvotes to the question, I am offering my component free of charge (if you find useful) here: http://dl.dropbox.com/u/10020780/SimpleAudioPlayer.zip
Maybe you can reflect on it :)
I use Audiere to accomplish this and find it works very well.
It's a C++ lib really, but there are a set of bindings available for C#.
For more info, see the question I asked.
You should have a look at FMOD which allows this kind of operation and much more. It is also cross platform which can be interested if you are also working on a mac.
Alvas.Audio has 3 audio players: Player
player.FileName = "123.mp3";
player.Play();
PlayerEx
public static void TestPlayerEx()
{
PlayerEx plex = new PlayerEx();
plex.Done += new PlayerEx.DoneEventHandler(plex_Done);
Mp3Reader mr = new Mp3Reader(File.OpenRead("in.mp3"));
IntPtr format = mr.ReadFormat();
byte[] data = mr.ReadData();
mr.Close();
plex.OpenPlayer(format);
plex.AddData(data);
plex.StartPlay();
}
static void plex_Done(object sender, DoneEventArgs e)
{
if (e.IsEndPlaying)
{
((PlayerEx)sender).ClosePlayer();
}
}
and RecordPlayer
public static void TestRecordPlayer()
{
RecordPlayer rp = new RecordPlayer();
rp.PropertyChanged += new PropertyChangedEventHandler(rp_PropertyChanged);
rp.Open(new Mp3Reader(File.OpenRead("in.mp3")));
rp.Play();
}
static void rp_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case RecordPlayer.StateProperty:
RecordPlayer rp = ((RecordPlayer)sender);
if (rp.State == DeviceState.Stopped)
{
rp.Close();
}
break;
}
}

Categories

Resources