Clear all event logs on Windows using PowerShell
I was bored with the vast amount of data in the eventlogs which were really not useful for me. So, in order to improve readability on my machine I decided to look for something to clear all of the eventlogs. Easy.
Since I always use the Administrative Events filter to view every warning and error I get a lot of junk (who cares for Kernel-Power warnings?)
Since I didn't feel like doing the following steps for each frigging event log there is on my machine. You would need to go to the following steps:
Now this is an excerpt from the eventlogs I have on this machine:
Analytic Application DirectShowFilterGraph DirectShowPluginControl EndpointMapper ForwardedEvents HardwareEvents Internet Explorer Key Management Service MF_MediaFoundationDeviceProxy MediaFoundationDeviceProxy MediaFoundationPerformance MediaFoundationPipeline MediaFoundationPlatform Microsoft-IE/Diagnostic Microsoft-IEDVTOOL/Diagnostic Microsoft-IEFRAME/Diagnostic Microsoft-IIS-Configuration/Administrative Microsoft-IIS-Configuration/Analytic Microsoft-IIS-Configuration/Debug Microsoft-IIS-Configuration/Operational Microsoft-PerfTrack-IEFRAME/Diagnostic Microsoft-PerfTrack-MSHTML/Diagnostic Microsoft-Windows-ADSI/Debug Microsoft-Windows-API-Tracing/Operational Microsoft-Windows-ATAPort/General Microsoft-Windows-ATAPort/SATA-LPM Microsoft-Windows-ActionQueue/Analytic Microsoft-Windows-AltTab/Diagnostic Microsoft-Windows-AppID/Operational Microsoft-Windows-AppLocker/EXE and DLL Microsoft-Windows-AppLocker/MSI and Script Microsoft-Windows-Application Server-Applications/Admin Microsoft-Windows-Application Server-Applications/Analytic Microsoft-Windows-Application Server-Applications/Debug
And so on (for about 10 times as large). I’m not going to clear them by hand.
So let’s call Powershell to the rescue! (Play Thunderbirds theme song!)
First of all (and nothing to do with Powershell): wevtutil
We’re going to use this tool to display every available event source on this machine:
wevtutil el
The help states:
el | enum-logs List log names.
Good, that’s what we need. Next up, we pass every line of this list to a command using a pipe and the Powershell Foreach-Object cmdlet
wevtutil el | Foreach-Object { … commands go here … }
The commands are going to be
wevtutil cl “$_”
The help states:
cl | clear-log Clear a log.
And $_ is the current variable in the enumeration of Foreach-Object. I added the quotes since there are event sources with spaces and we need to have the full name in order to have wevtutil to be able to clear that log.
Now let’s add some diagnostics output to see which one we’re currently clearing:
wevtutil el | Foreach-Object {Write-Host "Clearing $_"; wevtutil cl "$_"}
Now just run it through Powershell, and bam, a clean event log.
Cheers!
Silverlight: I hate “Element is already the child of another Element” (VisualStateManager)
Since I write Silverlight, I love it.
However, since I write Silverlight, I hate the “go to hell error”: “Element is already the child of another Element”.
Of course, this silly error message could be anything:
- A new dependency property with a default value of a different type the the dependency property itself
- An UIElement allready child of a panel added to the children collection of another Panel (yes yes as the message said)
- A cow eating an electric cable on the garden next door, disturbing the electric circuit and making your computer getting mad, and so on…
So what is the best way to debug this? Beside experience and not making any mistake in your code of course… There is none (hem I should think about a post giving tips about it).
However, sometimes you know what’s happening. When this exception is thrown by a call to VisualStateManager.GoToState(…).
In those cases, our mistake is easy to solve, we have somewhere a VisualState step referencing a element by name, and that element simply doesn’t exist in the VisualTree.
There is a easy but very long way to solve this issue, just check all your visual state step with your eyes and have fun hours matching them with your controls.
There is however the lazy geek way to do it
“Why would I do something boring when I can ask my slave computer to do it for me”
My way to solve it is easy: just override the GoToState method in a class who derive the VisualStateManager. Call this class instead of the VisualStateManager to move from one state to the other, and check on the overrited method if every step is correct.
This could be a time consuming method, as a VisualState step can sometimes calls a lot of time the same child of an element by their name.
So to avoid consuming too much time, I store the element matching the names searched by the step in a collection. You can ignore this step, but it may really help you if you have to debug huge VisualStates.
- public interface ISupportDebugerVisualStatManager
- {
- DependencyObject FastGetTemplateChild(string childName);
- FrameworkElement LayoutRoot { get; }
- Dictionary<string, bool> IsVisualStateStepSafe { get; }
- }
- //TODO remove any usage of this SafeVisualStateManager if no more exception is thrown in your app
- /// <summary>
- /// This VisualStateManager is to be used to debug VisualStateManager.GotoState call
- /// and avoid just aving "Element is allready the child of another element" exception
- /// </summary>
- public class SafeVisualStateManager : VisualStateManager
- {
- public new static bool GoToState(Control control, string stateName, bool useTransitions)
- {
- var iControl = control as ISupportDebugerVisualStatManager;
- if(iControl==null)
- throw new InvalidOperationException("SafeVisualStateManager must be used with a ISupportDebugerVisualStatManager only");
- if (!iControl.IsVisualStateStepSafe.ContainsKey(stateName))
- {
- VisualState state;
- VisualStateGroup group;
- if (iControl.LayoutRoot == null)
- return false;
- IList visualStateGroups = GetVisualStateGroups(iControl.LayoutRoot);
- if(visualStateGroups.Count == 0)
- {
- return false;
- }
- if (TryGetState(visualStateGroups, stateName, out group, out state))
- {
- var storyboard = state.Storyboard;
- if (storyboard != null)
- foreach (var child in storyboard.Children)
- {
- string targetName = Storyboard.GetTargetName(child);
- var target = iControl.FastGetTemplateChild(targetName);
- if (target == null)
- {
- iControl.IsVisualStateStepSafe.Add(stateName, false);
- throw new InvalidOperationException("'" + targetName + "' element not found in " + control.GetType());
- }
- }
- iControl.IsVisualStateStepSafe.Add(stateName, true);
- }
- else
- {
- iControl.IsVisualStateStepSafe.Add(stateName, false);
- throw new InvalidOperationException("'" + stateName + "' not found in " + control.GetType());
- }
- }
- return iControl.IsVisualStateStepSafe[stateName] && VisualStateManager.GoToState(control, stateName, useTransitions);
- }
- internal static VisualState GetState(VisualStateGroup vsg, string stateName)
- {
- return vsg.States.Cast<VisualState>().FirstOrDefault(state => state.Name == stateName);
- }
- internal static bool TryGetState(IList groups, string stateName, out VisualStateGroup group, out VisualState state)
- {
- foreach (var group2 in groups.OfType<VisualStateGroup>())
- {
- VisualState state2 = GetState(group2,stateName);
- if (state2 != null)
- {
- group = group2;
- state = state2;
- return true;
- }
- }
- group = null;
- state = null;
- return false;
- }
- }
Beside that, for your interest, here in one of my implementation of ISupportDebugerVisualStatManager:
- #region ISupportDebugerVisualStatManager
- public FrameworkElement LayoutRoot { get; set; }
- private readonly Dictionary<string, bool> isVisualStateStepSafe = new Dictionary<string, bool>();
- public Dictionary<string, bool> IsVisualStateStepSafe
- {
- get { return isVisualStateStepSafe; }
- }
- internal Dictionary<string, FrameworkElement> searchedChild = new Dictionary<string, FrameworkElement>();
- public DependencyObject FastGetTemplateChild(string childName)
- {
- if (!searchedChild.ContainsKey(childName))
- searchedChild.Add(childName, GetTemplateChild(childName) as FrameworkElement);
- return searchedChild[childName];
- }
- public override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
- LayoutRoot = GetTemplateChild("Root") as FrameworkElement;
- }
- #endregion
Of course this way to debug the VisualStateManager will still be much more slower then the actual VisualStateManager, so use it with caution, only in debug mode, not when you release the application.
I hope this could safe the life of some of you, as it already safe mine multiple times.
Cheers!
Having trouble with opening Silverlight 3 apps in Visual Studio 2010?
If you are like me, you probably have uninstalled the Silverlight 3 SDK. I don’t use it, and I like to keep my computer clean.
The problem I had was that I tried to open an old Silverlight 3 project in Visual Studio 2010.
Visual Studio launched the converter but the conversion failed.
The output window displays this:
C:\Users\Kristof Mattei\Desktop\SilverlightTable\SilverlightTable.csproj : error : Unable to read the project file 'SilverlightTable.csproj'.
C:\Users\Kristof Mattei\Desktop\SilverlightTable\SilverlightTable.csproj(126,3): The imported project "C:\Program Files\MSBuild\Microsoft\Silverlight\v3.0\Microsoft.Silverlight.CSharp.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
(emphasis mine).
As you can see it tries to load Silverlight 3, which we (me) kicked out.
Right click the unavailable project and select ‘Edit <nameofproject.csproj>`.
Now edit the TargetFrameworkVersion property from v3.0 to v4.0.
Now reload the project.
Of course you can run into bugs because of things that are gone in Silverlight 4 or have changed, but at least you can LOOK at the contents of the project now ![]()
Cheers!
WP7– Dofuscator free
Did you know?
MS and PreEmptive offer a free licence of dofuscator to all WP7 dev on the app hub ![]()
Find out more about this program on the PreEmptive Solutions website page for Windows Phone.
Finding assembly version mismatch
Last week I had an issue in MEF, but it could happen in many other situations.
This issue is simple: I was referencing in a project 2 framework libraries, and each of those libraries were referencing the same assembly, but not of the same version.
heuu ??? Ok this will need a nice picture:
![]()
.Where(“Tool assembly” should be of the same version). Better?
So of course, my project was compiling (due to MEF usage) but crashing when trying to compose the application.
As a good geek (and as I had the control on the two framework source code but not on the MEF composer) I had a few solution to solve this:
- Matching the version of each assembly with my eyes on windows explorer… long long work if we have a lot of assemblies
- Searching on the web after a program made by another geek somewhere in the world who will solve this issue for me and tell me witch assembly I should update to make my project work fine. This involve searching on the web, downloading a prog, trying to understand how it work and praying it work fine.
- Coding some line of code in my already opened visual studio.
As you can guess, the last solution was mine ![]()
So here it is for you, if you find yourself in the same situation as me and even more lazy, you will just have to copy past this sample:
- static void Main(string[] args)
- {
- Console.WriteLine("Dir Path 1: ");
- var dirPath1 = Console.ReadLine();
- Console.WriteLine("Dir Path 2:");
- var dirPath2 = Console.ReadLine();
- if (string.IsNullOrEmpty(dirPath1) || !Directory.Exists(dirPath1) ||
- string.IsNullOrEmpty(dirPath2) || !Directory.Exists(dirPath2))
- {
- Console.WriteLine("Can't find one of the both directory");
- }
- else
- {
- var files1 = Directory.GetFiles(dirPath1,"*.dll").Select(f=>f.Replace(dirPath1+"\\",""));
- var files2 = Directory.GetFiles(dirPath2, "*.dll").Select(f => f.Replace(dirPath2 + "\\", ""));
- var filesToCheck = files1.Intersect(files2);
- foreach(var fileToCheck in filesToCheck)
- {
- var file1 = FileVersionInfo.GetVersionInfo(Path.Combine(dirPath1, fileToCheck));
- var file2 = FileVersionInfo.GetVersionInfo(Path.Combine(dirPath2, fileToCheck));
- Console.ForegroundColor = file1.FileVersion != file2.FileVersion ?
- ConsoleColor.Red : ConsoleColor.Gray;
- Console.WriteLine("{0}\t{1}\t{2}", fileToCheck, file1.FileVersion, file2.FileVersion);
- }
- }
- Console.WriteLine("Press a key to exit");
- Console.Read();
- }
Enjoy ![]()
Microsoft.Xna.Framework.Audio and Windows 7 KN boum
Today, and since a few month, I’m spending some time having fun with XNA for WP7. But since a few month also, I avoid using sound in my new games because the audio framework of XNA doesn’t want to compile on my windows. FML
Of course, I did search on internet for solution, to understand what’s the difference between my windows and others, etc. And I allways found the solution about installing the windows media pack for windows N.
So I tried, multiple times, to install this http://www.microsoft.com/downloads/en/details.aspx?FamilyID=31017ed3-166a-4c75-b90c-a6cef9b414c4
And the installation went good, my computer restarted, then, each time, rollback the install for compatibility issues…
Then I bought my WP7, great phone, very handy to sync with your computer, as long as you can install Zune (of course). Zune, the kind of programs that Windows KN family can’t install.
So FML, and so could I though : FMXNA, FM!ZUNE and FMWP7 ![]()
But today, my life became like a small cloudy mini golf in heaven when I found this http://www.microsoft.com/downloads/en/details.aspx?FamilyID=13BEB697-E897-40A8-81B5-C20A0529F599
All my problems are now solved. If you have the same issue then me: remember to install the “Media Format Feature Pack for Windows 7 N with Service Pack 1 and Windows 7 KN with Service Pack 1 (KB968211)” and not the “Media Feature Pack for Windows 7 N with Service Pack 1 and Windows 7 KN with Service Pack 1 (KB968211) “
I hope this post will save the life of many. ![]()
The Truth table nightmare
Along my coding across many project I realised that implementing a truth table is always something either messy, either non easily scalable.
For those of you how wonder what the hell I’m speaking about, a truth table is just a table with one or multiple input condition and one or multiple output value.
For instance, here is the truth table for the && operator in c#:
| A | B | A && B |
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
Of course, this is an easy one, which you will code just by using the (A && B) bool.
But a truth table can be much more complex, using many many input operators. Across my code traveller adventure I saw two valid implementation of those kind of truth table.
The first one is the most easy to understand. The coder will just make one if then else at a time, putting them on into the other, like those Russian puppet.
I like to call this method of coding a Truth Table, the “Matroska If Then Else” method.
As coding the && c# operator table would be silly, let’s take another more complex Truth Table as example for our following samples:
| Input Values | Output | ||
| TRUE | Orientation.X | Male | 150 |
| TRUE | Orientation.X | Female | 321 |
| TRUE | Orientation.Y | Male | 587 |
| TRUE | Orientation.Y | Female | 235 |
| FALSE | Orientation.X | Male | 125 |
| FALSE | Orientation.X | Female | 369 |
| FALSE | Orientation.Y | Male | 147 |
| FALSE | Orientation.Y | Female | 152 |
As you can see, in this TT we don’t use only bool, but also some others type of data. But anyway, those kind of data can be easily converted to a double using a equality method.
In a “Matroska If Then Else” way, this would be the code:
- public int MatroskaIfThenElse(bool input1, Orientation input2, Gender intput3)
- {
- if(input1)
- {
- if(input2 == Orientation.Horizontal)
- {
- if (intput3 == Gender.Male)
- return 150;
- else // (intput3 == Gender.Female)
- return 321;
- }
- else // (input2 == Orientation.Vertical)
- {
- if (intput3 == Gender.Male)
- return 587;
- else // (intput3 == Gender.Female)
- return 235;
- }
- }
- else // (!input1)
- {
- if (input2 == Orientation.Horizontal)
- {
- if (intput3 == Gender.Male)
- return 125;
- else // (intput3 == Gender.Female)
- return 369;
- }
- else // (input2 == Orientation.Vertical)
- {
- if (intput3 == Gender.Male)
- return 147;
- else // (intput3 == Gender.Female)
- return 152;
- }
- }
- }
However, with a few cleaning of the code, this sample could have been made easier, but I wanted to highlight the complexity of such a method.
It’s easy to write, fast to execute, but really, if you start having more then 5 input parameters, you’ll soon fall into a hell of a code, impossible to manage and update.
A second way to write those kind of Truth Table, when, and only when, the output value is only a bool (or a set of two value only that can be translated to a bool) is to use the Logical connective to condensate it into one single Boolean expression.
This is really a perfect way to make your application preferment, but be sure that if you exceed 3 or 4 input values again, none of the following coders who will come to update your code will be able to do it in 5 min.
Doing this, you are actually going a step deeper in the machine language, going away from the sacral abstraction of language that c# and modern programming language try to achieve.
So? Will you ask: what is your solution?
My point of view is easy: “If I have a truth table on paper, why can’t I write it in my application.”
To do so, I decided to have a dictionary of Key/value where my Key would be an object containing a set of input value, and my value would be the output value of my Truth Table:
- public class TruthTable<TPredicate, TResult> : Dictionary<TPredicate, TResult>
- where TPredicate : IComparable
- {
- public TResult Match(TPredicate predicate, TResult fallBackValue)
- {
- return !ContainsKey(predicate) ? fallBackValue : this[predicate];
- }
- }
I like to call this method the “True Truth Table” method
Using it require to create your own container object to represent the input set of value. In this case:
- internal class TruthTableItem : Tuple<bool, Orientation, Gender>
- {
- public TruthTableItem(bool i1, Orientation i2, Gender i3)
- : base(i1, i2, i3)
- {
- }
- public override bool Equals(object obj)
- {
- var other = obj as TruthTableItem;
- return other != null && (other.Item1 == Item1 && other.Item2 == Item2 && other.Item3 == Item3);
- }
- public override int GetHashCode()
- {
- return Item1.GetHashCode() ^ Item2.GetHashCode() ^ Item3.GetHashCode();
- }
- }
Then you are ready to eye-hand-copy-past your truth table from your flying paper to your code:
- private static readonly TruthTable<TruthTableItem, int> TruthTable =
- new TruthTable<TruthTableItem, int>
- {
- {new TruthTableItem(true, Orientation.Horizontal, Gender.Male), 150},
- {new TruthTableItem(true, Orientation.Horizontal, Gender.Female), 321},
- {new TruthTableItem(true, Orientation.Vertical, Gender.Male), 587},
- {new TruthTableItem(true, Orientation.Vertical, Gender.Female), 235},
- {new TruthTableItem(false, Orientation.Horizontal, Gender.Male), 125},
- {new TruthTableItem(false, Orientation.Horizontal, Gender.Female), 369},
- {new TruthTableItem(false, Orientation.Vertical, Gender.Male), 147},
- {new TruthTableItem(false, Orientation.Vertical, Gender.Female), 152},
- };
- public int TrueTruthTable(bool i1, Orientation i2, Gender i3)
- {
- return TruthTable.Match(new TruthTableItem(i1, i2, i3), 0);
- }
This way is much easier to manage, to update, even to understand as long as the coder doesn’t deep dive the details.
If a business man want to change the output result for “TRUE
Orientation.Y
Female” to 5000, this can be done in top 20 seconds.
Of course, this method may be slower to run then the two other as we create at least one object containing the different input value, but this could be optimized a bit by directly using the combined hash code of all input value.
Anyway, a dictionary is using an hash set / hash table / call it with the good name if you wish, but it’s kind of a fast stuff. So as long as you don’t call this method 5 million times a second, it shouldn’t affect your application.
What do you think about it? Any idea, improvement to propose? Feel free tor comment!
WP7 XNA: Handle Back button
Nothing very hard here, but tonight I was playing with XNA on WP7 and did wonder how the hell I could handle a click on the Back button from my phone and avoid my game to exit to the wp7 home page each time I click it.
As I’m use to Silverlight I was searching for any method to override on my game, but in fact, it’s even more easy.
On the currently displayed DrawableGameComponent we just have to check the state of the GamePad during the Update method.
public override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { //insert your code here } }
I just lost my time because for me the button was not a GamePad, but anyway it make sense in XNA.
Cheers! ![]()
Visual Studio 2010 SP1: DebuggerTypeProxy works again! *yay*
A while ago I bumped into a bug in Visual Studio 2010 + Silverlight 4.
While working with a List / Dictionary / … it didn’t show the items in the list, instead it showed the normal ‘raw view’:
As you can see, there was no view to see the items.
What you would expect to see is this:
I reported the bug (many others did too!). The problem was that it was fixed in SL3, but not ported to SL4.
Now it’s fixed! This makes my work a lot easier. When we get SP1 @ work too that is!
Cheers!
.NET natural sort, a possible solution.
You have a list of items, let’s say 20 elements, starting at 1, until 20 (inclusive). We shuffle the list and we try to sort it.
- List<string> normalDotNetSort = GiveMeANewList();
The code to create the list:
- private static List<string> GiveMeANewList()
- {
- List<string> list = new List<string>();
- for (int i = 1; i <= 20; i++)
- {
- list.Add(string.Format("{0}", i));
- }
- return list.MixList();
- }
MixList just shuffles the list.
We’re using a normal Generic List and to sort, let’s use the Sort method, and write it to the console:
- normalDotNetSort.Sort();
- normalDotNetSort.ForEach(Console.WriteLine);
What would be the result?
.
.
.
.
.
.
.
.
.
.
.
.
.
1
10
11
12
13
14
15
16
17
18
19
2
20
3
4
5
6
7
8
9
That’s not what we wanted, but it is what we told the code to do. It first sorts on the first character, and then on the second (and so on…). That’s why 19 takes precedence of 2, since 1 < 2.
How do we fix this?
There is a little gem in the shlwapi.dll, namely StrCmpLogicalW. Since this is a native function we need to do a DllImport to expose the function to our C# code:
- public static class SafeNativeMethods
- {
- [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
- public static extern int StrCmpLogicalW(string psz1, string psz2);
- }
Now we can use this function in our own string comparer:
- public sealed class NaturalStringComparer : IComparer<string>
- {
- #region IComparer<string> Members
- public int Compare(string x, string y)
- {
- return SafeNativeMethods.StrCmpLogicalW(x, y);
- }
- #endregion
- }
And use this comparer to sort our list:
- List<string> interopSort = GiveMeANewList();
- interopSort.Sort(new NaturalStringComparer());
- interopSort.ForEach(Console.WriteLine);
And the result:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Much better no?