Archiv

Archive for the ‘C#’ Category

LDAP Verbindung mit C#

2. Dezember 2011 Hinterlasse einen Kommentar

// Kompilieren mit
// C:\Windows\Microsoft.NET\Framework\v3.5\csc.exe /out:ldap.exe /reference:"C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll" LDAPReader.cs   // Benötigt:
// System.DirectoryServices.dll   using System;
using System.DirectoryServices;
using System.IO;   namespace LDAP {   public class Program {   private const string FILE_NAME = "Thiel Michael.txt";
        private const string LDAP_PATH = "LDAP://X500.bund.de/OU=BSIEXTERN,o=Bund,c=de";
        private const string FILTER = "(&(objectClass=person)(cn=Thiel Michael))";   public static void Main(string[] args) {   Console.WriteLine("Verbinde mit " + LDAP_PATH);
            using (var searcher = new DirectorySearcher(new DirectoryEntry { Path = LDAP_PATH, AuthenticationType = AuthenticationTypes.Anonymous }, FILTER)) {
                try {
                    string email = searcher.FindOne().GetDirectoryEntry().Properties["mail"].Value.ToString();
                    Console.WriteLine(email);
                    File.WriteAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), FILE_NAME), email);
                    Console.WriteLine("Die Datei \"" + FILE_NAME + "\" wurde auf dem Desktop geschrieben");
                } catch (Exception e) {
                    Console.WriteLine(e.Message);
                }
            }
            Console.Read();
        }
    }
}
Advertisements
Kategorien:.NET, C#, Code Schlagwörter: , ,

Global System Hooks in C#

16. November 2011 Hinterlasse einen Kommentar

Currently I am programing a shell replacement for Windows 7 with WPF and C#. Low Level hooking to the mouse and keyboard is very simple, but message and shell hooking does not work at all. I did some research (Google) and found out that it is not possible in C#.
Then I found this article:
Using Window Messages to Implement Global System Hooks in C# from ChrisP1118.
He is basically using the Desktop window handle (with the help of SetProp and GetProp) to store the hWnd that is shared between the instances of the callbacks. It works very well. But there is a big problem. It depends on the desktop availability. Which does not exists if I’m using an other shell.
In his article he mentioned that he originally wanted to solve the problem with sharing memory.
Well I took his code and with the big help from
Microsoft I was able to implement memory sharing.

image

OK… I know… even a six years old could have done that… Easy stuff…

Source Code

WilsonGlobalSystemHooksWithSharedMemory_src.zip

Java Events im Vergleich zu C# Events

18. Februar 2011 4 Kommentare

Ich mache hier mal ein Vergleich um zu zeigen, was ich mit unnötige Komplexität und Unübersichtlichkeit meine.

 


Erstellen von Custom Events

Java

Java
1
23
45
    public interface EventCustom extends EventListener
    {        public void fireEvent(EventObject e);
    } 
GeSHi 1.0.8.8
Java
1
23
45
67
89
1011
1213
1415
1617
18
    protected Vector<EventCustom> listenerList = new Vector<EventCustom>();
     public void addEventListener(EventCustom eventListener)
    {        listenerList.add(eventListener);
    }      public void removeEventListener(EventCustom eventListener)    {
        listenerList.remove(eventListener);    }
        private void fireEndOfGame(EventObject e)
    {        for(EventCustom listener: listenerList)
            listener.fireEvent(e);    }
 
GeSHi 1.0.8.8

C#

C#
1
    public delegate void EventCustomHandler(object sender);
GeSHi 1.0.8.8
C#
1
private EventCustomHandler CustomEvent;
GeSHi 1.0.8.8

 


Event aufrufen

Java

Java
1
fireEndOfGame(new EventObject(this));
GeSHi 1.0.8.8

C#

C#
1
if(CustomEvent!=null) CustomEvent(this);
GeSHi 1.0.8.8

 


Listener hinzufügen

Java

Java
1
23
45
67
89
anyObject.addEventListener(new EventCustom()
{    @Override
    public void fireEvent(EventObject e)    {
         // Bla bla bla    }
}); 
GeSHi 1.0.8.8

oder

Java
1
23
45
67
89
    private EventCustom eventCustom = new EventCustom()
    {        @Override
        public void fireEvent(EventObject e)        {
            // bla bla bla        }
    }; 
GeSHi 1.0.8.8
Java
1
anyObject.addEventListener(eventCustom);
GeSHi 1.0.8.8

oder

Java
1
23
45
67
89
1011
1213
1415
public class CustomEvent implements EventCustom
{    private Object sender;
            public CustomEvent(Object sender)
    {        this.sender = sender;
    }            @Override    public void fireEvent(EventObject e)
    {        // bla bla bla
    }}
GeSHi 1.0.8.8
Java
1
private CustomEvent customEvent = new CustomEvent(this);
GeSHi 1.0.8.8
Java
1
anyObject.addEventListener(eventCustom);
GeSHi 1.0.8.8

 

C#

C#
1
anyObject.CustomEvent += AnyObject_CustomEvent;
GeSHi 1.0.8.8
C#
1
23
4
private void AnyObject_CustomEvent(object sender) 
{     // bla bla bla
}
GeSHi 1.0.8.8

oder

C#
1
23
4
this.CustomEvent += delegate(object sender) 
{    // bla bla bla
};
GeSHi 1.0.8.8

 

So… Genug für heute….

Kategorien:.NET, C#, Java Schlagwörter: , , , ,

Game of Life mit C# und WinForms

22. Januar 2011 Hinterlasse einen Kommentar

Diesmal habe ich in C# mit Klassen so gearbeitet wie es im OOP angedacht ist. Die Zellen als Klasse, eine Gruppe der Zellen als Klasse, die Welt als Klasse, der Renderer als Klasse u.s.w…

Es ist lang geworden, da ich noch ein paar Gimmicks eingebaut habe; Zum Beispiel Mutanten und Zombies!

Das Hauptprogramm ist eigentlich schön kurz

C#
1
23
45
67
89
1011
1213
1415
1617
1819
2021
2223
2425
2627
2829
3031
3233
3435
3637
3839
4041
4243
4445
4647
4849
5051
5253
5455
    static class Program
    {        /// <summary>
        /// Der Haupteinstiegspunkt für die Anwendung.        /// </summary>
        [STAThread]        static void Main()
        {            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);              // Create world            World SimWorld = new World();
            SimWorld.GridSize = 18;            SimWorld.Height = 30;
            SimWorld.Width = 40;            SimWorld.LifeAbundancy = 30;
            SimWorld.Zombies = true;            SimWorld.Mutants = true;
            SimWorld.Initialize();              FormWorld mainWindow = new FormWorld(SimWorld);              // Initialize form            mainWindow.FormBorderStyle = FormBorderStyle.FixedSingle;
            mainWindow.MaximizeBox = false;            mainWindow.Height = 600;
            mainWindow.Width = 800;            mainWindow.UseHexagon = false;
            mainWindow.CellBornedColor = Color.GreenYellow;            mainWindow.CellDyingColor = Color.Gray;
            mainWindow.CellLiveColor = Color.LimeGreen;            mainWindow.CellZombieColor = Color.DarkSlateBlue;
            mainWindow.CellMutantColor = Color.Red;            mainWindow.BackgroundColor = Color.PaleGreen;
            mainWindow.RefreshTime = 50;              // Create and init Button            Button btnGo = new Button();
            mainWindow.Controls.Add(btnGo);            btnGo.AutoSize = true;
            btnGo.Text = "Simulation starten";            btnGo.Top = (mainWindow.Height >> 1) - (btnGo.Height >> 1);
            btnGo.Left = (mainWindow.Width >> 1) - (btnGo.Width >> 1);            // Assign Click event
            btnGo.Click += delegate(object sender, EventArgs e)            // I know this is bad... 
            {                btnGo.Visible = false;
                mainWindow.StartSimulation();            };
                        Application.Run(mainWindow);
        }    }
GeSHi 1.0.8.8


Aber die Klassen sind arg lang…

Und so sieht es aus…

Normal

image

Normal in Hexagon Anordnung

image

Mit Zombies

image

Mit Zombies und Mutanten

image

Und der Source Code

C#
1
23
45
67
89
1011
1213
1415
1617
1819
2021
2223
2425
2627
2829
3031
3233
3435
3637
3839
4041
4243
4445
4647
4849
5051
5253
5455
5657
5859
6061
6263
6465
6667
6869
7071
7273
7475
7677
7879
8081
8283
8485
8687
8889
9091
9293
9495
9697
9899
100101
102103
104105
106107
108109
110111
112113
114115
116117
118119
120121
122123
124125
126127
128129
130131
132133
134135
136137
138139
140141
142143
144145
146147
148149
150151
152153
154155
156157
158159
160161
162163
164165
166167
168169
170171
172173
174175
176177
178179
180181
182183
184185
186187
188189
190191
192193
194195
196197
198199
200201
202203
204205
206207
208209
210211
212213
214215
216217
218219
220221
222223
224225
226227
228229
230231
232233
234235
236237
238239
240241
242243
244245
246247
248249
250251
252253
254255
256257
258259
260261
262263
264265
266267
268269
270271
272273
274275
276277
278279
280281
282283
284285
286287
288289
290291
292293
294295
296297
298299
300301
302303
304305
306307
308309
310311
312313
314315
316317
318319
320321
322323
324325
326327
328329
330331
332333
334335
336337
338339
340341
342343
344345
346347
348349
350351
352353
354355
356357
358359
360361
362363
364365
366367
368369
370371
372373
374375
376377
378379
380381
382383
384385
386387
388389
390391
392393
394395
396397
398399
400401
402403
404405
406407
408409
410411
412413
414415
416417
418419
420421
422423
424425
426427
428429
430431
432433
434435
436437
438439
440441
442443
444445
446447
448449
450451
452453
454455
456457
458459
460461
462463
464465
466467
468469
470471
472473
474475
476477
478479
480481
482483
484485
486487
488489
490491
492493
494495
496497
498499
500501
502503
504505
506507
508509
510511
512513
514515
516517
518519
520521
522523
524525
526527
528529
530531
532533
534535
536537
538539
540541
542543
544545
546547
548549
550551
552553
554555
556557
558559
560561
562563
564565
566567
568569
570571
572573
574575
576577
578579
580581
582583
584585
586587
588589
590591
592593
594595
596597
598599
600601
602603
604605
606607
608609
610611
612613
614615
616617
618619
620621
622623
624625
626627
628629
630631
632633
634635
636637
638639
640641
642643
644645
646647
648649
650651
652653
654655
656657
658659
660661
662663
664665
666667
668669
670671
672673
674675
676677
678679
680681
682683
684685
686687
688689
690691
692693
694695
696697
698699
700701
702703
704705
706707
708709
710711
712713
714715
using System;
using System.Drawing;using System.Threading;
using System.Windows.Forms;  namespace GameOfLifeCSharpWinForms{
    static class Program    {
        /// <summary>        /// Der Haupteinstiegspunkt für die Anwendung.
        /// </summary>        [STAThread]
        static void Main()        {
            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);
             // Create world
            World SimWorld = new World();            SimWorld.GridSize = 16;
            SimWorld.Height = 30;            SimWorld.Width = 60;
            SimWorld.LifeAbundancy = 30;            SimWorld.Zombies = true;
            SimWorld.Mutants = true;            SimWorld.Initialize();
             FormWorld mainWindow = new FormWorld(SimWorld);
             // Initialize form
            mainWindow.FormBorderStyle = FormBorderStyle.FixedSingle;            mainWindow.MaximizeBox = false;
            mainWindow.Height = 600;            mainWindow.Width = 800;
            mainWindow.UseHexagon = true;            mainWindow.CellBornedColor = Color.GreenYellow;
            mainWindow.CellDyingColor = Color.Gray;            mainWindow.CellLiveColor = Color.LimeGreen;
            mainWindow.CellZombieColor = Color.DarkSlateBlue;            mainWindow.CellMutantColor = Color.Red;
            mainWindow.BackgroundColor = Color.PaleGreen;            mainWindow.RefreshTime = 400;
             // Create and init Button
            Button btnGo = new Button();            mainWindow.Controls.Add(btnGo);
            btnGo.AutoSize = true;            btnGo.Text = "Simulation starten";
            btnGo.Top = (mainWindow.Height >> 1) - (btnGo.Height >> 1);            btnGo.Left = (mainWindow.Width >> 1) - (btnGo.Width >> 1);
            // Assign Click event            btnGo.Click += delegate(object sender, EventArgs e)
            // I know this is bad...             {
                btnGo.Visible = false;                mainWindow.StartSimulation();
            };                        Application.Run(mainWindow);        }
    }      public class FormWorld : Form     {
        private static World World;        public bool Simulate { get; set; }
        public Color BackgroundColor { set; get; }        public Color CellDyingColor { get; set; }
        public Color CellBornedColor { get; set; }        public Color CellLiveColor { get; set; }
        public Color CellZombieColor { get; set; }        public Color CellMutantColor { get; set; }
        public int RefreshTime { get; set; }          public bool UseHexagon         { 
            get{return World.Cells.HexagonGrid;}            set { World.Cells.HexagonGrid = value; } 
        }          public FormWorld(World world): base()        {
            World = world;        }
         public void StartSimulation()
        {            Simulate = true;
             Graphics g = Graphics.FromHwnd(this.Handle);
            int Generation = 0;              while (Simulate)            {
                this.Invalidate();                Application.DoEvents();
                DrawBuffer(g);                  this.Text = "Generation: " + Generation +                    " Population: " + World.Cells.Population +
                    " Stable Generation: " +                     World.StableGenerationCounter +
                    " Is Stable: " + World.IsStable.ToString();                  Generation++;                if (World.IsStable) Simulate = false;
                 Thread.Sleep(RefreshTime);
            }              g.Dispose();        }
         private void DrawBuffer(Graphics g)
        {            // Create Buffer
            Bitmap Buffer = new Bitmap(this.Width,this.Height);            Graphics BufferGraphics = Graphics.FromImage(Buffer);
             // Draw World Background
            SolidBrush brush = new SolidBrush(BackgroundColor);            BufferGraphics.FillRectangle(brush, 0, 0, 
                this.Width, this.Height);              // Net Pen            Pen pen = new Pen(CellLiveColor);
             // Get center
            float X = (this.Width >> 1) -                 (World.GridSize * World.Width >> 1);
            float Y = (this.Height >> 1) -                 (World.GridSize * World.Height >> 1);
             // Draw the cells
            int CellSize = World.GridSize - 2;              Cell.CellState status;            for (int x = 0; x < World.Width; x++)
            {                for (int y = 0; y < World.Height; y++)
                {                    status = World.Cells[x, y].Status;
                    switch (status)                    {
                        case Cell.CellState.Borned:                             brush.Color = CellBornedColor; 
                            break;                        case Cell.CellState.Dying: 
                            brush.Color = CellDyingColor;                             break;
                        case Cell.CellState.Live:                             brush.Color = CellLiveColor;
                            break;                        case Cell.CellState.Zombies:
                            brush.Color = CellZombieColor;                            break;
                        case Cell.CellState.Mutants:                            brush.Color = CellMutantColor;
                            break;                    }
                    if (status != Cell.CellState.Dead)                    {
                        BufferGraphics.FillEllipse(brush,                             (x * World.GridSize) + X + 
                            World.Cells[x, y].XOffset,                             (y * World.GridSize) + Y, 
                            CellSize, CellSize);                    }
                }            }
            try            {
                // Draw me                g.DrawImage(Buffer, 0, 0);
            }            catch { }
             World.Refresh();
                        pen.Dispose();
            brush.Dispose();            BufferGraphics.Dispose();
            Buffer.Dispose();        }
         protected override void OnPaint(PaintEventArgs e)
        {            if(!Simulate)  base.OnPaint(e);
        }          protected override void OnPaintBackground(PaintEventArgs e)        {
            if(!Simulate) base.OnPaintBackground(e);        }
         protected override void OnClosing(
            System.ComponentModel.CancelEventArgs e)        {
            Simulate = false;            base.OnClosing(e);
        }      }      public class Cell    {
        [Flags]        public enum CellState 
        {             Dead = 2, 
            Borned = 4,             Live = 8, 
            Dying = 16,             Zombies = 32, 
            Mutants = 64,            AllLiving = Borned | Live | Mutants,
            AllDead = Dead | Dying        };
         // Properties
        internal int IsZombie        {
            get            {
                return (Status | CellState.Zombies)                    == CellState.Zombies ?
                    1 : 0;            }
        }          internal int IsMutant        {
            get            {
                return (Status | CellState.Mutants)                    == CellState.Mutants ?
                    1 : 0;            }
        }          private bool IsAlwaysDead = true;          private CellState _status;        public CellState Status
        {             get{ return _status; }
        }          private Cells _parent;        public Cells Parent
        { get { return _parent; } }          private int _x;        public int X { get { return _x; } }
         private int _y;
        public int Y { get { return _y; } }          public float XOffset        { 
            get             {
                if (Parent.HexagonGrid)                    return Y % 2 == 1 ? 
                        Parent.Parent.GridSize >> 1 : 0;                else
                    return 0;            } 
        }          public Cell(Cells parent, int x, int y)        {
            _parent = parent;            _x = x;
            _y = y;              // All Cells are always dead in the beginning            _status = CellState.Dead;
             // All Cells along the sides are always dead...
            // This is just easier to check them for neighbors            // cause no Errors will occure in this case
            if ((X > 0 && X < Parent.Parent.Width-1) &&                (Y > 0 && Y < Parent.Parent.Height-1))
                IsAlwaysDead = false;            else
                IsAlwaysDead = true;        }
         ~Cell()
        {            _parent = null;
        }          internal bool HasAttribute(CellState cellState)        {
            if ((Status & cellState) == cellState)                return true;
            else if ((Status | cellState) == cellState)                return true;
            else                return false;
        }          public void Live()        {
            if (Status == CellState.Dead)            {
                Parent.PopulationInternal++;                _status = CellState.Borned;
            }            else if (Status == CellState.Dying)
            {                Parent.PopulationInternal++;
                _status = CellState.Live;            }
            else if (Status == CellState.Borned)                _status = CellState.Live;
        }          public void Die()        {
            if (Status == CellState.Live ||                Status == CellState.Mutants)
            {                Parent.PopulationInternal--;
                _status = CellState.Dying;            }
            else if (Status == CellState.Borned)            {
                Parent.PopulationInternal--;                _status = CellState.Dead;
            }            else if (Status == CellState.Dying || 
                Status == CellState.Zombies)                _status = CellState.Dead;
        }          public Cell RandomizeLife()        {
            if (Status != CellState.Live)            {
                if (Parent.Randomize.Next(1000) > 500)                {
                    Live();                    return this;
                }                else
                    return this;            }
            else                return this;
         }
         public void RefreshCellStatus()
        {            // skip this if we are "always dead"
            if(IsAlwaysDead) return;              #region Normal Cells            int Neighbors = CountNeighbors(CellState.AllLiving);
                        // Apply Rules
            // No 1. - Birth            if (HasAttribute(CellState.AllDead)
                 && Neighbors == 3)                Live();
             else if (HasAttribute(CellState.AllLiving))
            {                // No. 2 - Lonelyness
                if (Neighbors < 2)                    Die();
                // No. 3 - Live longer 🙂                else if (Neighbors > 1 && Neighbors < 4)
                    Live();                // No. 4 - Overpopulated
                // Mutants dont die on overpopulation                else if (Neighbors > 3 &&
                    Status != CellState.Mutants)                    Die();
            }            else if (Status == CellState.Dying)
                Die();              #endregion              #region Unusual Cells            if (Parent.Parent.Zombies || Parent.Parent.Mutants)
            {                  int ZombieNeighbor =                    CountNeighbors(CellState.Zombies);
                 int MutantNeighbor =
                    CountNeighbors(CellState.Mutants);                  #region Zombie Cells                // This is the Zombie special
                if (Parent.Parent.Zombies)                {
                     // The Zombie get beaten to death
                    // if enough cell are around it                    if (Status == CellState.Zombies &&
                        Neighbors > 3)                        Die();
                    // Dead Cell have a small chance                    // in turning to zombies
                    else if (Status == CellState.Dead)                    {
                        if (Parent.Randomize.Next(1, 1000) > 992)                            _status = CellState.Zombies;
                    }                    // if I am not a zombie and one
                    // of my neighbors is a zombie                    // I have a chance of getting
                    // bitten. The more zombies the higher                    // the chance
                    else if (Status != CellState.Zombies &&                        ZombieNeighbor > 0)
                    {                        if (Parent.Randomize.Next(1, 1000) >
                            (999 >> ZombieNeighbor))                            _status = CellState.Zombies;
                    }                    // if there are too many zombies neighbors
                    // My neighbor will eat me                    else if (Status == CellState.Zombies &&
                        ZombieNeighbor > 4)                        Die();
                     // A Zombie has a chance of dying
                    // if a mutant is one of his neighbors                    // The more mutants the higher the
                    // chance                    if (Status == CellState.Zombies &&
                        MutantNeighbor > 0)                    {
                        if (Parent.Randomize.Next(1, 1000) >                            (700 >> ZombieNeighbor))
                            Die();                    }
                 }
                #endregion                  #region Mutant Cells                // Mutant Cell Special
                if (Parent.Parent.Mutants)                {
                    // A living cell has a chance in                    // turning to a mutant
                    if (Status == CellState.Live &&                        Parent.Randomize.Next(1, 1000) > 800)
                        _status = CellState.Mutants;                    // A mutant cell will die if
                    // there are more than 4                    // zombies around him
                    else if (Status == CellState.Mutants &&                        ZombieNeighbor > 4)
                        Die();                    // A mutant will turn normal if
                    // there are too many Mutants around                    // him
                    else if (Status == CellState.Mutants &&                        MutantNeighbor > 3)
                        _status = CellState.Live;                    // Dead Cells will live if more than 2
                    // Mutants are around                    else if (HasAttribute(CellState.AllDead) &&
                        MutantNeighbor > 2)                    { Live(); Live(); }
                 }
                #endregion            }
            #endregion        }
         private int CountNeighbors(CellState cellStateToCount)
        {            int RetVal = 0;
            if(!IsAlwaysDead)            {
                RetVal += Parent[X + 1, Y].                    HasAttribute(cellStateToCount).ToInt();
                 RetVal += Parent[X, Y - 1].
                    HasAttribute(cellStateToCount).ToInt();                RetVal += Parent[X, Y + 1].
                    HasAttribute(cellStateToCount).ToInt();                  RetVal += Parent[X - 1, Y].                    HasAttribute(cellStateToCount).ToInt();
                 // We are arranging the cells in a hexagon
                // Thats why its less 2 neighbors to check                // But we have to swap neighbors every 2nd
                // line                if (!Parent.HexagonGrid)
                {                    RetVal += Parent[X - 1, Y - 1].
                        HasAttribute(cellStateToCount).ToInt();                    RetVal += Parent[X - 1, Y + 1].
                        HasAttribute(cellStateToCount).ToInt();                    RetVal += Parent[X + 1, Y - 1].
                        HasAttribute(cellStateToCount).ToInt();                    RetVal += Parent[X + 1, Y + 1].
                        HasAttribute(cellStateToCount).ToInt();                }
                else                {
                    if (XOffset > 0)                    {
                        RetVal += Parent[X + 1, Y - 1].                            HasAttribute(cellStateToCount).ToInt();
                        RetVal += Parent[X + 1, Y + 1].                            HasAttribute(cellStateToCount).ToInt();
                    }                    else
                    {                        RetVal += Parent[X - 1, Y - 1].
                            HasAttribute(cellStateToCount).ToInt();                        RetVal += Parent[X - 1, Y + 1].
                            HasAttribute(cellStateToCount).ToInt();                    }
                }            }
            return RetVal;        }
         // Overload the plus operator
        public static int operator +(int number, Cell cell)        {
            return (cell.Status == CellState.Live ||                cell.Status== CellState.Borned)? 
                number + 1 : number;        }
         // Overload the minus operator
        public static int operator -(int number, Cell cell)        {
            return (cell.Status == CellState.Live ||                cell.Status == CellState.Borned) ? 
                number - 1 : number;        }
         // Override ToString
        public override string ToString()        {
            return "Cell " + X + " " + Y + " " +                 Status.ToString();
        }    }
     public class Cells
    {        internal int PopulationInternal { get; set; }
        internal Random Randomize { get; set; }          public int Population { get { return PopulationInternal; } }        public bool HexagonGrid { get; set; }
         private Cell[,] Lifeforms;
        public Cell this[int x, int y]        {
            get { return Lifeforms[x, y]; }            set { Lifeforms[x, y] = value; }
        }          private World _parent;        public World Parent
        { get { return _parent; } }                public Cells(World world)        {
            _parent = world;            Lifeforms = new Cell[Parent.Width, Parent.Height];
            PopulationInternal = 0;              // Populate with cells            for (int x=0; x < Parent.Width; x++)
            {                for (int y=0; y < Parent.Height; y++)
                {                    Lifeforms[x, y] = new Cell(this, x, y);
                }            }
             // Initialize Randomizer
            int Seed;            if (!int.TryParse(
                DateTime.Now.ToString("ffffff"), out Seed))                Seed = DateTime.Now.Second;
            Randomize = new Random(Seed);        }
         // Make sure to kill the cells
        ~Cells()        {
            for (int x = 0; x < Parent.Width; x++)            {
                for (int y = 0; y < Parent.Height; y++)                {
                    Lifeforms[x, y] = null;                }
            }            _parent = null;
        }          // Randomly Populate        public void Populate()
        {            // Calculate abundancy of life
            int Abundancy = ((Parent.Width-2) *                (Parent.Height-2)) * 
                Parent.LifeAbundancy / 100;            // randomly scatter cells
            int RandomY;            while (Abundancy > 0)
            {                for (int x = 1; x < Parent.Width - 2; x++)
                {                    RandomY = Randomize.
                        Next(1, Parent.Height - 2);                    Abundancy -= 
                        this[x, RandomY].                        RandomizeLife();
                }            }
        }    }
     public class World
    {        public Cells Cells { get; set; }
        public int Width { get; set; }        public int Height { get; set; }
        public int GridSize { get; set; }        public int StableGenerations { get; set; }
        public bool Zombies { get; set; }        public bool Mutants { get; set; }
        public int StableGenerationCounter        { get { return StabilityCounter; } }
         private bool _isStable = false;
        public bool IsStable { get { return _isStable; } }          private int _lifeAbundancy = 10;        public int LifeAbundancy
        {            get { return _lifeAbundancy; }
            set            {
                if (value < 0)                    _lifeAbundancy = 0;
                else if (value > 100)                    _lifeAbundancy = 100;
                else                    _lifeAbundancy = value;
            }        }
         public World()
        {            StableGenerations = 10;
        }          public void Initialize()        {
            if (Width < 4) Width = 4;            if (Height < 4) Height = 4;
            if (GridSize < 4) GridSize = 4;            Cells = new Cells(this);
            Cells.Populate();        }
         private int StabilityCounter = 0;
        private int OldPopulation = 0;        public void Refresh()
        {            for(int y=1; y<Height-2;y++)
            {                for(int x =1;x<Width-2 ;x++)
                {                    Cells[x,y].RefreshCellStatus();
                }            }
             if (Cells.Population > OldPopulation - 3 && 
                Cells.Population < OldPopulation + 3)                StabilityCounter++;
            else                StabilityCounter = 0;
             if (StabilityCounter == StableGenerations)
                _isStable = true;              OldPopulation = Cells.Population;        }
    }      internal static class Extensions    {
        public static int ToInt(this bool value)        {
            if(value) return 1;            else return 0;
        }    }
} 
GeSHi 1.0.8.8
Kategorien:.NET, C# Schlagwörter:

Game of Life mit C#

19. Januar 2011 Hinterlasse einen Kommentar

Ich hatte heute mal wirklich Lust darauf gehabt das “Game of Life” in verschiedenen Sprachen zu programmieren.
Angedacht hatte ich Assembler, C bzw. C++, C#, VB.NET, VB6, Turbo Pascal, Java… Vielleicht fallen mir noch andere Sprachen ein, dass ich auf die Schnelle erlernen kann…

Hier der Code für C# … Nicht optimiert…

C#
1
23
45
67
89
1011
1213
1415
1617
1819
2021
2223
2425
2627
2829
3031
3233
3435
3637
3839
4041
4243
4445
4647
4849
5051
5253
5455
5657
5859
6061
6263
6465
6667
6869
7071
7273
7475
7677
7879
8081
8283
8485
8687
8889
9091
9293
9495
9697
9899
100101
102103
104105
106107
108109
110111
112113
114115
116117
using System;
using System.Threading;  namespace GameOfLifeCSharp{
    class Program    {
         private const int FELD_GRÖSSE = 16;
        private const char ZEICHEN_WESEN = '#';        private const int STABILE_GENERATIONEN = 10;
         static void Main(string[] args)
        {            bool[,] felder = new bool [FELD_GRÖSSE, FELD_GRÖSSE];
             // Felder mit leben füllen
            Random randomNumber = new Random(DateTime.Now.Second);                        for (int x = 1; x < FELD_GRÖSSE - 1; x++)            {
                for (int y = 1; y < FELD_GRÖSSE - 1; y++)                    felder[x, y] = 
                        randomNumber.Next(0, 1000) > 500 ?                         true : false;
            }              int nachbarzähler = 0;            int alteanzahl = 0;
            int neueanzahl = 0;            int generationStabilität = 0;
            int generationen=0;              while (generationStabilität < STABILE_GENERATIONEN)            {
                for (int x = 1; x < FELD_GRÖSSE - 1; x++)                {
                    for (int y = 1; y < FELD_GRÖSSE - 1; y++)                    {
                        // Regeln                        // Nachbarn zählen
                        nachbarzähler += felder[x - 1, y] ? 1 : 0;                        nachbarzähler += felder[x + 1, y] ? 1 : 0;
                         nachbarzähler += felder[x, y + 1] ? 1 : 0;
                        nachbarzähler += felder[x, y - 1] ? 1 : 0;                          nachbarzähler += felder[x - 1, y + 1] ? 1 : 0;                        nachbarzähler += felder[x - 1, y - 1] ? 1 : 0;
                         nachbarzähler += felder[x + 1, y + 1] ? 1 : 0;
                        nachbarzähler += felder[x + 1, y - 1] ? 1 : 0;                          // Regel 1                        if (!felder[x, y] && nachbarzähler == 3) 
                            felder[x, y] = true;                        // Regel 2
                        else if (nachbarzähler < 2)                             felder[x, y] = false;
                        // Regel 3                        else if (nachbarzähler > 1 && 
                            nachbarzähler < 4) { }                        // Regel 4
                        else if (nachbarzähler > 3)                             felder[x, y] = false;
                         // anzahl zählen
                        if (felder[x, y]) neueanzahl++;                          nachbarzähler = 0;                    }
                }                  ShowUs(ref felder);                Console.WriteLine("Generation: {0}, Anzahl: {1}", 
                    generationen, neueanzahl);                  if (neueanzahl >= alteanzahl -2 &&                     neueanzahl <= alteanzahl +2)
                    generationStabilität++;                else
                    generationStabilität = 0;                  alteanzahl = neueanzahl;                neueanzahl = 0;
                 generationen++;
                 Thread.Sleep(100);
            }              Console.WriteLine(                "Seit {0} Generationen stabil\nEnter drücken um zu beenden", 
                generationStabilität);            Console.Read();
         }
         private static void ShowUs(ref bool[,] felder)
        {            Console.Clear();
             for (int x = 0; x < FELD_GRÖSSE; x++)
            {                for (int y = 0; y < FELD_GRÖSSE; y++)
                {                    if (felder[x, y])
                        Console.Write(ZEICHEN_WESEN);                    else
                        Console.Write(" ");                }
                Console.Write("\n");            }
        }    }
} 
GeSHi 1.0.8.8
Kategorien:.NET, C# Schlagwörter:

Konsolenprogramme und Parameter-Parser

12. Januar 2011 Hinterlasse einen Kommentar

Es ist eigentlich schade, dass .NET out-of-the-box kein Parser für den Commandline hat. So erfindet jeder das Rad immer wieder neu. Ich habe jetzt Schätzungsweise 1 Milliarde* verschiedene Parser gesehen. Von einfach bis leicht Kompliziert bis hin zu Professionell. Keines davon hat mich so richtig überzeugt. Das Meiste finde ich einfach zu überladen; zu viel unnötiges Zeugs. Deshalb habe ich was eigenes gebastelt. Sehr einfach zu benutzen und gut geeignet für kleinere Programme oder simple Parameterübergaben.

Beispiel:

C#
1
23
45
67
89
1011
1213
1415
16
ParamHandler ph = new ParamHandler();
 ph.Parameters.Add(new ParamHandler.ParamHandlerItems("-path", "Zielordner"));
ph.Parameters.Add(new ParamHandler.ParamHandlerItems("-d", "Alle Bilder downloaden"));ph.Parameters.Add(new ParamHandler.ParamHandlerItems("-url", "Url eingeben"));
 ph.Execute(args);
 ph.Syntax = "[[-path] <string>] [-d] [[-url] ]";
ph.UsageExample = "-url=http://www.google.de/images?q=jigsaw -d -path=C:\temp";  if (ph.Parameters[ph.Help].HasValue)    ph.ShowHelp();
 if (ph.Parameters["-d"].HasValue)...
 
GeSHi 1.0.8.8

 

Source Code:

C#
1
23
45
67
89
1011
1213
1415
1617
1819
2021
2223
2425
2627
2829
3031
3233
3435
3637
3839
4041
4243
4445
4647
4849
5051
5253
5455
5657
5859
6061
6263
6465
6667
6869
7071
7273
7475
7677
7879
8081
8283
8485
8687
8889
9091
9293
9495
9697
9899
100101
102103
104105
106107
108109
110111
112113
114115
116117
118119
120121
122123
124125
126127
128129
130131
132133
134135
136137
138139
140141
142143
144145
146147
148149
150151
152153
154155
156157
158159
160161
162163
164165
166167
168169
170171
172173
174175
176177
178179
180181
182183
184185
186187
188189
190191
192193
194195
196197
198
using System;
using System.Collections.ObjectModel;using System.Collections.Specialized;
using System.Reflection;  namespace ClassPak{
    /// <summary>    /// Vereinfacht die Auswertung von übergebenen Parametern
    /// </summary>    public class ParamHandler
    {        /// <summary>
        /// Die Parameter und die Werte        /// </summary>
        public class ParamHandlerItems        {
            /// <summary>            /// Constructor
            /// </summary>            /// <param name="parameter">Parameter tag<!--param>
            /// <param name="description">Eine kurze Beschreibung des Parameters<!--param>            public ParamHandlerItems(string parameter, string description)
            {                Parameter = parameter;
                Description = description;            }
             /// <summary>
            /// Constructor            /// </summary>
            /// name="parameter">Parameter Tag</param>            public ParamHandlerItems(string parameter)
            {                Parameter = parameter;
            }              /// <summary>            /// Ruft einen Wert ab, das den Tag eines Parametes angibt, oder legt diesen fest. ZB.: -h ode /? oder -?
            /// </summary>            public string Parameter { get; set; }
            /// <summary>            /// Ruft einen Wert ab, das den Parameter kurz beschreibt, oder legt diesen fest.
            /// </summary>            public string Description { get; set; }
             private string _value;
            /// <summary>            /// Ruft einen Wert ab, das den Wert des Parameters angibt, oder legt diesen fest
            /// </summary>            public string Value
            {                get
                {                    return _value;
                }                set
                {                    _value = value;
                    _hasvalue = true;                }
            }              private bool _hasvalue=false;            /// <summary>
            /// Ruft einen Wert ab, das angibt ob der Parameter einen Wert erhalten hat oder nicht            /// </summary>
            public bool HasValue { get { return _hasvalue; } }        }
         /// <summary>
        /// Eine Kollektion der Items        /// </summary>
        public class ParamHandlerItemsCollection : KeyedCollection<string, ParamHandlerItems>        {
            /// <summary>            /// Constructor
            /// </summary>            public ParamHandlerItemsCollection() : base() {}
             /// <summary>
            /// Wird ausgeführt, wenn ein Element über den Schlüssel aufgerufen wird.            /// </summary>
            /// name="item">            /// <returns></returns>
            protected override string  GetKeyForItem(ParamHandlerItems item)            { return item.Parameter; }
         }
         public StringCollection ParametersDefault { get; set; }
         /// <summary>
        /// Die Parameter und deren Werte        /// </summary>
        public ParamHandlerItemsCollection Parameters { get; set; }        /// <summary>
        /// Ruft einen Wert ab, das angibt wie die Parameter benutzt werden kann, oder legt diesen fest.        /// </summary>
        public string UsageExample { set; get; }        /// <summary>
        /// Ruft einen Wert ab, das angibt wie der Syntax lautet, oder legt diesen fest.        /// </summary>
        public string Syntax { get; set; }        private char[] _delimeter = new char[] {'='};
        /// <summary>        /// Ruft einen Wert ab, das angibt welches Zeichen als Trennzeichen zwischen Parameter und
        /// Parameterwert genutzt werden soll, oder legt diesen fest.        /// </summary>
        public char[] Delimeter        {
            get { return _delimeter; }            set { _delimeter = value; }
        }          /// <summary>        /// Standard Parameter für Hilfe
        /// </summary>        private string _help = "--help";
        public string Help        {
            get { return _help; }            set { _help = value; }
        }          /// <summary>        /// Constructor
        /// </summary>        public ParamHandler()
        {            Parameters = new ParamHandlerItemsCollection();
        }          /// <summary>        /// Zeigt eine Vorgefertigte Hilfe Seite an
        /// </summary>        public void ShowHelp()
        {            Assembly assy= Assembly.GetCallingAssembly();
             Console.WriteLine("\n\nNAME\n\t" + assy.GetName().Name + " v" + assy.GetName().Version);
            Console.WriteLine("\n\nDESCRIPTION\n\t" + ((AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(assy,                typeof(AssemblyDescriptionAttribute))).Description);
             if (Parameters.Count > 0)
            {                if(UsageExample.Length>0)
                    Console.WriteLine("\n\nUSAGE EXAMPLE\n\t" +                        System.AppDomain.CurrentDomain.FriendlyName +" " + UsageExample);
                 if (Syntax.Length > 0)
                    Console.WriteLine("\n\nSYNTAX\n\t" +                        System.AppDomain.CurrentDomain.FriendlyName + " " + Syntax);
                 Console.WriteLine("\n\nPARAMETERS");
                 for (int i = 0; i < Parameters.Count; i++)
                {                    Console.WriteLine("\t" + Parameters[i].Parameter.PadRight(18, ' ') + Parameters[i].Description);
                }            }
            Console.WriteLine("");        }
         /// <summary>
        /// Zieht aus den übergebenen Parameterliste die Werte der Parameter heraus        /// </summary>
        /// name="args">Parameterliste -> kommt von Main(string[] args)</param>        public void Execute(string[] args)
        {            //Add help parameter if not already added
            if (!Parameters.Contains(Help))                Parameters.Add(new ParamHandlerItems(Help, "Show help"));
             string[] param;
            foreach (string arg in args)            {
                param = arg.Split(Delimeter, 2);                  if (param.Length == 1 && Parameters.Contains(param[0]))                {
                    Parameters[param[0]].Value = param[0];                }
                else if (param.Length > 1)                {
                    if (Parameters.Contains(param[0]))                        Parameters[param[0]].Value = param[1];
                    else                        throw new Exception("Invalid or unknown Parameter");
                }                else if (arg.Length > 0)
                    ParametersDefault.Add( param[0] );            }
        }      }}
 
GeSHi 1.0.8.8
Kategorien:.NET, C#

SSD, Temporäre Ordner und Ramdisks


Auf SSD müssen ja bekanntlich die Schreibvorgänge auf das Minimum reduziert werden um die Lebensspanne künstlich zu erhöhen. Zusätzlich zu diesen Optimierungen sollte man auch alle temporären Ordner, das sich leider fast jedes Programm selbst festlegt, woanders legen. Am besten in einem RamDisk. Solch ein RamDisk lohnt sich aber erst ab 4GB Arbeitsspeicher, damit man mindestens 1GB abzwacken kann. Empfehlen kann ich aus Erfahrung das kostenlose Programm Dataram RamDisk. Es funktioniert auch auf Windows 7 x64.

Alles was auf dem RamDisk liegt sind natürlich nach dem Neustart weg. Die Ziele der Junctionpoints sind auch weg. Man benötigt also ein Programm, das die Ordner und die Junctionpoints automatisch anlegt.

Das Programm benötigt diese Klasse –> JunctionPoint aus dem Artikel Manipulating NTFS Junction Points in .NET
Die Methode “Delete” habe ich etwas angepasst.


/// <summary>
        /// Deletes a junction point at the specified source directory.
        /// Does nothing if the junction point does not exist.
        /// </summary>
        /// <remarks>
        /// Only works on NTFS.
        /// </remarks>
        /// <param name="junctionPoint">The junction point path</param>
        /// <param name="bDeleteFolder">Delete the specified source directory also</param>
        public static void Delete(string junctionPoint, bool bDeleteFolder = true)

if (bDeleteFolder)
{
    try
    {
        Directory.Delete(junctionPoint);
    }
    catch (IOException ex)
    {
        throw new IOException("Unable to delete junction point.", ex);
    }
}

Eine Liste der Ordner sollte sich unter C:\Windows\ befinden. Der Dateiname sollte lauten “Junction.lst”. Der Inhalt von Junction.lst sollte etwa so aussehen.


C:\Users\%1\Videos\DivX Movies\Temporary Downloaded Files
C:\Users\%1\AppData\Roaming\Macromedia
C:\Users\%1\AppData\LocalLow\DivX\Temporary Downloaded Files
C:\Users\%1\AppData\LocalLow\Microsoft\Silverlight\is
C:\Users\%1\AppData\Local\Temp
C:\Users\%1\AppData\Local\assembly\tmp
C:\Users\%1\AppData\LocalLow\Microsoft\Windows Live\Setup\tmp
C:\Users\%1\AppData\Roaming\Local
C:\Users\%1\AppData\Roaming\Microsoft\Windows\Cookies
C:\Users\%1\AppData\Roaming\Microsoft\Windows\IECompatCache
C:\Users\%1\AppData\Roaming\Microsoft\Windows\IEDownloadHistory
C:\Users\%1\AppData\Roaming\Microsoft\Windows\IETldCache
C:\Users\%1\AppData\Roaming\Microsoft\Windows\PrivacIE
C:\Users\%1\AppData\Local\Opera\Opera\cache
C:\Users\%1\AppData\Local\Opera\Opera\temporary_downloads
C:\Users\%1\AppData\Roaming\Opera\Opera\sessions
C:\Windows\TEMP
C:\ProgramData\Avira\AntiVir Desktop\LOGFILES
C:\ProgramData\Avira\AntiVir Desktop\TEMP
C:\TEMP


%1 wird durch den Anmeldenamen des Benutzers ersetzt. Das Programm unterstützt also mehrere angemeldete Benutzer. Ordner wie “C:\Windows\TEMP” sollte man für alle Freigeben, ansonsten funktioniert das setzen der Junctions nicht.

image

Idealerweise sollte das Programm dann in der Registry im Run eingetragen sein, damit es bei jeder Anmeldung auf jedenfall ausgeführt wird.

Windows x32


HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run


Windows x64


HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run


Übrigens … Der Ramdisk muss RAMDISK heissen, sonst findet das Programm es nicht. Alternativ könnt ihr auch die Konstante RAMDISK_NAME ändern.


using System;
using System.IO;
using Monitor.Core.Utilities; // http://www.codeproject.com/KB/files/JunctionPointsNet.aspx

namespace JunctionLord
{
    class Program
    {
        private const string RAMDISK_NAME = "RAMDISK";

        static void Main(string[] args)
        {
            string junctionListPath = Path.Combine(
                Environment.GetEnvironmentVariable("SystemRoot"), "junction.lst");
            bool bHasError = false;

            if (File.Exists(junctionListPath))
            {
                string[] junction = File.ReadAllLines(junctionListPath);

                // Locate the RAMDISK
                string ramDiskRoot = "";
                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    if (drive.DriveType == DriveType.Fixed && drive.IsReady && 
                        drive.VolumeLabel.ToUpper() == RAMDISK_NAME)
                        ramDiskRoot = drive.RootDirectory.FullName;
                }

                if (ramDiskRoot.Length > 0)
                {

                    string junc;
                    string src;
                    string UserName = Environment.UserName;

                    Directory.CreateDirectory(Path.Combine(ramDiskRoot, UserName));
                    for (int x = 0; x < junction.Length; x++)
                    {
                        junc = junction[x].Replace("%1", UserName);
                        src = Path.Combine(ramDiskRoot, UserName, 
                            System.IO.Path.GetFileName(junc));

                        // create a directory on the RAMDISK - destination dir
                        Directory.CreateDirectory(src);
                        Console.WriteLine(junc + "<-->" + src);

                        // remove old junction if ramdisk root is not the same as last time
                        if (JunctionLord.Properties.Settings.Default.OldPath != ramDiskRoot && 
                            JunctionPoint.Exists(junc))
                            JunctionPoint.Delete(junc, false);

                        // To avoid senseless writing to the SSD, we should only change the
                        // source dir if we needs to
                        if (Directory.Exists(junc) && !JunctionPoint.Exists(junc))
                        {
                            try
                            {
                                DirectoryInfo juncdir = new DirectoryInfo(junc);
                                if (juncdir.GetDirectories("*", SearchOption.TopDirectoryOnly).Length > 0 ||
                                    juncdir.GetFiles("*").Length > 0)
                                {
                                    // Sometimes the source dir cant be deleted
                                    Directory.Delete(junc, true);
                                    Directory.CreateDirectory(junc);
                                }

                                if (!JunctionPoint.Exists(junc))
                                {
                                    JunctionPoint.Create(junc, src, true);
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                                bHasError = true;
                            }
                        }
                    }

                    // Replace old settings
                    if(JunctionLord.Properties.Settings.Default.OldPath != ramDiskRoot) 
                        JunctionLord.Properties.Settings.Default.OldPath = ramDiskRoot;

                }
                else
                {
                    Console.WriteLine("RAMDISK not found");
                    bHasError = true;
                }
            }
            else
            {
                Console.WriteLine("Junction List not found ... It should be in " + junctionListPath);
                bHasError = true;
            }

            if (bHasError)
            {
                Console.WriteLine("Press enter to continue...");
                Console.ReadLine();
            }

        }
    }
}


Oder hier Downloaden

 http://cid-fbf19bfeb328f9cb.office.live.com/embedicon.aspx/Sources/JunctionLord.zip

Kategorien:.NET, C# Schlagwörter: , ,