How to reference WinRT components in Powershell - windows

I'm trying to use the Windows.System namespace, part of WinRT, in PowerShell.
Instead of a dll, the assembly comes as a winmd. The two ways of loading assemblies into PowerShell don't seem to work
#[System.Reflection.Assembly]::LoadFile("C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral\Windows.winmd")
#Add-Type -Path "C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral\Windows.winmd"
I am aware that using Windows API's is a bit trickier than loading my .NET code. I have pinched code for using parts of the win32, would a WinRT solution be similar?
$script:nativeMethods = #();
function Register-NativeMethod([string]$dll, [string]$methodSignature)
{
$script:nativeMethods += [PSCustomObject]#{ Dll = $dll; Signature = $methodSignature; }
}
function Add-NativeMethods()
{
$nativeMethodsCode = $script:nativeMethods | % { "
[DllImport(`"$($_.Dll)`")]
public static extern $($_.Signature);
" }
Add-Type #"
using System;
using System.Runtime.InteropServices;
public static class NativeMethods {
$nativeMethodsCode
}
"#
}
Register-NativeMethod "user32.dll" "int MessageBox (IntPtr hWnd, string text, string caption,int type)"
Add-NativeMethods
[NativeMethods]::MessageBox(0, "Please do not press this again.", "Attention", 0)| Out-Null
My goal is to run Windows.System.Launcher.LaunchFileAsync("C:\file"); in PowerShell. How can I load the WinRT components I need?

To load WinRT binaries into PowerShell use this example:
> [Windows.Data.Json.JsonValue,Windows.Web,ContentType=WindowsRuntime]
> $value = new-object Windows.Data.Json.JsonObject
> $value.Stringify()
{}
I think you will need a StorageFile:
> [Windows.System.Launcher,Windows.Web,ContentType=WindowsRuntime]
> [Windows.System.Launcher]::LaunchFileAsync
OverloadDefinitions
-------------------
static Windows.Foundation.IAsyncOperation[bool] LaunchFileAsync(Windows.Storage.IStorageFile file)
static Windows.Foundation.IAsyncOperation[bool] LaunchFileAsync(Windows.Storage.IStorageFile file, Windows.System.LauncherOptions options)
To create one, you may do something like this:
> [Windows.Management.Core.ApplicationDataManager,Windows.Web,ContentType=WindowsRuntime]
> $value = [Windows.Management.Core.ApplicationDataManager]::CreateForPackageFamily("BackgroundTaskApp_mxmz85hp10cp4")
> $asyncInfo = $value.LocalFolder.CreateFileAsync("foo.txt")
To await *Async() methods, you will need to do something like to create a wrapper.

Related

Get the start and end times of the Focused Window from powershell

I want to get the start time and end time of the Focused Window that is focused through Powershell. The Script used to get the Focused Window is as follows.
Add-Type #"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"#
$a = [tricks]::GetForegroundWindow()
get-process | ? { $_.mainwindowhandle -eq $a }
Now I want the start time when the window is focused and when the control is lost(End time). Thanks in Advance.

How can I get the foreground Window using batch?

I tried to get the foreground Window and write it in a file.
After a few tries, I've only got the task list.
Now I discovered this Code, but it won't work for me:
Add-Type #"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
"#
$a = [tricks]::GetForegroundWindow()
get-process | ? { $_.mainwindowhandle -eq $a }
Thanks :)
The code you have is a Powershell snippet. Save that file as something.ps1 or run it from cmd.exe with this:
powershell something.ps1

Error creating instance of C# class in F# script file

I have the following C# class that I would like to make use of in F#
using System;
using System.Collections.Generic;
using System.Text;
namespace DataWrangler.Structures
{
public enum Type { Trade = 0, Ask = 1, Bid = 2 }
public class TickData
{
public string Security = String.Empty;
public uint SecurityID = 0;
public object SecurityObj = null;
public DateTime TimeStamp = DateTime.MinValue;
public Type Type;
public double Price = 0;
public uint Size = 0;
public Dictionary<string, string> Codes;
}
}
I would like to create an instance of it in F#. The code I am using to do this is in an f# script file
#r #"C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll"
open System
open System.Collections.Generic;
open System.Text;
open DataWrangler.Structures
type tick = TickData // <- mouse over the "tick" gives me a tooltip with the class structure
// it bombs out on this line
let tickDataTest = tick(Security = "test", TimeStamp = DateTime(2013,7,1,0,0,0), Type = Type.Trade, Price = float 123, Size = uint32 10 )
The error I get is:
error FS0193: internal error: Could not load file or assembly 'file:///C:\Users\Chris\Documents\Visual Studio 2012\Projects\WranglerDataStructures\bin\Debug\WranglerDataStructures.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.
I have checked the file paths and they seem to be correct. I can mouse over the 'type tick' and it gives me the structure of the C# object. So It seems to be finding the C# code. Can anyone tell me what I am doing wrong here? Syntax? Still very new to C# -> F# introp
There are several things to check here:
Make sure that fsi.exe is running in a bit mode that is compatible with your WranglerDataStructures.dll. You run fsi.exe as a 64, or 32 bit process by setting a flag in the Visual Studio Options, under F# Tools -> F# Interactive -> 64-bit F# Interactive. You can usually avoid these types of problems by setting your C# assembly to compile as Any CPU.
Make sure that WranglerDataStructures.dll doesn't depend on other libraries that you are not referencing from F#. Either add the references in F#, or remove them from WranglerDataStructures.dll.
If these steps don't yield success try using the fuslogview.exe tool http://msdn.microsoft.com/en-us/library/e74a18c4.aspx to see exactly what reference is not being loaded.

Drag File Warning Extension VS 2010?

I am wondering if anyone knows an extension that pops up a warning if you drag a file to another folder through VS 2010 solution explorer. Many times I will be on a file and my computer may lag for a second and all of a sudden the file is now in some other folder and I may not even notice it.
There is a Visual Studio extension available called VSCommands 2010 which has a feature Prevent accidental Drag & Drop in Solution Explorer.
Edit
The feature is part of the Pro package which is not free.
I don't know of a free Visual Studio extension that would do it, but here is a C# sample of an Addin that demonstrate how to hook into Visual Studio global remove & rename file management. It's based on the IVsTrackProjectDocumentsEvents2 interface.
You would have to extend the two OnQueryxxx methods to suit your needs.
using System;
using System.Diagnostics;
using EnvDTE;
using EnvDTE80;
using Extensibility;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace MyAddin1
{
public class Connect : IDTExtensibility2, IVsTrackProjectDocumentsEvents2
{
private uint _trackerCookie;
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_addInInstance = (AddIn)addInInst;
// the Addin project needs assembly references to Microsoft.VisualStudio.Shell, Microsoft.VisualStudio.Shell.Interop && Microsoft.VisualStudio.OLE.Interop
// any version should do
ServiceProvider sp = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);
IVsTrackProjectDocuments2 tracker = (IVsTrackProjectDocuments2)sp.GetService(typeof(SVsTrackProjectDocuments));
// ask VS to notify us of files & directories changes
tracker.AdviseTrackProjectDocumentsEvents(this, out _trackerCookie);
}
public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)
{
if (_trackerCookie != 0)
{
// we quit, tell VS not to notify us anymore
ServiceProvider sp = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);
IVsTrackProjectDocuments2 tracker = (IVsTrackProjectDocuments2)sp.GetService(typeof(SVsTrackProjectDocuments));
tracker.UnadviseTrackProjectDocumentsEvents(_trackerCookie);
_trackerCookie = 0;
}
}
public int OnQueryRenameFiles(IVsProject pProject, int cFiles, string[] rgszMkOldNames, string[] rgszMkNewNames, VSQUERYRENAMEFILEFLAGS[] rgFlags, VSQUERYRENAMEFILERESULTS[] pSummaryResult, VSQUERYRENAMEFILERESULTS[] rgResults)
{
Trace.WriteLine("OnQueryRenameFiles pProject:" + pProject + " old[0]:" + rgszMkOldNames[0] + " new[0]:" + rgszMkNewNames[0]);
// TODO: implement this (I have assumed cFiles is 1 here)
if (!NotRenameOk(old[0], new[0])
{
rgResults[0] = VSQUERYRENAMEFILERESULTS.VSQUERYRENAMEFILERESULTS_RenameNotOK; // nope, it's not ok
}
return 0;
}
public int OnQueryRemoveFiles(IVsProject pProject, int cFiles, string[] rgpszMkDocuments, VSQUERYREMOVEFILEFLAGS[] rgFlags, VSQUERYREMOVEFILERESULTS[] pSummaryResult, VSQUERYREMOVEFILERESULTS[] rgResults)
{
Trace.WriteLine("OnQueryRemoveFiles pProject:" + pProject + " file[0]:" + rgpszMkDocuments[0]);
// TODO: needs to be implemented, use rgResults to tell VS if it's ok or not
return 0;
}
// other IVsTrackProjectDocumentsEvents2 methods implementation omitted for brevity...

creating and using DLLs in visual studio c#

I have created my first dll using c# and visual studio 2010. I am trying to use it in a program. The dll is in the program directory but visual studio will not allow using myDLL stating that it could not be found. I have also tried adding it as a reference in the solution explorer. What more do I need to do?
Here is one of the files from my class.
namespace nbt
{
class TAG_Long
{
private string name;
private long payload;
public TAG_Long(FileStream f)
{
name = NameTag.SetTagName(f);
byte[] buffer = new byte[(int)dataBytes.TYPE_LONG];
f.Read(buffer, 0, (int)dataBytes.TYPE_LONG);
Array.Reverse(buffer);
payload = BitConverter.ToInt64(buffer, 0);
}
}
}
Try putting your class in a namespace

Resources