Skip to main content

How to use C# library from JavaScript in Windows 8

Nu stiu daca v-ati jucat pana acuma cu Windows 8 si Visual Studio 2011, dar o sa aveti o surpriza. Aplicatiile pe care le puteti scrie pentru desktop pot sa fie XAML (impreuna cu C#) sau HTML5 (HTML, CSS, JavaScript).
WinRT (Windows Runtime) ne permite sa avem interoperabilitate intre C++, C#, JavaScript. Este asemanator cu ce era COM+ pe vechiul Windows. Prin intermediul sau putem sa comunicam intre cele trei limbaje. Din punct de vedere tehnicec, WinRT este mult mai simplu decat P/Invoke, avand o sintaxa destul de simpla. Un fisier ".winmd", o sa contina tot API pe care noi il expunem intr-un format destul de asemanator cu cel de .NET.
Metadatele dintr-un ".winmd" descriu codul care a fost scris pentru WinRT. Prin intermediul acestor informatii, putem apela atat API sistemului de operare cat si librarii scrise in alte limbaje de programare. Tot API-ul sistemului de operare pe care noi il accesam din orice limbaj se face prin intermediul WinRT.
Mai jos o sa prezint cum putem sa scriem cod C# care sa fie folosit de JavaScript si ce probleme pot sa apara.
Odata ce am creeat proiectul .NET, putem sa ii schimbam output type-ul la "WinMD". In momentul cand facem acest lucru procesul de build o sa se schimbe putin. Pentru a crea assembly-ul o sa se folosesca un tool cu numele "Windows Metadata Explorer". Odata ce am facut acest pas o sa vedem o multime de warning-uri si erori din cauza ca clasele trebuie sa respecte cateva reguli.
O clasa pe care vrem sa o expunem pentru a putea sa fie consumata de JavaScript trebuie sa fie sealed. Clasele pe care nu dorim sa poata fi consumate de JavaScript trebuie sa aibe atributul [EnableComposition]. Destul de interesant mi se s-a parut ca in cazul in care avem o clasa goala, o sa avem parte de eroare, chiar daca e sealed.
In cazul in care lucrati cu liste (input paramas sau return value), sa nu uitati sa folositi interfete. De exemplu folositi IList si nu List. Partea buna este ca nu suntem obligati sa folosim un array. In cazul in care uitati de acest lucru o sa va treziti cu o eroare de genul:
Method Ex.Foo.GetAll()' has a parameter of type 'System.Collections.Generic.List' in its signature. Although this type is not a valid Windows Runtime type, it implements interfaces which are valid Windows Runtime types. Consider changing the method signature to instead use one of the following types: 'System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyList, System.Collections.Generic.IEnumerable'.
Partea buna este ca mesajul ne da destule informatii despre care este problema si o solutie la aceasta problema. As vrea sa vad mai des erori care ne indica si solutii, nu doar sa urle ca nu e in regula.
Nu incercati sa va definiti interfete generice, clase generice sau metode generice. In acest moment acest lucru nu este suportat in acest moment. Poate din cauza ca notiunea de generic nu exista sau nu are acelasi sens in toata limbajele. Acelasi lucru se intampla si cu metodele declarate virtual. Nu putem sa avem metode virtual.

public sealed Foo
{
    private IList<string> _items;
    public IList<string> GetAll()
{
    return _items;
}
public string DefaultItem { get; set; }
}
Apelurile pe care le putem face pot sa fie atat sincrone, dar si asincrone. In cazul in care vreti sa faceti apeluri asincrone puteti sa folositi Task<...>. Daca incercati sa faceti acest lucru o sa vedeti o eroare din cauza ca Task<...> nu este inclus in WinRT. O solutie la aceasta problema este ca in loc sa returnam Task<...> sa returnam un IAsyncOperation<...>.
Prin intermediul acestuia putem sa facem un apel asincron. Trebuie abut grija deoarece de la developer preview la consumer preview lucrurile s-au schimbat putin. Inainte era folosita metoda urmatoare pentru a crea un nou IAsyncOperation
AsyncFactory.Create(() => { ... } );
Daca incercam sa folosim AsyncFactory o sa ne trezim cu urmatorul mesaj de eroare:
The name 'AsyncFactory' does not exist in the current context
Dar o sa ne trezim ca nu mai putem sa gasim aceast factory. Pentru a putea returna un IAsyncFactory putem sa facem in felul urmator:
return Task.Run<string>( async () =>
{
    return "someString";
}).AsAsyncOperation();
Mai jos puteti sa gasiti codul scris in C# si JavaScript pentru a putea apela cod C# din JavaScript. Nu uitati ca in proiectul care contine JavaScript sa adaugati o referinta la proiectul vostru.
C#
public sealed class Foo()
{
    public IAsyncOperation<string> GetDefault()
    {
        return Task.Run<string>( async () =>
        {
            return "Default"
        }).AsAsyncOperation();
    }
}
JavaScript
var foo = new MyNamespace.Foo();
foo.GetDefault().then(
function(result)
{
    // Do something with result
}
)
In mare am vazut cam ce se poate face. Mi se pare un feature destul de dragut, care in cazul aplicatiilor complexe o sa ne ajute extrem de mult.
Enjoy!

Comments

  1. Interesant :)
    Intrebarea ar fi: cand ai folosi MS JavaScript in loc de C# intr-o aplicatie WinRT, pentru Windows8?

    In rest, nu e vorba de implementarea JavaScript "propriu-zisa" a Mozilla foundation, ci doar de implementarea specifica a Microsoftului (ce se numea JScript, apoi JScript.Net si acum rebotezat JavaScript ca sa ne pacaleasca mai bine), compatibila ECMAScript 5, cu extensiile specifice..

    ReplyDelete
  2. Nu e vorba de MS JavaScript. E vorba de JavaScript pe care il folosesti pe orice pagina HTML. In momentul de fata daca vrei sa faci o aplicatie HTML 5 ai nevoie de JavaScript.
    Din punctul asta de vedere eu visez dupa ECMAScript 3, care ar fi adus OOP-ul mai aproape.

    ReplyDelete
  3. Mai sus am vazut ca vorbesti de WinRT.. Codul ala JavaScript de mai sus, care apeleaza C#, il poti de ex. rula intr-o pagina HTML afisata cu Google Chrome?
    O "aplicatie" HTML 5 ma astept sa ruleze in Firefox pe Linux la fel cum ruleaza pe Windows 8.. :)

    ReplyDelete
  4. @Tudor: Cam asta ar fi punctul meu de vedere legat de HTML5 si Windows 8 http://vunvulearadu.blogspot.com/2012/03/what-is-html5-for-native-windows-8.html

    ReplyDelete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP