The book of inspiration

February 18, 2009

Extension Method ToChainedFunc

Filed under: c# — zproxy @ 12:10 pm

Lets assume you have a function which takes an offset as input and provides another offset as output.

   97 Func<int, int> ScanSingleResult =
   98     offset =>

I have ommited the actual implementation for clarity’s sake. Now lets assume I will need to the function to be called multiple times each time passing previous output as the next input. For that functionality I will define the following extension method:

   22 public static Func<T, T> ToChainedFunc<T>(this Func<T, T> e, int count)
   23 {
   24     return
   25         value =>
   26         {
   27             var p = e(value);
   28
   29
   30             for (int i = 1; i < count; i++)
   31             {
   32                 p = e(p);
   33             }
   34
   35             return p;
   36         };
   37 }

Now I will be able to chain three subsequent calls to the implementation method with ease like this:

  165 var resultend = ScanSingleResult.ToChainedFunc(3)(headend);
Advertisements

January 22, 2009

SynchronizedCounter

Filed under: c# — zproxy @ 11:13 am

This is a code post. Skip it if you do not read code.

Have you ever wondered how easy would it be to have a simple synchronized counter? This is my version of it.

The value and the date is saved in the registry. It will infer the registry path via these attributes:

    8 assembly: AssemblyTitle
   11 assembly: AssemblyCompany

This is how you would use it in an infinite loop:

  154 var c = new SynchronizedCounter.ResetEachMinute("Index0");
  155
  156     while (true)
  157     {
  158         new { Counter = c.Increment().ToString("000000") }.ToConsole();
  159
  160         Thread.Sleep(1000 + new Random().Next(2000));
  161     }

In Vista and later you will need to add permissions for the program to modify the registry at its location.

synchronizedcounter

The implementation:

   14 internal static class Extensions
   15 {
   16     public static T ToConsole<T>(this T e)
   17     {
   18         Console.WriteLine(e.ToString());
   19
   20         return e;
   21     }
   22
   23
   24     public static string PathCombine(this string[] e)
   25     {
   26         var p = e[0];
   27
   28         for (int i = 1; i < e.Length; i++)
   29         {
   30             p = Path.Combine(p, e[i]);
   31         }
   32
   33         return p;
   34     }
   35
   36     public static TReturn ReadWrite<TReturn, A, B>(this RegistryKey k, Func<A, B, TReturn> h)
   37     {
   38         return InternalReadWrite<TReturn>(k, h);
   39     }
   40
   41     public static TReturn SynchronizedReadWrite<TReturn, A, B>(this RegistryKey k, Func<A, B, TReturn> h)
   42     {
   43         var n = typeof(TReturn).GUID.ToString();
   44         var s = new Semaphore(1, 1, n);
   45         s.WaitOne();
   46         try
   47         {
   48             return InternalReadWrite<TReturn>(k.CreateSubKey(n), h);
   49         }
   50         finally
   51         {
   52             s.Release();
   53             s.Close();
   54         }
   55     }
   56
   57     static TReturn InternalReadWrite<TReturn>(this RegistryKey k, Delegate h)
   58     {
   59         var s = (TReturn)h.DynamicInvoke(
   60             Enumerable.ToArray(
   61                 from p in h.Method.GetParameters()
   62                 let kv = k.GetValue(p.Name)
   63                 let v = kv == null ?
   64                     Activator.CreateInstance(p.ParameterType) :
   65                     Convert.ChangeType(kv, p.ParameterType)
   66                 select v
   67             )
   68         );
   69
   70         foreach (var p in typeof(TReturn).GetProperties())
   71             k.SetValue(p.Name, Convert.ToString(p.GetValue(s, null)));
   72
   73         return s;
   74     }
   75 }
   76
   77 public class SynchronizedCounter
   78 {
   79     /// <summary>
   80     /// Given the last date and value you will need to provide the next value
   81     /// </summary>
   82     public Func<DateTime, int, int> IncrementImplementation;
   83
   84     public SynchronizedCounter(string Name)
   85         : this(Assembly.GetEntryAssembly(), Name)
   86     {
   87
   88     }
   89
   90     public SynchronizedCounter(Assembly SoftwareAssembly, string Name)
   91     {
   92         if (SoftwareAssembly == null)
   93         {
   94             // In design mode we cannot save to registry
   95             Increment = () => 1;
   96             return;
   97         }
   98
   99         this.IncrementImplementation = (Date, Counter) => Counter + 1;
  100
  101         var k = Registry.LocalMachine.CreateSubKey(
  102             new[]
  103             {
  104                 "Software",
  105                 ((AssemblyCompanyAttribute)SoftwareAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false).Single()).Company,
  106                 ((AssemblyTitleAttribute)SoftwareAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false).Single()).Title,
  107                 Name
  108             }.PathCombine()
  109         );
  110
  111         Increment =
  112             () =>
  113                 k.SynchronizedReadWrite(
  114                     (DateTime Date, int Counter) =>
  115                     {
  116                         return new
  117                         {
  118                             Date = DateTime.Now,
  119                             Counter = IncrementImplementation(Date, Counter)
  120                         };
  121                     }
  122                 ).Counter;
  123     }
  124
  125     /// <summary>
  126     /// This function will read the registry, apply the increment implementation, 
  127     /// write to the registry and return the new counter
  128     /// </summary>
  129     public readonly Func<int> Increment;
  130
  131     public class ResetEachDay : SynchronizedCounter
  132     {
  133         public ResetEachDay(string Name)
  134             : base(Name)
  135         {
  136             this.IncrementImplementation =
  137                 (Date, Counter) =>
  138                     Date.Day == DateTime.Now.Day ? Counter + 1 : 1;
  139         }
  140     }
  141
  142     public class ResetEachMinute : SynchronizedCounter
  143     {
  144         public ResetEachMinute(string Name)
  145             : base(Name)
  146         {
  147             this.IncrementImplementation =
  148                 (Date, Counter) =>
  149                     Date.Minute == DateTime.Now.Minute ? Counter + 1 : 1;
  150         }
  151     }
  152 }

December 3, 2008

One cannot have multiple configuration files

Filed under: c# — Tags: , , — zproxy @ 3:33 pm

You really cannot have multiple configuration files, for example each per referenced assembly.

.NET configuration subsystem always uses a single configuration file per AppDomain, and it is very much .exe centric.

What this means is that even though you created separate config file for your library assembly, it will never be picked up — .NET config subsystem will always look at your .exe configuration file for settings.

What you should do is simply put all your configuration options, including Coherence configuration, into your main application’s App.config and remove library configuration file from your solution, as it will never be used.

If you really need to have separate configuration file for the library and want to specify Coherence configuration options there (and there are very few reasons why you would want to do that), you will need to load your class library into a separate AppDomain and specify the config file to use. Take a look at MSDN documentation for AppDomainSetup.ConfigurationFile property for an example on how to do that, but again, that’s probably not what you want to do.

Read more about the architecture over here.

November 2, 2008

ListChangedType.ItemDeletingItem

Filed under: c#, microsoft — Tags: — zproxy @ 8:15 am

ListChangedType.ItemDeleted is useless because ListChangedEventArgs.NewIndex is already gone. As a workaround one would need to maintain a shadow list in order to get a reference to the deleted item.

October 2, 2008

Silverlight: Quake

Filed under: c# — Tags: , , — zproxy @ 8:21 am

Someone at Innoware is working in porting Quake to Silverlight – coolness!

September 30, 2008

ClickOnce apps cannot have refererences to exe

Filed under: c# — Tags: — zproxy @ 12:10 pm

If you add a referenece to a exe in your clickonce application it fails to load. Whats up with that?

January 5, 2008

C# to x86

Filed under: c#, life — Tags: , , , — zproxy @ 12:16 am

There is singularity (wiki) and there is sharpOS at sourceforge. I do not know in what exactly do they differ, but this page might. Both projects are working on a kernel that has been written entirely in C# or its derivate. Neat huh. Someday in the future your application can be run on a computer exclusively with the kernel all alone or inside a browser virtually – all a matter of a few check boxes available under project settings dialog… this sure looks the way it is going… And when will we see routers written in c#? 😀

Andrew shared on OSnews:

Except that Singularity and SharpOS are not that similar. The only thing they have in common are the CLR and C# except Singularity is written in Singh# which is C# with extensions that make writing OS’s in C# possible.

The architecture is different. The three things that stand out are:

– Software Isolated Processes (SIP)
– Contract based Channels
– Manifest Based programs

December 25, 2007

new example: isometric ThreeDStuff, javascript tycoon?

Filed under: c#, dhtml, examples, javascript, jsc — zproxy @ 11:23 pm

This example demostrates how would an isometric javascript game look like in your browser. You can see landscape from Transport Tycoon and the characters are from Wolfenstein 3D and Doom.



Update:

The map is now a little bit larger, you can drag the map around. The dudes can now be selected and ordered to move.

Updated version. And the menu for developers like me. There is also a poll in the openttd forums.

Update: Mentioned by Ondra.

December 16, 2007

new example: worm game

Filed under: c#, examples, javascript, jsc — zproxy @ 1:52 pm


Designed to work with AmiNET110 on your TV.

Pause – P on keyboard or Pause on remote control

Change Zoom Level – Page Up or Down

Enter – To add new apples or respawn

Arrows – Change Direction

December 15, 2007

amino110 remote control example

Filed under: c#, examples, jsc — zproxy @ 8:16 pm


This example shows which button you are pressing on your Amino110 remote control.

December 7, 2007

volta vs jsc

Filed under: c# — zproxy @ 5:00 pm

Just found out that the volta project is now ready for the world to see.

First thought was, yay my jsc project is obselete, but when i looked at the code that volta had produced. It looks like volta uses javascript as msil – still bytecode but now as javascript. See the example project for volta here. A year ago i tried the very same.

Code from volta:

var oA = Assembly.References.cB();var kA = GetTypeDef(oA, "System.Int32");
var kB = GetInstanceDef(oA , "System.Nullable`1", [kA]);
var kC = GetTypeDef(Prelude, "Microsoft.LiveLabs.Volta.Prelude.RuntimeHelpers" );
var kD = GetTypeDef(Assembly, "WordWorm.MyPage");
var lA = GetTypeRef(Prelude, "Microsoft.LiveLabs.Volta .JavaScript.Object");
var lB = GetTypeRef(Prelude, "Microsoft.LiveLabs.Volta.Prelude.TypeDef");
var lC  = GetTypeRef(oA, "System.Object");
var lD = GetTypeRef(oA, "System.Int32");
var lE = GetTypeRef(oA, "System .Void");
var mA = GetMethodDef(kC, "Box", [lA, lB, lC]);
var mB = GetMethodDef(kB, ".ctor", [lD, lE]);
var  mC = GetMethodDef(kC, "Unbox", [lC, lC]);
var mD = GetMethodDef(kC, "OneLevelClone", [lC, lC]);

Code from jsc:

  // NatureBoy.js.Dude2.LookAtMouse
  type$QW1Ihd1VgDy4NHfHDq0FBw.kQAABt1VgDy4NHfHDq0FBw = function (b)
  {
    var a = this, c, d;

    c = new pBcFaqMiojilwt8AVV9H1g();
    c.e = b;
    c.__4__this = a;
    c.h = new ctor$hgMABnJhNza2FzlBzkMp7g(a, 'ogAABt1VgDy4NHfHDq0FBw');
    UAAABnL6FTqbvTbIOm0H5w(c.e, c.h);
    d = new ctor$GQcABllDWDCrMGy9G7lP7Q(c, '_LookAtMouse_b__3');
    return d;
  };

Now with projects like gwt, silverlight, xna, moonlight, flash, script#, operas 3d canvas and google gears it will be very interesting to see where it goes.

And yes, soon I will update the binaries for jsc. They are out of date at the moment and users should use svn.

November 17, 2007

Example: TextScreenSaver

Filed under: c#, dhtml, examples, javascript — zproxy @ 6:49 pm

New example added.

Demonstrates scrolling, zoomable, draggable text and xml serialization support.


November 11, 2007

Javascript 2D Adventure Game Demo

Filed under: c#, games, javascript, jsc — zproxy @ 9:42 am

You can walk around the map. The edges of the screen are doorways to next room. When the character finds an item, he will talk about it.

There is a problem with IE. So it wont display background image. I really have no clue why its like that.. really frustrating. Works with every other browser!

November 4, 2007

Windows.Forms & Vectors in DHTML!!

Filed under: c#, dhtml, examples, jsc — zproxy @ 12:50 pm

Two new examples to release – both are really not there yet. But you can see where the road is going to.

PS. There seems to be some issues with system colors – even deprecated in CSS3 ?

November 3, 2007

Here be dragons!

Filed under: c#, examples, games, jsc — zproxy @ 7:23 pm

Here be dragons!

This weekend me and my girlfriend made some figures from plasticine. Other than that you can now also command a unit from wolf3d and doom. Wheee!

Maybe someday there will be a full blown RTS coming… who knows!:D

NatureBoy – Dragons!
[source:svn]  

November 2, 2007

jsc:js – MonthSchedule

Filed under: c#, examples, javascript, jsc — zproxy @ 4:31 pm

If you just happen to run a store with a few employees and work from clock to clock you need to maintain and create work schedules. Luckily for I have made such a project.

This Application lets you manage the workschedule of your workers. You can add or remove workers on the left, specify how many workers must be present at any given day at the bottom, which days are free days, when to come later and when to go earlier. It also calculates total workhours on the right. You can use your mousewheel or just click on the buttons.

 

MonthSchedule
[source:svn]  

This time it utilizes localization – based on a locals.xml document you can switch between languages.

Localizing your application is now as simple as this: “year”.Localize().

This ScriptApplication was tested with following browsers:

Safari 3.0.3
Opera 9.24
Netscape Navigator 9.0.0.1
FireFox 2.0.0.8
Internet Explorer 7.0

October 14, 2007

duke in your browser

Filed under: c#, dhtml, examples, games, javascript — zproxy @ 1:32 pm

Long time no see. I still have ~8 months to serve in the army.

In the meanwhile visual studio 2008 beta 2 has been released. I have updated the ScriptCoreLib framework, but anonymous types are now not supported due to the internal changes (can be fixed tho).

Also no new binary downloads have been set up – svn has the latest source!

Everybody knows the duke nukem 3d. This time you can move him around your browser. See it for yourself! I am thinking of a free multiplayer RTS duke game. What you think?

NatureBoy – Duke
[source:svn]

June 28, 2007

New Example: MouseWheel

Filed under: c#, dhtml, examples, jsc — zproxy @ 10:28 am

Mousewheel works now with IE, FireFox and Safari. Did you know that each of them use separate event names?

Demo can be found here below.

   

June 27, 2007

New Examples: Google Gears, TextRotator

Filed under: c#, dhtml, examples — zproxy @ 12:42 pm

I have made two new examples. One will display differend qoutes like a typewriter and the other will utilize Google Gears client side database to store information about postcards.

 
 
 
 
 
 
 
 

May 23, 2007

Example: Hot Polygon

Filed under: c#, dhtml, examples, javascript, jsc — zproxy @ 1:26 pm

Yet another example is out of the door. Soon there will be a compiler and framework update, and initial windows forms support will be added. Thats right. You can then write a .net usercontrol that runs both on desktop and on html.

This new example demonstrates the use of custom cursors, map, area, timed animation, cookies and a custom dialog.

Hot Polygon
[source:svn]  

May 13, 2007

Example: Lights out 2

Filed under: c#, dhtml, games, javascript, jsc — zproxy @ 10:22 am

Now with graphics! (By Chris)

Just so you know, the animated background works the best with IE7 instead of mozilla browsers 🙂

Lights Out 2( 20×15)
[source:svn]

How would it look like in 3d? I can think of rotating 2d map but if things go 3d how would one navigate? 🙂

May 6, 2007

example: rollover

Filed under: c#, dhtml, examples, javascript — zproxy @ 1:45 pm

Today i found out that you actually can generate style rules on the fly 🙂

To demostrate what can be done with dynamic styles and png 24’s i have made the following example:

The example works with latest netscape, opera, firefox and ie7. (ie6 will probably crash)

Rollover
[source:svn]  

May 4, 2007

Image Zoomer

Filed under: c#, dhtml, javascript — zproxy @ 12:17 pm

I found this neat example on the web the other day. So I figured it cannot be that hard to do it with jsc:javascript. While doing that i managed to fix a bug in the ScriptCoreLib too!

My version lets you zoom with the wheel! 🙂

 

April 25, 2007

onbeforeunload

Filed under: c#, javascript, jsc — zproxy @ 8:15 am

While scrolling down on the Google reader i found the Ajaxian post about onbeforeunload. To test it out i have made a simple project. It simply asks politely whether or not the user really wants to leave. To see the code look here.

The other unmentioned new example is the filmstrip. You can find its source within the svn.

April 24, 2007

jsc:javascript updated (anonymous types, let keyword)

Filed under: c#, javascript, jsc — zproxy @ 5:51 pm

jsc:javascript now supports c# anonymous types, which means you can now declare anonymous types and use them:)

The following is now able to be translated:

from i in items.Select(i => i.Trim())

where i.ToLower().IndexOf(user_filter) > -1

let xlength = i.Length

select new { i, xlength }

See the demo here. Download updated jsc here.

Also if the type is sealed and its method has no overrides no overloads its original name is now used.

Because of that you can now see javascript like this being generated:

// <>f__AnonymousTypea`2.get_xlength

type$_f71afda4effe4031a75113b83190f181.get_xlength = function ()

{

var a = this, b;b = a.__i__AnonymousTypeFielde;

return b;

};

April 22, 2007

FreeCell, Spider

Filed under: c#, cardgames, dhtml, examples, freecell, jsc — zproxy @ 11:58 am

Update:

These two examples have been ported to run on Windows Presentation Framework.

It took no less than 2 years and 2 months to do so 🙂

Here i present you the card games from the past. They were originally coded within c# at july 2006. Now they are included in the svn 🙂

April 21, 2007

Announcment: ScriptCoreLib.Silverlight interop library.

Filed under: c#, javascript, silverlight — zproxy @ 10:30 am

At the moment silverlight is only scriptable via javascript. I have heard that there are plans to embedd a small CLR with it. If that happens the jsc project has to reevaluate its directions. Until then i began to work with an interop lib, which will allow you to write within c# against silverlight.

See the demo here.The client application source can be found here and the introp library is here.

April 13, 2007

Y combinator within jsc:javascript

Filed under: c#, javascript, jsc — zproxy @ 2:01 pm
  1. See the demo first.
  2. See the source after you read this post.
  3. Download the project template itself if you happen to have visual studio 2005 with linq.

There is an interesting discussion of the use of lambadas over here. And a javascript implementation over here, here and here. And of course more details are at wiki.

In c# you will be able to define a factorial function like this:

  196             var factorial = Lambadas.Y<int, int>(

  197                 fac =>

  198                     n =>

  199                         n <= 2 ? n : n * fac(n – 1)

  200             );

And if you are interested the Y implementation looks like this:

   76         [Script]

   77         public delegate Func<A0, T> YDelegate<A0, T>(Func<A0, T> e);

   82         public static Func<A0, T> Y<A0, T>(this YDelegate<A0, T> le)

   83         {

   84             var me = default(Func<A0, T>); return me = p => le(me)(p);

   85         }

And yes this is carefully written so that my jsc compiler could handle it 🙂

Here is the output in javascript for the factorial method implementation mentioned above:

  // LINQPreviewScriptApplication.js.Class1+<>c__DisplayClass2c.<.ctor>b__1e

  type$_0a0337b105406833892f4a5229521fc0._0a0337b105406833892f4a5229521fc0_600003d = function (b)

  {

    var a = this, c;

    c = ((b <= 2) ? b : (b * a.fac._d6f6e19b927a1a3aab00282efb5d8ed3_60006e0((b – 1))));

    return c;

  };

April 3, 2007

new: jsc:javascript template for orcas

Filed under: c#, javascript, jsc — zproxy @ 3:03 pm

If you happen to have a CTP version of the next Visual Studio codename ‘Orcas’ then this post is for you.

There is a screencast showing off what you could do, a template to download and install, also you could just look at the source code and you see the live demo.

linqtoobjects.png

March 23, 2007

jsc:javascript and active desktop

Filed under: c#, dhtml, examples, games, javascript, jsc, space invaders — zproxy @ 9:17 am

It just occurred to me that jsc:javascript can benefit from the Active Desktop.

So I have decided to make a manual tutorial.

In this short tutorial I will add an active desktop item of the Space Invaders.

Step 1. Right-click on the desktop and select properties.

screen11.jpg

Step 2. Click the button ‘Costumize Desktop’ and select the tab ‘Web’.

screen2.jpg

Step 3. Now click on the ‘New’button and add the location:

screen3.jpg

Step 4. Confirm the action.

screen4.jpg

Step 5. Wait for the synchronization to complete and close the dialogs by clicking on the ‘OK’ or ‘Apply’ button.

screen5.jpg

Step 6. Resize and move the new windows and enjoy the web application on your desktop.

screen6.jpg

This reminds a bit something what Appolo is trying to do doesn’t it?

Now only if I would repeat the steps with other examples:

screen7.jpg

I am also aware that once could do this automatically in the Internet Explorer. It didn’t work on my box at the moment. What a shame.

Older Posts »

Create a free website or blog at WordPress.com.