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

Saturday, April 24, 2010

Race Condition as Illustrated with Racer X and Speed Racer

Sometimes nothing works better than a simple example.

Below is a short program that demonstrates a race condition that occurs when two threads share some bit of state. It is written in C# and if you run it several times you should see inconsistent behaviors.

Sometimes Speed Racers thread finishes first and resets the SharedState to true and sometimes Racer X wins. This is the heart of threading problems, shared state and inconsistent results.

Now lets looks at a proposed fix. In RacerX there is a commented line
//System.Threading.Thread.Sleep(100);

By uncommenting it,  the inconsistent behaviour changes. Sometimes the program finishes because RacerX finished first and waited long enough for Speed Racer to finish. (You know he was the older brother and always looking out for Speed Racer)

But sometimes Speed Racer finishes first and he doesn't wait for RacerX. So Racer X keeps circling around. (Keep in mind Speed did not know that Racer X was his older brother)

So in this case it appears that the code has gotten better because the bug is now showing only half the time. But in reality it is just as flaky. The bug has now become intermittant and harder to reproduce.


class Program
{
static bool SharedState = true;

static void Main(string[] args)
{
Thread racerX = new Thread(RacerX);
racerX.Start();
Thread speedRacer = new Thread(SpeedRacer);
speedRacer.Start();
System.Threading.Thread.Sleep(2000);
SharedState = false;
}


static void RacerX()
{
while (SharedState)
{
Console.WriteLine("RacerX");
}
//System.Threading.Thread.Sleep(100);
SharedState = true;
}


static void SpeedRacer()
{
while (SharedState)
{
Console.WriteLine("SpeedRacer");
}
SharedState = true;
}
}

Thursday, April 22, 2010

The bug that never happened.

I was demonstrating some F# code in Visual Studio 2010. It is shown below and it defines and then computes the discriminant function for quadratics.

let quadratic = fun a b c -> (b * b) - (4 * a *c)
let discriminant = quadratic 4 5 6
printfn "discriminant = %d" discriminant

Everything works, no surprise. But then as I modified the code. In particular as I changed the last line to:

printfn "discriminant = %d %d" discriminant

A compile warning occurred! So the compiler parsed the formatting string as well and checked that there where enough parameters provided. No doubt there is a nuance to functional programming that is requiring this level of checking.

But compare this to a line of C#

string wrongNumberOfArgs = string.Format("{0} {1}", 12);

The c# compiler is perfectly okay with this and it is only at runtime that you get the crash. In the simple case that I have shown this does not matter. But simple cases are not where this occurs. It is when it is complex that it occurs. So in the C# case you will find this out when you execute the code, when your mind has switched contexts.

In the F# case, the compiler warning is immediate because of the incremental compiles. You are best positioned to fix the code because you just keyed it in. In fact this is a bug that never happened.

Saturday, January 3, 2009

F# leads the transformation


What F# represents is a partitioning of the programming languages. And unlike previous partitions this is a transformative change. General purpose languages are being supplanted by a collection of domain specific languages. These domain specific languages will include a general purpose language but it will not be there to rule them all but rather to orchestrate them all.
F# is a native or natural functional language where objects are possible (but the objects may not feel native or natural). C# is an object oriented language. With the advent of LINQ, some functional capabilities are possible but most C# programmers have experienced the unnatural things LINQ is doing to the language.
So each language has a dominant paradigm, C# is an object oriented language and F# is functionally oriented. Each supports the other paradigm but using that paradigm is for one off or special purpose needs. LINQ allows C# programmers to off load a bunch of data processing tasks that are hard and / or tedious to code in any C derivative language. Likewise objects are available in F# in case you need to maintain state. But the more you need to maintain state the less the task you are working with is a functional oriented task.
Since we are 60+ years into programming, Bare-Naked-Ladies-Fans ("It's all been done") are sure to point out this has all been done before. This is a valid point as C++ and Perl demonstrate. Both languages have adapted and provide these and numerous other features. However both languages have purchased these abilities at ever increasing complexity. As the Ruby creator aptly points out C++ is constantly surprising him. For a hobbyist, surprise is fun. For a guy trying to get something done surprise is bad.
But leaving aside surprise, it is hard to feel like you know either of C++ of Perl in their entirety. All special purpose languages that succeed will share this fate. Every feature the language supports will require some complexity to implement it in the syntax. The future being unknowable will always mean some choices turn out to be less than perfect.
So as the general purpose languages evolve their complexity and internal contradictions will grow as well. The languages scream for a refactoring. But refactoring is the one tool no language can ever use. No matter how ill advised a feature, it cannot be removed because this would break countless programs. And refactoring is not the removal of one feature but the wholesale change of several features.
What history gave us was series of general purpose languages (C, C++, Perl, Java, C# and others) where an attempt was made to refactor to the perfect paradigm. The dot Net platform opens up a new way; several languages can interoperate on the same platform and in the same development environment. F# is the break out example because unlike the C# and VB.net interaction it implements a completely different programming paradigm.
The general purpose languages do not have to implement every hot new feature. They can develop side by side with the F# languages, leveraging their power without corrupting their own syntax.

Sunday, August 24, 2008

Code: Test For Service Existence

Code To Test For Service Existence


bool serviceExists = false;
foreach ( System.ServiceProcess.ServiceController serviceController in System.ServiceProcess.ServiceController.GetServices())
{
if (serviceController.ServiceName == "TwentyTwentyLiveService")
{
serviceExists = true;
}
}

Saturday, August 23, 2008

Code: Determining If A User Is An Admin

There are several built in roles to help determine if the user is an Admin, User or Guest.


 WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();

WindowsPrincipal currentPrincipal = newWindowsPrincipal(currentIdentity);
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
  //Administator code
}
if (currentPrincipal.IsInRole(WindowsBuiltInRole.User))
{
 // User code
}
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Guest))
{
 // Guest or anonymous code
}

Wednesday, August 20, 2008

Reflecting On Browser Properties


We are armpit deep in Mobile Development and facing multiple Level 2 Ignorance traps.
One area concerns browsers. As each Mobile Platform has a unique browser and browser settings.
To help with this, we have a page where we use Reflection to dump out the browser properties.
Note the code has a "evil" empty try catch, our code is similar (read much improved).
But I though it would be handy to provide the essence of the solution.
Type
browserType = Request.Browser.GetType();
foreach (PropertyInfo propertyInfo in
browserType.GetProperties())
{
try
{
Response.Write(propertyInfo.Name +
" : " + propertyInfo.GetValue(Request.Browser, null).ToString()
;
}
catch
{
}
}

Thursday, July 24, 2008

Does Security Make C++ Obsolete

Stephen Gould said every species is extinct, they just do not know it.

From a security point of view C++ may be obsolete and we just do not know it yet. Increasing C++ is justified based on performance factors and legacy code. The performance increase that still remains is due primarily to the direct access to memory. This is when comparing to a language that handles memory management like Java or C# or VB.Net.

The security implications of direct memory access becomes apparent when examining lists of top security threats. At the top of the list are Buffer Overflows and Stack Overflows. Both are possible only because of direct memory access.

Since C# is memory managed except when you explicitly tell it not to be, you could say that it is "Secure By Default". This is in contrast to C++ which is "Unsecure By Default."

Wednesday, July 23, 2008

Testing for Endianess

A colleague is studying for a Microsoft Interview.
One of the questions is to write code to test for Endian.
The answer Microsoft likes involves bit twiddling, but one wonders why they would not prefer calling their own framework:
using System;


using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1

{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("BitConverter.IsLittleEndian " + BitConverter.IsLittleEndian.ToString());
Console.ReadLine();
}
}
}



Sunday, July 13, 2008

C Sharp Interview Questions: Modifiers

Interview Quesions involving class and method modifiers.

1. What are the features of an abstract class?
Answer: It cannot be instantiated.It can contain abstrast methods and accessors.

2. When an non-abstract class derives from an abstract class with abstract methods or accessors what must it do?
Answer: It must provide implementations for all abstract methods and accessors.

3. What is an abstract method?
Answer: Implicitly it is a virtual method.Permitted only in abstract classes.It has no body.

4. Why are abstract methods not permitted in non-abstract classes?
Answer: Abstract methods have no implementation, which would be required in a concrete class.

5. When a field or local variable is marked const what does it change?
Answer: The value cannot change. It can only be initialized at declaration.

6. How is override used?
Answer: It is used to modify a method, property or indexer to change the implementation.

7. When a field is marked readonly what does it change?
Answer: The value can only be set in the constructor during initialization.

8. In terms of runtime and compile time, compare const and readonly.
Answer. const is compile time and readonly is runtime.

9. What is a sealed class?
Answer: The class cannot be derived by another class.

10. How does static change fields and methods?
Answer: They become global and belong to the type instead of the instance.

11. What is a virtual method?Answer: It is a method that implementation can be changed in a derived class by using the override keyword.

12. Why is modifiying a class with both abstract and sealed an error?
Answer: An abstract class cannot be instantiated

Friday, July 11, 2008

C Sharp Interview Questions: Operators

Questions involving Operators.

1. When the division operator "/" is used with two integers what is result?
Answer: An integer division with the remainder discarded ( 16 / 5 is 3).

2. What is the operator "%"?
Answer: It returns the remainder from the division.

3. What are the operators "" and ""? How do the differ?
Answer:
Operator "" is the bitwise-or operator.
It accepts boolean operands and integer operands.
The second parameter is always evaluated.
For integer operatands the individual bit places are or'ed separately.

Operator "" is the condition-or operator.
If the first operand is true the second parameter will not be evaluated.

4. What are the operators "&" and "&&"? How do the differ?
Answer:
Operator "&" is the bitwise-and operator.
It accepts boolean operands and integer operands.
The second parameter is always evaluated.
For integer operands the individual bit places are and'ed separately.

Operator "&&" is the condition-and operator.
If the first operand is false the second parameter will not be evaluated.

5. What are the operators '>>' and '<<'? Which mathematical operations are similiar? Answer: Operator '>>' is the right shift operator (right bit shift). It is similar to dividing by a power of 2.
Operator '<<' is the left shift operator (left bit shift). It is similar to multiplying by a power of 2.

6. What are the operators '?:' and '??' ?
Answer:
Operator '?:' is the conditional operator and is used in a statement in the form:
(conditional expression) ? (expression 1) : (expression 2)
If the (conditional expression) evaluates to true then the result of (expression 1) is returned.
If the (conditional expression) evaluates to false then the result of (expression 2) is returned.
Operator '??' returns the left operand if the left operand is not null otherwise it returns the right operand.

Monday, July 7, 2008

Visual Studio: Hot Keys: Refactoring

Note all of the Refactoring Hot Key Chords start with Ctrl R.

Ctrl + R E
Encapsulate a Field, creates a property from a field

Ctrl + R I
Extract an Interface, create a new interface from an existing class, interface or struct

Ctrl + R M
Extract Method, create method from code selection

Ctrl + R P
Promote to Parameter, promote a local variable to a parameter

Ctrl + R V
Remove Parameters

Ctrl + R R
Rename, allows renaming of identifier

Ctrl + R O
Change Order of Parameters

Sunday, July 6, 2008

C Sharp Interview Questions: Access Modifiers

Questions involving C# Access Modifier keywords.

1. Describe how the keyword "internal" affects access.
Answer: can only be accessed from the same assembly

2. Describe how the keyword "private" affects access.
Answer: can only be accessed from same class or structure

3. Describe how the keyword "protected" affects access.
Answer: can only be accessed from the class where it is declared or a derived class

4. Describe how the keyword "public" affects access.
Answer: No Restriction

5. Can multiple access modifiers be used on a member or type.
Answer: Only the combination "protected internal" is allowed

6. What is the default accessibility of an enum?
Answer: public

7. What is the default accessibility of an interface?
Answer: public

8. What is the default accessibility of a class ?
Answer: private

9. What is the default accessibility of an struct?
Answer: private

Saturday, July 5, 2008

Index Of C# Interview Questions

Index Of C# Interview Questions

Actors

Agarwal Corollary

Agarwal's Law

AP Calculus

ASPNET account

backupfile

backupset

Bright Shiny Object

Bug Focus

Build

C#

Calculus

Code Pattern

Cognitive Load

Compact Net Framework

Coroutine

Daisy Chain Bug

Desktop Virtualization

DEV

Dot Net Framework

Dot Net Singularity

DotNet Singularity

Enterprise Agreement

enum

Even More Law

EventHandler

Exception

Exception Handling

Feature Focus

FileSystemWatcher

Firefox

Five Nines

Full Package Retail

Generator

GPS

helpctr.exe

hex literal

Hyper VTM

IEnumerable

IIS

Index

installer

INT

integer literal

Intellisense

Internet Explorer

Interviewing

Join

Linux

Micro Dot Net Framework

Microsoft Application Virtualization

Microsoft Team System

Microsoft Virtual PC

Mono

Moonlight

Moore's Law

msdb

msinfo.exe

msinfo.htm

MsTest

MultiBrain

MultiCore

multiplatform

MultiThread

Net Framework

NETWORK SERVICE

NUnit

Open Business

Open Value

Open Value Subscription

Parse

Permutation

Poisoned Candy

Prod

Production

QA

Refactor

Regex

Regression Bug

Requirements

Select License Agreement

Separation of Concerns

Serial Port

Server Virtualization

ServiceController

ServiceProcess

Silverlight

Snippets

Software Development

Software Development Practices

Source Control

Sprint

Sprint Aircard

SQL Server

Subroutine

System

System Info

System.Exception

Team Server

Team System Build

TfsBuild

Thread

ThreadStart

Three Nines

TryParse

UAT

uint

Unix

Use Case

User Acceptance Testing

VB.net

Version Control

Virtualization

Visual Studio

VJ#

Web Service

Win32

Win64

Windows Server

Windows Terminal Services

Windows XP

yield

Wednesday, July 2, 2008

C Sharp Interview Question: Basic Part 1

Basic Questions.

1. Does C# support multiple inheritance?
No.

2. Can a class implement more than one interface?
Yes

3. Outline three exception handling code blocks"
try{} catch(){}
try{} finally {}
try{} catch() {} finally {}

4. When is the finally block executed?
When there is an error and a catch block is present the catch block executes first.
Following that the finally block is executed.
When there is no error, the finally block executed immediately after the last line in the flow of the try block.

5. What is the most common use of a finally block?
Release resources acquired or used in the try block.

6. Explain immutable in relation to C#.
All primitive types are immutable which means that after the type is constructed (allocated) it's value will not change. Statements that appear to change the value, actually cause the type to be constructed (reallocated) again.

7. For class named BaseClass and a class named DerivedClass, how would you declare DerivedClass to indicate that it directly inherits from base class?
class DerivedClass : BaseClass

8. What is the implicit parameter of set method of a property?
Value

9. What are three types of comments used in C#?
Single line comments '//'
Multiline comments that start with '/*' and ends with '*/'
XML comments '///'

Tuesday, July 1, 2008

Regular Expression Groups

Regular Expression Groups

===========
Sample Code
===========
string testIpString = "192.168.110.112";
string regularExpressionString = @"^(?<octet1>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet2>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet3>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet4>[01]?\d\d2[0-4]\d25[0-5])$";

//Option 1//Match matches = Regex.Match(testIpString, regularExpressionString);
//Option 2//Match matches = Regex.Match(testIpString, regularExpressionString,RegexOptions.ExplicitCapture);

Console.WriteLine("Groups");

foreach (Group group in matches.Groups)
{
Console.WriteLine(group.ToString());
}

Console.WriteLine("Named Groups");

Console.WriteLine( matches.Groups["octet1"].ToString());
Console.WriteLine( matches.Groups["octet2"].ToString());
Console.WriteLine( matches.Groups["octet3"].ToString());
Console.WriteLine( matches.Groups["octet4"].ToString());

Console.ReadLine();
===============
Option 1 output
===============
Groups
192.168.110.112
.
.
.
192
168
110
112
Named Groups
192
168
110
112
===============
Option 2 output
===============
Groups
192.168.110.112
192
168
110
112
Named Groups
192
168
110
112
===============
Commentary
===============

Most of the power is in the regular expression:

@"^(?<octet1>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet2>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet3>[01]?\d\d2[0-4]\d25[0-5])(\.)(?<octet4>[01]?\d\d2[0-4]\d25[0-5])$";

Sunday, June 29, 2008

C Sharp Interview Questions: Keywords

C Sharp Interview Questions: Keywords

1. List several C# keywords.

abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate,
do,
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
int
interface
internal
is
lock
long
namespace
new
null
object
operator
out
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
volatile
void
while

2. List Several C# Contextual Keywords

from
get
group
into
join
let
orderby
partial (as a type)
partial (as a method)
select
set
value
var
where (generic type constraint)
where (query clause)
yield

3. List several C# Value Type keywords.


bool
byte
char
decimal,
enum
int
long
sbyte
short
struct
uint
ulong
ushort

(note string is a built in reference type, your call on grading it)


4. List several C# Reference Type keywords.


class,
delegate,
interface

(object and string are built in reference types)



5. List several C# Access Modifier keywords.

internal
private
protected
public


6. List several C# Modifier keywords (class modifiers, method modifiers...)

abstract
const
event
extern
override
readonly
sealed
static
unsafe
virtual
volatile



7. List several C# keywords involving iteration statements.

do
for
foreach
in
while


8. List several C# keywords involving selection statements.

if
else
switch


9. List several C# keywords involving jump statements.

break
continue
goto
return

10. List several C# keywords involving Exception Handling statements.

throw
try
catch
finally


11. List several C# keywords involving method parameters.

params
ref
out


12. List several C# keywords involving namespaces.

namespace
using


13. List several C# keywords involving operator.

as
checked
is
new
sizeof
typeof
true
false
stackalloc
unchecked


14. List several C# keywords involving conversion operators.

explicit
implicit
operator



15. List several C# keywords involving access (class access).

base
this


16. List several C# default keywords.

true
false
null

Thursday, June 26, 2008

Last Day of Current Month

Some C# code to determine the last day of the current month.

//One liner
DateTime lastday = DateTime.Today.AddMonths(1).AddDays(-DateTime.Today.Day);

// Extra line to make it more readable
DateTime today = DateTime.Today;
DateTime lastday = today.AddMonths(1).AddDays(-today.Day);

Tuesday, June 24, 2008

Regex Characters Digits and Underscores

Regex to validate a string is composed of only characters, numbers and underscores.

==comments==

Brackets mean match any one of:
"[abcde]" means match any one of a,b,c,d,e.

Dash between characters is a short hand for include all characters between.
"[a-z]" any lowercase letter
"[A-Z]" any uppercase letter
"[0-9]" any digit

Plus sign after a bracket means match one or more
"[a-zA-Z_0-9]+" will match any substring composed of only letter, digits or the underscore, the substring must have at least one

Dollar Sign matches the beginning of a string and Hat '^' matches the end of a string.
"$[a-zA-Z_0-9]+^" will match any substring composed of only letter, digits or the underscore, the substring must have at least one. Also there can be no characters before or after the matching substring.

==code==

public bool ValidateIdentifier(string identifier)
{
Regex re = new Regex("^[a-zA-Z_0-9]+$");
MatchCollection match = re.Matches(identifier);
if (match.Count != 1)
{
//_LastException = new Exception("Identifier must have only characters, digits and underscores");
return false;
}

return true;
}

Wednesday, June 18, 2008

Forcing The Compile Order Of Projects In Visual Studio

For managed code projects, setting project references causes Visual Studio to do the right thing in terms of building dependencies and linking them in the right order. It does the job so well I do not care how it goes about it.

But in the case of Unmanaged Code you will occasionally want to move the outputs around so they can be found by other projects.

To do this right click on the solution in the Solution Explorer, select Properties from the menu.

In the property pages dialog, under Common Properties, select Project Dependencies.

Here you will be able to select a project, then select which projects it Depends on.

Note if the checkbox for a project is grayed out it means a dependency already exists going the other way.

Sunday, June 15, 2008

-0X80000000 is not -2147483648

Got an obscure one today.

The code that follows illustrates the problem but is not the code where the problem was
found.

We were expecting that the hex integer literal 0X80000000 would correspond to the integer value of (-1)(2^31) since this is a legal value. We tried this several ways (2) (3) (4) and they all resulted in an error. This is because the code which parses hex integer literals does not recognize the 0X80000000 as valid int value as such it then tries to create it as uint. If you remove comment (1) you will see these (2) works.

What is a little disturbing is (5) the decimal integer literal for (-1)(2^31) is a valid value.

===Code Follows===
enum Range //(1)// : uint
{
flag1 = 0X1,
flag2 = -0X2,
flag3 = 0X4,
flag4 = 0X8,
flag5 = 0X10,
flag6 = 0X20,
flag7 = 0X40,
flag8 = 0X80,

flag9 = 0X100,
flag10 = 0X200,
flag11 = 0X400,
flag12 = 0X800,
flag13 = 0X1000,
flag14 = 0X2000,
flag15 = 0X4000,
flag16 = 0X8000,

flag17 = 0X10000,
flag18 = 0X20000,
flag19 = 0X40000,
flag20 = 0X80000,
flag21 = 0X100000,
flag22 = 0X200000,
flag23 = 0X400000,
flag24 = 0X800000,

flag25 = 0X1000000,
flag26 = 0X2000000,
flag27 = 0X4000000,
flag28 = 0X8000000,
flag29 = 0X10000000,
flag30 = 0X20000000,
flag31 = 0X40000000,
//2// flag32 = 0X80000000 // Cannot implicitly convert 'uint' to 'int'
//3// flag32 = -0X80000000 // Cannot implicitly convert 'uint' to 'int'
//4// flag32 = 0X80000000u // Cannot implicitly convert 'uint' to 'int'
//5// flag32 = -2147483648 // Works
}