Search code examples
c#windowswinformsawesomium

how does the Awesomium JSObject work i can't find an example


I'm using Awesomium WebControl on a Form in C# and i'm trying to pass information into the browser that a USB device has been plugged in i have the USB detection working but for some reason i can't build a JSObject() with the values per device plugged in into it.

Here is the code that is fired when a Device is plugged into the computer

JSObject js_obj;

DriveInfo[] allDrives = DriveInfo.GetDrives();

JSValue[] js_arr = new JSValue[allDrives.Count()];

int count = 0;

foreach (DriveInfo drive in allDrives)
{
    if (drive.IsReady == true)
    {
        if (drive.DriveType == DriveType.Removable)
        {
            js_obj = new JSObject();
            js_obj["Id"] = new JSValue("");
            js_obj["TimeAdded"] = new JSValue("");
            js_obj["DriveLetters"] = new JSValue(drive.VolumeLabel);
            js_obj["Port"] = new JSValue("");
            js_arr[count] = new JSValue(js_obj);
            count++;
        }
    }
}

this.Browser.CallJavascriptFunction("DiskDetector", "DeviceAdded", js_arr);

But when i add a break point at this.Browser.CallJavascriptFunction("DiskDetector", "DeviceAdded", js_arr); js_arr is an array of 4 with where all the values are null

I think the problem is my use of the JSObject and Setting values JSObject Extends IDisposable and i though i would have to all Add("key", "Value"); but the method is not there for me to use


Solution

  • USB drives can sometimes have a DriveType of DriveType.Fixed rather than DriveType.Removable.


    Just to make sure I didn't miss anything, I've also taken your code (minus your Removable condition and referencing drive.Name instead of drive.VolumeLabel to get the actual drive letter) to see if I could get it to work:

    JSObject js_obj;
    
    DriveInfo[] allDrives = DriveInfo.GetDrives();
    
    JSValue[] js_arr = new JSValue[allDrives.Count()];
    
    int count = 0;
    
    foreach (DriveInfo drive in allDrives)
    {
        if (drive.IsReady == true)
        {
            js_obj = new JSObject();
            js_obj["Id"] = new JSValue("");
            js_obj["TimeAdded"] = new JSValue("");
            js_obj["DriveLetters"] = new JSValue(drive.Name);
            js_obj["Port"] = new JSValue("");
            js_arr[count] = new JSValue(js_obj);
            count++;
        }
    }
    
    foreach (var js_val in js_arr)
    {
        if (js_val == null)
            continue;
    
        Trace.WriteLine(js_val.GetObject()["DriveLetters"].ToString());
    }
    

    And it outputs:

    C:\
    S:\
    T:\
    Y:\
    Z:\
    

    As I expect. I'm still not sure why it isn't working for you, but this proves your usage of JSObject is correct.