DCSIMG
July 2008 - Posts - Pavel's Blog
Sign in | Join | Help

Pavel's Blog

Pavel is a software guy that is interested in almost everything
software related... way too much for too little time

July 2008 - Posts

Friend Assemblies

Published at Jul 31 2008, 08:10 AM by pavely

One of my students sent me this question by email:

"Say we have a DAL layer assembly and a BL layer assembly. Each BL class is responsible for saving one entity – let’s call one of the entities ‘X’.

Since the BL uses the DAL to perform the actual save operation, the XDAL.save(x) must be public.

This way, we can’t force the developer to go through BL.save(x) and it can be bypassed – calling XDAL.save directly (skipping validation part for example).

It can be solved in some nasty way… But we heard there might be something helpful in .Net 3.5 that might cover this need (something like ‘friend’ in C++)"

In a nutshell, when we use an internal (C#) type, no other assembly can use it. If we use public, any assembly can use it. How can we allow internal types to be visible to certain assembly(ies)?

One solution to this issue is the concept of Friend Assemblies (supported from .NET 2.0). Using the InternalsVisibleToAttribute attribute (specified on the assembly itself), we can indicate which assemblies can have access to this assembly's internal types.

Some "Less Famous" but Useful LINQ Operators

Published at Jul 20 2008, 09:25 AM by pavely

LINQ has many operators, but some get more attention than others. The most famous are the ones which can be expressed in a from clause, such as Where, OrderBy, OrderByDescending, GroupBy and Select. However, many other operators exist - here's my favorite list:

Intersect, Union, Except

These operators are the set operators intersection (AND), union (OR) and difference.

The Intersect operator returns the items that are present in both sequences as a new sequence. Here's an example:

var list1 = new List<int> { 2, 4, 9, 11, 3, 6 };
var list2 = new List<int> { 3, 8, 4, 30, 9, 16 };

var newlist = list1.Intersect(list2);

The result is 4, 9, 3 as the common elements.

Union returns all elements present in both sequences:

newlist = list1.Union(list2);
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

The returned result is 2, 4, 9, 11, 3, 6, 8, 30, 16.

Except returns the difference in the sets, i.e. the elements in list1 except those that exist in list2 and list1:

newlist = list1.Except(list2);
The result is 2, 11, 6.
 

First, FirstOrDefault, Last, LastOrDefault

Sometimes only the first item in a resulting sequence is interesting. In this case the First() operator returns that element. However, if the sequence is empty, an exception is thrown. This may be inconvenient, and a null return value would be preferred.

This is where the FirstOrDefault() operator comes in. If the sequence is empty it returns null.

 

ToList, ToArray

Most LINQ operators such as Where, Union, etc. don't calculate the result of the operator right away. Instead, an object implementing IEnumerable<T> is returned which does "deferred execution". What this means is that the actual execution is done only when the sequence is enumerated. This may come as quite a surprise. Consider the previous code, with a small extra:

var list1 = new List<int> { 2, 4, 9, 11, 3, 6 };
var list2 = new List<int> { 3, 8, 4, 30, 9, 16 };

var newlist = list1.Intersect(list2);

list1.Add(30);

foreach(int x in newlist)
    Console.WriteLine(x);
What would be the output? Will it include the number 30? The (possibly) surprising answer is yes! That's because the actual Intersect operator does its thing only when the foreach loop executes.
Usually this behavior is what you want, to minimize operations that may not be required right away.
Sometimes, however, you want to get a hold of the result right now, preventing further input changes to affect the result. This is exactly what the ToList() and ToArray() do. They force execution right now and return the relevant sequence immediately. Further changes to the inputs will not affect the output.
 
 
.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

קורסים קרובים שאני מעביר

Published at Jul 15 2008, 09:49 AM by pavely

שני קורסים שאני עומד להעביר בקרוב ואולי יעניינו מישהו...

ב-27 ליולי (החודש הזה) אני מעביר את Advanced .NET with C# - הקורס הורחב ל-4 ימים וכולל גם את .NET security ומבוא ל-C# 3 ו-LINQ. סילבוס מלא ניתן למצוא כאן.

ב-31 לאוגוסט אני מעביר את הקורס Windows Internals ששודרג אף הוא וכולל חומר חדש על ה-Internals של Windows Vista ו-Windows Server 2008. הקורס כולל חומר המסביר את אופן הפעולה של Windows ברמת ה-kernel וחלקים הקרובים ל-kernel. הוא מיועד לכל מי שרוצה להבין לעומק כיצד Windows עובד בנושאים כגון Processes, threads, virtual memory, I/O, security ועוד. הוא מתאים במיוחד לכותבי device drivers ולמי שעוסק ב-system programming, אם כי לדעתי כל אחד שמתכנת ל-Windows גם אם זה בעולם גבוה כמו NET. צריך להכיר את הדברים. זה משפר משמעותית את היכולת לכתוב קוד יעיל וחכם ל-Windows. סילבוס מלא ניתן למצוא כאן

 

Reflection and Privates

Published at Jul 08 2008, 02:32 PM by pavely

During teaching of .NET reflection topics, I mention that using reflection, one can get to the private members of types, and even invoke those members dynamically.

I sometimes get the response in the lines of - how is this possible? What's the point of putting something as private if it's exposed through reflection?

The answer to the "dilemma" is that applications usually run with FullTrust permissions, which means they actually can do anything, including poking in other's privates. But, doing reflection requires having the ReflectionPermission permission with an appropriate flag (ReflectionPermissionFlag enumeration) which may not be granted in partial trust scenarios. The flag allows restricting reflection to enumerating public elements only, allowing dynamic invocation of members and more.

Malware and Hidden Registry Keys

Published at Jul 02 2008, 09:21 PM by pavely

Normal 0 false false false EN-US X-NONE HE MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:0cm; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:"Times New Roman"; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin;}

One of the ways malware activates itself after it infiltrates a system, is by adding itself to the registry key HKLM\Software\Microsoft\Windows\CurrentVersion\Run with a value of Rundll32.Exe, the malware DLL (usually a random character combination) and an entry point.

However, if you open RegEdit.Exe and try to find those keys - you usually won't. That's because they're hidden, or to be more precise - hidden from RegEdit.Exe.

RegEdit.Exe uses the Win32 API to query and manipulate the registry. Keys and values are NULL terminated (with the ‘\0' character). But, the Native API (the undocumented API exposed through NtDll.Dll allows embedded ‘\0' characters (a length is provided, which is all that's needed), so if a malware creates such a value with an additional NULL, RegEdit will fail to see it (or delete it).

The Native API function signatures are "known", but before you attempt to create such a registry editor (or at least viewer), you can try the Reg.Exe tool that is part of Windows.

For example, the command

Reg Query HKLM\Software\Microsoft\Windows\CurrentVersion\Run

Will show all the values in that key (including the hidden ones).

Reg Delete HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v SomeValue

Will delete the value SomeValue even if it has a NULL after the name.

Happy malware hunting!