Tuesday, November 27, 2012

Run exe using NetworkService account

Sometime back we had a requirement of running an exe in the context of network user. Initially it looked very easy. But when I tried to impersonate the execution, I realized the difficulty. It is easy to impersonate as a standard user .But cannot impersonate as NetworkService. So what are the alternatives.

  1. Run a windows service and start the process/executable from that service.
  2. Schedule a task and specify target as our exe and use NetworkService to initiate execution. Delete the task after execution.

Run exe through windows service

This is a simple matter or creating a windows service and executing a exe when we start the service. Immediately after completion of exe stop the service.This can be summarized as

  1. Create a simple windows service
    1. This should accept an exe path through the OnStart() method.
    2. Execute the exe.
    3. Stop the service by calling Stop() method.
  2. Use the sc start command to start the service and pass path as param.

You may download the program from here.

Schedule task on behalf of NetworkService

This too simple. The steps are

  1. Create a scheduled task pointing to your application using ‘schtasks’ command.
    1. Use “NT AUTHORITY\NETWORK SERVICE" as user profile
    2. Give the run frequency as onlogon. This is to ensure that, it will never run before we trigger.
    3. eg: <drive>:\<folder>>schtasks /create /tn testser /sc onlogon /ru "NT AUTHORITY\NETWORK SERVICE" /tr d:\Temp\HelloWorld.exe (No way to reduce params)
  2. Run the task
    1. schtasks /run /tn "testser"
  3. Delete the task
    1. schtasks /delete /tn testser /f (/f is to delete forcefully.Else it will ask a confirmation)

Better wrap this into a single batch file which accepts the exe name and run the same in the context of ‘NetworkService’. ie you can use like RunAsNetworkService <file path>

NB: If you simply create the task using command, it will not run, it is in a portable system such as laptop and it is in battery during invocation. To resolve that, you need to create an xml file where you can specify to enable task running in batteries and point the same xml in the task creation command.Below links explains how to create task with xml file option.


Difference between IIF and If in VB.Net

In C# the conditional operator ‘?:’ works in a simple fashion and there is only one ternary operator. Early days of  VB.Net was too similar to C# as we had IIF function to achieve the same. But later they added a additional features to if keyword to behave like ternary conditional operator. That change mainly introduced an question into VB.Net interviews. What is the difference between IIF and if keyword.

‘IIF’ is a function which is available in Microsoft.VisualBasic.dll where the ‘if’ is a keyword which is part of the language. Simply speaking you can right click on the IIF and select “Go To Definition”.

IIF always accept 3 parameter. But if can accept 2 parameter. In that case the behavior will be changed in such a way that it returns second param if the first is null.Else the first parameter.

IIF evaluates all three parameter expressions (truepart and false part) regardless the value of first expression. But ‘if’ evaluates either second or third expression based on the value of the first expression.

Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim result As Boolean = IIf(True, TruePart(), FalsePart())
MessageBox.Show("Result :" & result)
End Sub
Public Function TruePart() As Boolean
Return True
End Function
Public Function FalsePart() As Boolean
Return False
End Function

The out put of the above code shows as follows .
Messagebox shows ‘Result :True’ and the output window

Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Dim result As Boolean = If(True, TruePart(), FalsePart())
MessageBox.Show("Result :" & result)
End Sub

The out put of the above code shows as follows .
Messagebox shows ‘Result :True’ and the output window shows only

Want to learn more about other features of if keyword such as null alternate please visit the msdn link

Tuesday, November 6, 2012

Deciding when to use interface and abstract class?

This is a famous question which is there from the days managed languages avoided multiple inheritance. Mainly C# and Java. They brought a new concept called interface to deal with multiple inheritance. (I don't know whether this is introduced by some other language).From those days a new question entered into almost all the technical interviews related to C#,.net and Java. The question is nothing but "What is the difference between interface and abstract class?" which is covered in almost all interview question answer sites.

If the candidate is just out of college and had completed any C# / Java course his answer will be
  • Interface is created using the keyword 'interface' and abstract class by 'abstract'
  • Interface cannot have implementation.Some methods in abstract class can have function body.
'Have you used interface in your academic projects?' will almost make him silent.

The candidate who has got experience in using interfaces will say
  • All the methods in interface needs to be implemented.
  • Interfaces are using to implement contracts for eg WCF contract should be interface decorated with  DataContract attribute.
If he has created interface in any of his programs he will say
  • We cannot declare variables in interface.
  • Interfaces don't allow constructors.
  • Interfaces cannot have static members.
  • There is no need to specify access modifies in interface.
  • Interfaces can inherit from interface only where abstract class can be created from interfaces as well as another class.
More advanced programmers will add some more items
  • Interfaces are used to implement multiple inheritance.
  • Interfaces can be implemented by structures.
  • C# allows us to have 2 methods with same signature in single class provided one method is implemented as explicit interface method.
But if you ask even the advanced programmers "What is the ultimate factor which makes you to create an interface or abstract class?" they will be little confused.ie Forget about multiple inheritance and structures.We don't know whether an entity is going to be used in multiple inheritance scenario or not .Also we don't know whether there needs a common base class method implementation.

The answer is simple. 

If an object is related to another object using "Is-A" relationship use abstract class. If the object is related to another as "Can-Be" use interface.

eg: Parrot Is-A Bird.Parrot Can fly.Pigeon is-a Bird and it can also fly.Duck is-a Bird .But it cannot fly.Here Is-A decides the need for abstract base class 'Bird'.'Flyable' is a Can-Be behavior. We cannot say all birds can fly. So the Can-Be behavior translate to interface 'IFlyable' or simply 'Flyable'. It would be more clear if we take the case of a Helicopter. It Can fly.But it is not a Bird.

We can conclude as "Use interface if its a behavior.Abstract class in case of common features."

Hope this clears confusion in many developer minds.