Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, December 2, 2013

Create better native UI with Awesomium

awesomium.ui



Source on Github

Create amazing UI the way it should be done... with awesomium.ui.
This is a starter kit for the Awesomium browser based UI and WInform.

Dependencies

Awesomium http://awesomium.com.

Overview

Creating Web UI is easy and fun. With the enormous amount of power built into a modern HTML5 browser, creating fluid rich UI is a breeze.

This is not true when creating Native Application UI. The process is plagued with subtleties that slowly crush developers spirits and ultimately produce projects that take more time and do far less.

Fortunately for us there are ways to bridge the gap between web and native. One of those project is http://awesomium.com/. Awesomium gives you C# wrappers to an underlying Chromium based browser. What does these mean for developers….

All the great features like:

  • CSS3
  • Canvas
  • SVG
  • WebGL
  • WebRTC
  • WebSockets
  • And much more …

You can even run web plugins… think Flash or Unity. Side Note: Awesomium has a Unity3d plugin for Mac/Windows game builds.. also very cool.

Inspiration

Game companies have been doing this for years. Both “Stream” and “Origin” are native browser based UI. The goal with my project is to provide some simple extensions to the Awesomium based libraries that get you up and running fast. Also to provide a good looking UI example … Similar to “Steam” and “Origin”

UI 1

Usage

I have provided a demo project that you can refrence to get you up and running. The basic idea is this:

  • Create a Native Winform project for you solution.
  • Reference

    • Awesomium.Core.dll
    • Awesomium.Windows.Forms.dll
    • awesomium.ui
  • Create a Winform. In my example project I used the default “Forms1.cs”

  • Open the Form1.cs and replace the inherited base class from “Form” to my base class “awesomium.ui.FromBase”
  • Now create a directory in your project called “.appui”

  • Create an html page inside “.appui” directory that has the same name as your Winform. Inside my demo this file was “Form1.html” Make sure to change the “Build Action” for all your html/css/img content to “Content” and “Copy if newer”. This will move the html to your output folder when you build your project.

  • Compile and run the project and you will now have amazing looking UI that has limitless possibilities.

Communication

Communicating with your UI layer is a breeze. This is all done through javascript and json. There are 2 directions for your communication

HTML UI to Native C-Sharp

Inside you javascript create a call like so

ScriptInterface.call('JSMyMethod', 'arg1','arg2');

The first argument is the name of the method in your C# to call. All additional argument are arguments to that function.

On your C# side you would define a method like so:

public void JSMyMethod(string a, string b){
    // do stuff..
}.

C# to HTML javascript

simply use the interface

base.Webbrowser.ExecuteJavascript( "javascript to execute in here" );

Demo Project

UI 2

Friday, November 22, 2013

Neo4J Membership Provider



Neo4JMembershipProvider

asp.net Neo4J Membership Provider

Dependencies

Neo4J Graph Database >= v 2.0.0 (Make sure it has label support)
Neo4JClient https://www.nuget.org/packages/Neo4jClient. NOTE: this package is auto installed as a dependency when you use NuGet

Install

NuGet package https://www.nuget.org/packages/Neo4JMembershipProvider/
This is a step by step install for a new MVC application.
First thing to do is to make sure that you have the latest NuGet installed in your Visual Studio. Again, make sure it is the latest version.
ScreenShot
At this point make sure that you have Neo4J up and running and that you can connect to it. Assuming you have Neo4J installed on your localhost you should be able to connect via your web browser with the address.
http://localhost:7474
If you have everything up and running you should see a screen similar to this one. ScreenShot
Create a new MVC 3/4 web application. Once you are looking at the project files, right click on your refrences and choose "Manage NuGet Packages.."
This will open the NuGet Modal. Select "Online" from your list of sources on the left hand side. Next you can search for "Neo4JMembershipProvider" in the top right search menu.
Once you see the package in the main list. Click the install button.
Verify that the package installed by looking for a green checkmark next to the package. See image as refrence ScreenShot
Now we have to make a few changes to the configuration of our application.
First off we will need to modify our web.config file to include the following lines
<configuration>

  ...

 <connectionStrings>
    <add name="DefaultConnection" connectionString="http://localhost:7474/db/data" providerName="Nextwave.Neo4J.Connector.Neo4JClient" />
  </connectionStrings>
  <appSettings>

    ...

    <add key="enableSimpleMembership" value="false" />
    <add key="autoFormsAuthentication" value="false" />
  </appSettings>
  <system.web>

    ...

    <roleManager enabled="true" />
    <machineKey validationKey="C50B3C89CB21F4F1422FE158A5B42D0E8DB8CB6CDA1742572A48722401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE" decryptionKey="8A9BE8FD22AF6979E7D20198CFEA50DD3D3799C77AF2B722" validation="SHA1" />
    <membership defaultProvider="Neo4JMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add name="Neo4JMembershipProvider" type="Nextwave.Neo4J.Membership.Neo4JMembershipProvider" connectionStringName="DefaultConnection" applicationName="Nextwave" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" />
      </providers>
    </membership>

    ...

</configuration>
I have also included an image with the highlighted changes.
NOTE: that your connection string may need to change to point to your db location ScreenShot
The last thing you need to do is to modify your "InitializeSimpleMembershipAttribute.cs" This is located in your /filters/InitializeSimpleMembershipAttribute.cs
Make the following code changes
  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
  {
      private static SimpleMembershipInitializer _initializer;
      private static object _initializerLock = new object();
      private static bool _isInitialized;

      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
          // Ensure ASP.NET Simple Membership is initialized only once per app start
          LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
      }

      private class SimpleMembershipInitializer
      {
          public SimpleMembershipInitializer()
          {
              try
              {
                  WebSecurity.InitializeDatabaseConnection("DefaultConnection", "User", "Id", "UserName", autoCreateTables: false);
              }
              catch (Exception ex)
              {
                  throw new InvalidOperationException("Something is wrong", ex);
              }
          }
      }
  }
That should be all you need.
You will now be able to start your application and regester / login
Your users will be nodes in neo4J with the "User" label.
So for example you could list all your users with the following Cypher
MATCH u:User RETURN u;

Finally

My solution has only undergone a very small amount of testing.
However, if you have any trouble please contact me and I will be glad to help.
Thanks... and Enjoy the power of your new graph db :)

Tuesday, October 29, 2013

Windows DLL Injection used for good not evil

Dll Injection


Dll Injection is a procedure for "hooking" into an already running peice of codes memory space.  So as to spy on or replace functionality.  This post serves to outline my open source project that demonstrates dll patching.  You can find the source code for this post on GitHub


slimhook

Demonstration of dll injection. As well loading .net runtime and calling .net code. Example hijacking d3d9 dll and altering rendering of games.
This project has 2 goals. The first is to have a simple clean interface for performing DLL injection on a windows shared library. The second is to load and execute your custom code in the .net runtime.
Last this project puts these 2 concepts together an performs a DLL injection on a direct3d video game. It then deals with the d3d driver using the SlimDX framework in .net. In this simple example we turn your triple A PC game graphics into “toon” style shading. Which is to say, we reduce the color space significantly using a technique described here: http://en.wikipedia.org/wiki/Posterization

Requirements:

  • N-CodeHook: http://newgre.net/ncodehook This is included in this project since there is a free license to do what you want with it. N-CodeHook is based on Microsoft detours(http://research.microsoft.com/en-us/projects/detours/).. but is completely free. The main advantage to N-CodeHook is the inline patching takes care of your “trampoline”. More info on this is availabe here: http://newgre.net/node/5
  • SlimDX SlimDX is a free open source framework that enables developers to easily build DirectX applications using .NET technologies such as C#, VB.NET, and IronPython. http://slimdx.org/ You need to goto the site and download the latest 4.0 runtime version of the library in order to run the demo code.

There are 3 projects in the solution.

  • inject.prog (Native C++ dll) This is the native C++ dll that will perform the dll injection on the target process. This is also responsible for loading the .net runtime and registering the function callbacks
  • SlimHook3D (C# .net) This is the code we want to execute in the targeted applications memory space. In the case of this demo we require SlimDX and perform graphics operations on the frame buffer of a hooked video game.
  • WinHookApp (C# ,net) Simple WinForm application that allow you to put in the process ID of the target process. This will then start the dll injection process.

How it works

The WinHookApp includes “System.Runtime.InteropServices” to load the symbols from our inject.dll. This can be seen with the following code
[DllImport("inject.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern int Inject(int pid, StringBuilder amsBase);
Here we are loading the function that takes to parameters. The PID of the process we want to inject and the assembly base for the .net assembly that we want to load.
Once the inject function is called __declspec(dllexport) int WINAPI Inject(int pid, wchar_t* asemblyBase)
We start the process of DLL injection. We intend to inject the same dll we are executing from, namely inject.dll.
We start by getting a handle to the kernel32 lib
HMODULE hKernel32 = ::GetModuleHandle(L"Kernel32");
Next we call OpenProcess on the process we are trying to inject
HANDLE hProcess = ::OpenProcess( PROCESS_ALL_ACCESS,FALSE, pid );
Next we allocate memory inside that process with enouch room to hold the path to this library
pLibRemote = ::VirtualAllocEx( hProcess, NULL, sizeof(szLibPath), MEM_COMMIT, PAGE_READWRITE );
Now we write the path to this lib in the memory we just allocated.
::WriteProcessMemory( hProcess, pLibRemote, (void*)szLibPath, sizeof(szLibPath), NULL );
From here we create a remote thread that will call "LoadLibraryA" passing it the location of the path we just wrote
hThread = ::CreateRemoteThread( hProcess, NULL, 0,(LPTHREAD_START_ROUTINE) ::GetProcAddress( hKernel32,"LoadLibraryA" ),pLibRemote, 0, NULL );
We now should have this dll loaded into the remote process. The next thing we need to do is call a method in our dll. In this case we want to call "HookD3d9". We first get the address of the function.
FARPROC hookProc = ::GetProcAddress( hLoaded,"HookD3d9" );
Now we load the parameters to the function in the same manore that we did before. This parameter will be the base path for the .net dll asembly.
::WriteProcessMemory( hProcess, pLibRemote, (void*)asemblyBase, sizeof(szLibPath), NULL );
We now calculate the offset to our function "HookD3d9" and call the function with passing in the parameter.
DWORD offset = (char*)hookProc - (char*)hLoaded;
myfile<< std::hex << "Offset: " << offset <<std::endl;

  // Call the real action now that we are loaded.  We can not do anything interesting from the dllMain so we need another exprot to call
  DWORD entry = (DWORD)hLibModule+offset;
  myfile<<"Create Remote Thread 2 at entry: "<< std::hex << entry  <<std::endl;
  HANDLE hThread2 = ::CreateRemoteThread( hProcess, NULL, 0,(LPTHREAD_START_ROUTINE)entry, pLibRemote, 0, NULL );
We now will be executing "HookD3d9" inside of the other process.

Loading and running the .NET runtime

I will save this for a future post ....

Tuesday, October 22, 2013

C# FLV byte stream metadata injector

C# FLV byte stream metadata injector

This post relates to my open source project on github. For source code visit me on git flv-streamer-2-file

flv-streamer-2-file

Project takes and FLV stream coming in from a "raw" source, and could be at any point in the "live" stream.
It then saves the FLV to disk and corrects Metadata to allow for seek operations on stream close.
Is this an FLV Metadata injector? Yes. But this one has been written to address some specific needs. Also I think it could be more useful than a lot of the other ones that are out there. Here are some of the major differences:
  • Written entirely in C# (.net)
  • Avoids usage of “unsafe” code.
  • Handles arbitrary file sizes and streams.
  • Memory efficient.
  • Small code base
  • And of course is open source

Overview

This code was developed to accomplish a specific task, but can be adapted to do a number of things to an FLV file.
My goal was to take an FLV stream … and save that stream to disk while still being able to seek inside the file. This means that you can drop out of the stream at any time and the file will contain the portion of content up to that point. The file on disk will contain the total duration and thus be seekable (tested with VLC).
Here is the general idea. I store the FLV header and meta data. I make sure that there are “placeholder” values for the meta data I want. I then write this out to the head of the file we are saving. I then stream the tag data to disk. I also keep a count of audio and video packets… you could also choose to alter timestamps ect…
When the stream errors our or has reached the end. I close the file and then go back in to the head to alter placeholder values. In my case the “duration” or total time of the file in seconds will allow players to now seek in the file.

Usage

The solution consists of 2 projects:
  • FlvStream2File (class library)
  • ConsoleTest (example app)
Compile the FlvStream2File. This is the only project required to use in your application. To use the test app.. simply compile and in a console window you can run:
>ConsoleTest.exe “path to infile.flv” “path to outfile.flv”
This will read in the source FLV and produce an output FLV with the correct duration in the metadata (thus it will allow seek operations)
If you run in the debugger you will also get a lot of useful output via the “Debug.Write” (System.Diagnostics)
Here is an example of how to use the lib.
using(FlvStream2FileWriter stream2File = new FlvStream2FileWriter("out.flv"));
{
  // keep adding bytes to the file (choose a block size)
  while(bytedata){
    stream2File.Write(buffer);
  }

  // finish write and fix flv header.
  stream2File.FinallizeFile();
}

Refrences

Here are some of the features of the more full featured and closed source version of FLV Metadata injector http://www.buraks.com/flvmdi/
Here is some good information around FLV file format
Also you will need to know a little bit about “Action Message Format” (AMF).

Expanding on this

My needs were specific, but the code can be adapted very easily to handle any of the other functions that you see in closed source projects such as FLVMDI

Ideas, Questions, Comments?

Just message me and I will try to help.