Sunday, May 6, 2018

Interop between Unmanaged C++ with Managed C#

Managed C# Code -> ManagedCS.dll ( Assembly)

  • create methods as static public
  • set output path to a location where the ManagedDll.lib can reference during runtime

public static class ManagedClass
    {
        public static void ShowValue(ref int value)
        {
            DialogResult result = MessageBox.Show("C# Message Box", "C# Message Box", MessageBoxButtons.OKCancel);
            if (result == DialogResult.OK)
                value = 1;
            else
                value = 2;
            return;
        }

        public static void PassString(string s)
        {
            MessageBox.Show(s);
        }

        public static void PassImage(byte[] byteArray)
        {
            //byte[] imageBytes = Convert.FromBase64String(base64String);

            MemoryStream ms = new MemoryStream(byteArray, 0, byteArray.Length);

            // Convert byte[] to Image
            ms.Write(byteArray, 0, byteArray.Length);
            Image image = Image.FromStream(ms, true);

            image.Save(@"c:\Out\Out.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        public static void PassFloat(float f)
        {
            Console.WriteLine("F=" + f);

        }
    }




Managed C++ Code -> ManagedDLL.lib


  • cretaed as a CLR class library project  ( /clr)
  • Add reference to managedCS.dll 
  • Create a wrapper class
  • Use Marshall to convert data types before passing to managed code

public ref class DoWork
{
public:void ShowCSharpMessageBox(int *value)
{
ManagedCS::ManagedClass::ShowValue(*value); // call csharp dll
return;
}
public:void PassCSharpString( char *str) 
  {

 
  String  ^s = Marshal::PtrToStringAnsi(static_cast(str) );
  ManagedCS::ManagedClass::PassString(s);

  }
public:void PassCShrapFloat(float value)
{
ManagedCS::ManagedClass::PassFloat(value);
return;
}
  public:void PassCSharpImage(unsigned char str[], int len )
  {
printf("len = %d", len);
  array ^byteArray = gcnew array(len + 2);
  Marshal::Copy( (IntPtr)str, byteArray, 0, len );    
  ManagedCS::ManagedClass::PassImage ( byteArray);

  }

  • export the methods to unmanaged code

__declspec(dllexport) void ShowMessageBox(int *value)
{
ManagedDLL::DoWork work;
work.ShowCSharpMessageBox(value);
}

__declspec(dllexport) void PassString(char *s)
{
ManagedDLL::DoWork work;
work.PassCSharpString(s);
}
__declspec(dllexport) void PassFloat(float f)
{
ManagedDLL::DoWork work;
work.PassCShrapFloat(f);
}
__declspec(dllexport) void PassImage(unsigned char *s, int len)
{
ManagedDLL::DoWork work;
work.PassCSharpImage(s, len);

}


Unmanaged C++

  • Add references to exported methods in code
_declspec(dllexport) void ShowMessageBox(int *value);
_declspec(dllexport) void PassString(char *s);
_declspec(dllexport) void PassFloat(float f);
_declspec(dllexport) void PassImage(unsigned char *s, int len);
  • Add linker input to point to the ManagedDLL.lib

Wednesday, December 4, 2013

Extending a ext4 partition without losing data

umount /boot
parted /dev/sdb
(parted) print
Model: ATA Patriot Torqx 2 (scsi)
Disk /dev/sdb: 32.0GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1 1049kB 12.9GB 12.9GB primary type=83
2 12.9GB 13.0GB 107MB primary ext4 type=83
(parted) rm 2
(parted) mkpart
Partition type? primary/extended? primary
File system type? [ext2]?
Start? 12.9GB
End? 13.4GB
(parted) quit
resize2fs /dev/sdb2
resize2fs 1.42.6 (21-Sep-2012)
Filesystem at /dev/sdb2 is mounted on /boot; on-line resizing required
old_desc_blocks = 1, new_desc_blocks = 2
The filesystem on /dev/sdb2 is now 498688 blocks long

Sunday, July 14, 2013

IEEE 802.3 vs EthernetII

IPv4/6 uses Ethernet II frame format almost exclusively. In 802.3 there must be a LLC/SNAP header to indicate which upper layer protocol to use. The first 20 bytes of both framing format are the same. The differences is

  • 802.3 : uses a 2 bytes length field
  • EthernetII: uses a 2 bytes type field. 


To differentiate between them 802.3 values < 0x0600 (1536), Ethernet II >= 0x0600

802.2 LLC header:

DSAP address SSAP address Control field Information field
8 bits 8 bits 8 or 16 bits N * 8 bits

802.2 SNAP haeder:
LLC SNAP
AA AA 03 00 00 00 08 00
3 octet OUI 2 octet TYPE-field

Wednesday, May 8, 2013

Windows 2008/7 Network Discovery

To allow your computer and shared resources to be visble in network list.
  • Start "Function Discovery Resource Publication"
  • Set Firewall to allow Network Discovery
When you use Network and Sharing Centre-> Change advanced sharing settings
  • To turn on network discovery , Function Discovery  started, SSDP Discovery  started, UPnP device hoststarted

Wednesday, April 10, 2013

Hyper-v management

http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/01/17/allowing-non-administrators-to-control-hyper-v.aspx

Runnning a program as a priviledged user

  1. Using impersonation code:
  2. Uisng App manifest in a .net project :
    • create a new App.Manifest item in project and add
  3. using powershell command to spawn a new process:
    • $password = ConvertTo_SecurityString "password"
    • $cred = New-Object System.Management.Automation.PSCredential("username", $password)
    • start-process process-name -verb RunAs $cred

Wednesday, September 19, 2012

Use C# to get JSON data from the web and map it to .NET class

using Json.net , available through Nuget package
Use C# to get JSON data from the web and map it to .NET class => made easy! - CodeProject

http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm

using native datacontractjsonserializer
http://msdn.microsoft.com/en-us/library/hh674188.aspx


using native .NET JavascriptSerializer

Example code for deserializing the following JSON :

string
res =
@" {
""exhibitions"": [
{
""id"": ""1056"",
""name"": ""Alfa Romeo Sustaining Beauty"",
""admission_fee"": false,
""opened_on"": ""2001-12-01"",
""closed_on"": ""2001-05-31"",
""closed"": false,
""website"": null
},

{
""id"": ""1082"",
""name"": ""Agriculture"",
""admission_fee"": false,
""opened_on"": null,
""closed_on"": null,
""closed"": false,
""website"": http://www.sciencemuseum.org.uk/visitmuseum/galleries/agriculture.aspx
} ] }";

// the class property names must match those JSON names
   
public class Exhibition
{
public int id {get; set;}
public string name { get; set; }
public bool admission_fee { get; set; }
public string opened_on { get; set; }
public string closed_on { get; set; }
public bool closed { get; set; }
public string website { get; set; }
}


public class Response {
public Exhibition[] exhibitions;
}


System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();

Response  list = json.Deserialize(res);


Example code for serializing objects to JSON string

System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
var e1 = new Exhibition { name = "Test1", closed = true };
var e2 = new Exhibition { name = "Test2", id = 456 };
var r = new Response();
r.exhibitions = new Exhibition[2] { e1, e2 };
string s = json.Serialize(r);
 

   

 



 
 

Tuesday, September 18, 2012

A Cloud Storage Programming Interface

The SharpBox API has a bug with Box.Net storage provider see
A Cloud Storage Programming Interface - Store everything - sharpbox - View Issue #16934: BoxDotNet GetRoot(); always returning NULL.

--- sample console application showing how to list , upload and download dropbox and box.net files.
static void Main(string[] args)

{


CloudStorage dropBoxStorage = new CloudStorage();
CloudStorage boxNetStorage = new CloudStorage();

 
//credentials access
 
GenericNetworkCredentials cred = new GenericNetworkCredentials();

cred.UserName =
somebody@somemail.com;

cred.Password =
"somePassword";

 
//access token
ICloudStorageAccessToken accessToken = null;

using (FileStream fs = File.Open("dropbox", FileMode.Open, FileAccess.Read, FileShare.None))

{

accessToken = dropBoxStorage.DeserializeSecurityToken(fs);

}




var dropBoxConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox);
var boxNetConfig = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.BoxNet);



var boxNetstorageToken = boxNetStorage.Open(boxNetConfig, cred);
 
var dropBoxstorageToken = dropBoxStorage.Open(dropBoxConfig, accessToken);
 
var boxNetRoot = boxNetStorage.GetRoot();

var dropBoxRoot = dropBoxStorage.GetRoot();


foreach (var fof in boxNetRoot)

{

Boolean bIsDir = fof is ICloudDirectoryEntry;
 
Console.WriteLine("{0}:{1}", bIsDir ? "DIR" : "FIL", fof.Name);

}


foreach (var fof in dropBoxRoot)
{


Boolean bIsDir = fof is ICloudDirectoryEntry;


Console.WriteLine("{0}:{1}", bIsDir ? "DIR" : "FIL", fof.Name);

}

string tmpFile = Environment.ExpandEnvironmentVariables("%temp%");
 
//Console.WriteLine("Downloading..");


//dropBoxStorage.DownloadFile(dropBoxRoot, "big_file",tmpFile, UploadDownloadProgress);


Console.WriteLine("Uploading..");

boxNetStorage.UploadFile(tmpFile+
"\\big_file", boxNetRoot, UploadDownloadProgress);


Console.WriteLine("Completed");

boxNetStorage.Close();

dropBoxStorage.Close();



}


static void UploadDownloadProgress(Object sender, FileDataTransferEventArgs e)

{


Console.Write("x");

e.Cancel =
false;

}

}

Thursday, July 26, 2012

Windows Network Name and Firewall Profiles

Firewall Profiles are preset inbound and outbound rules on Windows firewall. There are by default 3 profiles: Private Domain and Public.

The Windows Network Location awareness detectes a network by looking quering the presence of default gateway, SSIDs to assign a name to the network. This network name is then associated with firewall profile to protect the connection. If there is no gateway detected on a network interface the network name will be Unidentified Network and you cannot change the firewall profile, it will always be Public.

Internet access detection is by querying a fixed URL
The local security policy Network List Manager Policies can be use to control the changing of network names etc.

Updated : 9/5
On Windows 8, public or private depends on whether file sharing is turn on/off. On->public, off->private

See:
http://technet.microsoft.com/en-us/library/cc753545.aspx
http://www.frostbyte.com.au/Blog/tabid/64/EntryId/9/Windows-7-incorrectly-reports-No-Internet-Access.aspx

Wednesday, July 25, 2012

VMware Host network DHCP service

On host network, the built-in VMware DHCP service, vmnetdhcp.exe is set to run automatically. To disable, use Windows service or comment out the scope in  C:\Users\All Users\VMware\vmnetdhcp.conf

VMware Player boot menu

bios.bootDelay = "5000"
to the VMX file - this will delay the boot by 5 seconds

press ESC to go into boot menu

Monday, July 23, 2012

Creating a default profile in Windows 7

    1. Create a new standard local user account (name it STDPROFILE), add this account to the local Administrators group on the PC.
    2. Reboot, then log onto the PC using the local user account from Step 2.
    3. Set up profile settings as desired; desktop icons, IE home page, etc…
    4. Reboot when finished, log back onto PC with the local “Administrator” account
    5. Double-click “Computer”, then Click Organize, Folder and Search Options. On the View tab, make sure “Show Hidden files, folders and drives” is selected; also uncheck “Hide protected Operating System Files”. Click OK.
    6. Under C:\Users, rename the hidden “Default” user folder (NOT “Default User”)
    • Make a copy of the profile (STDPROFILE) customized in Step 2, rename the folder “Default”.
    • Right-click the folder – under Properties, then Security tab - Add “Everyone” permissions with Full Control (include all folders and subfolders).
    1. Run regedit.exe
    2. Click on HKEY-LOCAL-MACHINE. Under File, select “Load Hive”
    3. Browse to the “C:\Users\Default” folder, click on ntuser.dat (make sure hidden and system files are displayed). Name the key TEMPLATE_ACCOUNT.
    • Right-click on the TEMPLATE_ACCOUNT key, select Export, save the .reg file to the desktop. Open the .reg file with Notepad, and under “Edit – Replace…”, put the user name STDPROFILE in the “Find what:” field, to be replaced with the string %USERNAME% - choose “Replace All” then save the .reg file. Double-click it to re-import the changes.
    1. Re-open regedit.exe (or switch over to it if it’s still open)
    2. Under TEMPLATE_ACCOUNT - Control Panel - Desktop, change “Wallpaper” path to the wallpaper of your choice (a local OR network path will work here). Check other settings and modify any other keys.
    3. If RealPlayer is installed to the image – click on TEMPLATE_ACCOUNT – SOFTWARE – RealNetworks. Delete the entire RealNetworks Key. This key will re-created for each user as they open Realplayer. If the RealNetworks Key is left in, RealPlayer will crash for each user with the message “EXITING APPLICATION”.
    4. When done, click on TEMPLATE_ACCOUNT. Then click File, select “Unload Hive”. This will save the changes you made.