Ohad's Blog

Lets talk about .net !

Mirror at:
blogs.microsoft.co.il

News

         Ohad Israeli's Facebook profile

Grab this badge here!

C# Code Snippts

Favorite Blogs

Israeli .Net Bloggers

August 2004 - Posts

Secrets of Great Architects

Don Awalt and Rick McUmber published a nice article at July Architects Journal.

"All great architects have mastered the ability to conceptualize a solution at distinct levels of abstraction. By organizing the solution into discrete levels, architects are able to focus on a single aspect of the solution while ignoring all remaining complexities. Presents techniques for applying levels of abstraction to IT solutions, and compares this to other engineering disciplines. (16 printed pages)"

Process.Start and redirect to text file / pipe another process

When you want to spawn a process, but want the process to dump to a text file you might use :

Process.Start("cmd.exe", "/c foo.exe -arg >" + dumpDir + "\\foo_arg.txt");

In case you don't need the file "foo_arg.txt" itself but want the actual output its possible to set ProcessStartInfo.RedirectStandardOutput flag to true and then read the process output using Process.StandardOutput stream.

Another option is to use Process Start for piping the output of the first process to the second :

Process.Start("cmd.exe", "/c foo.exe -arg " + "| bar.exe");

 

Evolution of Programmer :-)

High School/Jr.High

 

10 PRINT "HELLO WORLD"
20 END

First year in College

 

program Hello(input, output)
begin
writeln('Hello World')
end.

Senior year in College

(defun hello
(print
(cons 'Hello (list 'World))))

New professional

#include <stdio.h>
void main(void)
{
char *message[] = {"Hello ", "World"};
int i;

for(i = 0; i < 2; ++i)
printf("%s", message[i]);
printf("\n");
}

Seasoned professional

 

#include <iostream.h>
#include <string.h>

class string
{
private:
int size;
char *ptr;

public:
string() : size(0), ptr(new char('\0')) {}

string(const string &s) : size(s.size)
{
ptr = new char[size + 1];
strcpy(ptr, s.ptr);
}

~string()
{
delete [] ptr;
}

friend ostream &operator <<(ostream &, const string &);
string &operator=(const char *);
};

ostream &operator<<(ostream &stream, const string &s)
{
return(stream << s.ptr);
}

string &string::operator=(const char *chrs)
{
if (this != &chrs)
{
delete [] ptr;
size = strlen(chrs);
ptr = new char[size + 1];
strcpy(ptr, chrs);
}
return(*this);
}

int main()
{
string str;

str = "Hello World";
cout << str << endl;

return(0);
}

Master Programmer

 

[
uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820)
]
library LHello
{
// bring in the master library
importlib("actimp.tlb");
importlib("actexp.tlb");

// bring in my interfaces
#include "pshlo.idl"

[
uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820)
]
cotype THello
{
interface IHello;
interface IPersistFile;
};
};

[
exe,
uuid(2573F890-CFEE-101A-9A9F-00AA00342820)
]
module CHelloLib
{

// some code related header files
importheader(<windows.h>);
importheader(<ole2.h>);
importheader(<except.hxx>);
importheader("pshlo.h");
importheader("shlo.hxx");
importheader("mycls.hxx");

// needed typelibs
importlib("actimp.tlb");
importlib("actexp.tlb");
importlib("thlo.tlb");

[
uuid(2573F891-CFEE-101A-9A9F-00AA00342820),
aggregatable
]
coclass CHello
{
cotype THello;
};
};


#include "ipfix.hxx"

extern HANDLE hEvent;

class CHello : public CHelloBase
{
public:
IPFIX(CLSID_CHello);

CHello(IUnknown *pUnk);
~CHello();

HRESULT __stdcall PrintSz(LPWSTR pwszString);

private:
static int cObjRef;
};


#include <windows.h>
#include <ole2.h>
#include <stdio.h>
#include <stdlib.h>
#include "thlo.h"
#include "pshlo.h"
#include "shlo.hxx"
#include "mycls.hxx"

int CHello::cObjRef = 0;

CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk)
{
cObjRef++;
return;
}

HRESULT __stdcall CHello::PrintSz(LPWSTR pwszString)
{
printf("%ws\n", pwszString);
return(ResultFromScode(S_OK));
}


CHello::~CHello(void)
{

// when the object count goes to zero, stop the server
cObjRef--;
if( cObjRef == 0 )
PulseEvent(hEvent);

return;
}

#include <windows.h>
#include <ole2.h>
#include "pshlo.h"
#include "shlo.hxx"
#include "mycls.hxx"

HANDLE hEvent;

int _cdecl main(
int argc,
char * argv[]
) {
ULONG ulRef;
DWORD dwRegistration;
CHelloCF *pCF = new CHelloCF();

hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

// Initialize the OLE libraries
CoInitializeEx(NULL, COINIT_MULTITHREADED);

CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE, &dwRegistration);

// wait on an event to stop
WaitForSingleObject(hEvent, INFINITE);

// revoke and release the class object
CoRevokeClassObject(dwRegistration);
ulRef = pCF->Release();

// Tell OLE we are going away.
CoUninitialize();

return(0); }

extern CLSID CLSID_CHello;
extern UUID LIBID_CHelloLib;

CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */
0x2573F891,
0xCFEE,
0x101A,
{ 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
};

UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */
0x2573F890,
0xCFEE,
0x101A,
{ 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
};

#include <windows.h>
#include <ole2.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "pshlo.h"
#include "shlo.hxx"
#include "clsid.h"

int _cdecl main(
int argc,
char * argv[]
) {
HRESULT hRslt;
IHello *pHello;
ULONG ulCnt;
IMoniker * pmk;
WCHAR wcsT[_MAX_PATH];
WCHAR wcsPath[2 * _MAX_PATH];

// get object path
wcsPath[0] = '\0';
wcsT[0] = '\0';
if( argc > 1) {
mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1);
wcsupr(wcsPath);
}
else {
fprintf(stderr, "Object path must be specified\n");
return(1);
}

// get print string
if(argc > 2)
mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1);
else
wcscpy(wcsT, L"Hello World");

printf("Linking to object %ws\n", wcsPath);
printf("Text String %ws\n", wcsT);

// Initialize the OLE libraries
hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED);

if(SUCCEEDED(hRslt)) {


hRslt = CreateFileMoniker(wcsPath, &pmk);
if(SUCCEEDED(hRslt))
hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello);

if(SUCCEEDED(hRslt)) {

// print a string out
pHello->PrintSz(wcsT);

Sleep(2000);
ulCnt = pHello->Release();
}
else
printf("Failure to connect, status: %lx", hRslt);

// Tell OLE we are going away.
CoUninitialize();
}

return(0);
}

Apprentice Hacker

#!/usr/local/bin/perl
$msg="Hello, world.\n";
if ($#ARGV >= 0) {
while(defined($arg=shift(@ARGV))) {
$outfilename = $arg;
open(FILE, ">" . $outfilename) || die "Can't write $arg: $!\n";
print (FILE $msg);
close(FILE) || die "Can't close $arg: $!\n";
}
} else {
print ($msg);
}
1;

Experienced Hacker

 

#include <stdio.h>
#define S "Hello, World\n"
main(){exit(printf(S) == strlen(S) ? 0 : 1);}

Seasoned Hacker

% cc -o a.out ~/src/misc/hw/hw.c
% a.out

Guru Hacker

 

% cat
Hello, world.
^D

New Manager

 

10 PRINT "HELLO WORLD"
20 END

Middle Manager

 

mail -s "Hello, world." bob@b12
Bob, could you please write me a program that prints "Hello,
world."?
I need it by tomorrow.
^D

Senior Manager

% zmail jim
I need a "Hello, world." program by this afternoon.

Chief Executive

% letter
letter: Command not found.
% mail
To: ^X ^F ^C
% help mail
help: Command not found.
% damn!
!: Event unrecognized
% logout

Com Plus Info v1.0

Following is a class I wrote more then a year ago when someone wanted to know what is the COM+ application name behind a specific process id, all he was able to get was 'dllhost.exe' and he wanted needed the specific COM+ application name.

Using the helped class you'll be able to get the PID of an Application Name or the Application Name of a specific PID plus the ability to get all COM+ applications currently running.

Today someone asked me for the same feature... i had to dig a little and i found it... But now i have decided to publish it so it wont get lost again. 

If you find this class useful leave me a note as its nice to hear someone else beside me is using the code in my blog :-)

Update: To use COMSVCSLib namespace you need to add a reference to c:\windows dir\system32\comsvsc.dll

// ComPlus Info v1.0
// (c) Ohad Israeli
//
using System;
using System.Collections;
using COMSVCSLib;
using System.Runtime.InteropServices;

namespace ComInfo
{
    public class ComPlusHelper
    {
        public ComPlusHelper()
        {}

        public static ArrayList GetApplicationList()
        {
            COMSVCSLib.MtsGrp GrpObj =
null;
            Type dcomType = Type.GetTypeFromProgID("mts.MtsGrp");
           
Object dcomObj = Activator.CreateInstance( dcomType );
            GrpObj = (COMSVCSLib.MtsGrp) dcomObj;
            object obj = null;
            COMSVCSLib.COMEvents eventObj =
null;
            ArrayList arr=
new ArrayList(GrpObj.Count);
            for (int i = 0 ;i < GrpObj.Count ; ++i)
            {
                GrpObj.Item (i,
out obj);
                eventObj = (COMSVCSLib.COMEvents) obj;
                arr.Add(eventObj.GetProcessID()+" : "+eventObj.PackageName);
                Marshal.ReleaseComObject(obj);
                obj =
null;
                Marshal.ReleaseComObject(eventObj);
                eventObj =
null;
            }
            Marshal.ReleaseComObject( dcomObj );
            dcomObj =
null;
            return arr;
       }
       public static int GetPidByName(string strComPlusProgName)
       {
          
int returnVal = 0;
           COMSVCSLib.MtsGrp GrpObj =
null;
           Type dcomType = Type.GetTypeFromProgID("mts.MtsGrp");
           Object dcomObj = Activator.CreateInstance( dcomType );
           GrpObj = (COMSVCSLib.MtsGrp) dcomObj;
           object obj = null;
           COMSVCSLib.COMEvents eventObj =
null;
           for (int i = 0 ;i < GrpObj.Count ; ++i)
           {
                GrpObj.Item (i,
out obj);
                eventObj = (COMSVCSLib.COMEvents) obj;
                if (eventObj.PackageName.ToUpper()==strComPlusProgName.ToUpper())
                     returnVal=eventObj.GetProcessID();
                Marshal.ReleaseComObject(obj);
                obj =
null;
                Marshal.ReleaseComObject(eventObj);
                eventObj =
null;
            }
            Marshal.ReleaseComObject( dcomObj );
            dcomObj =
null;
            return returnVal;
       }
       public static string GetNameByPid(int intPid)
       {
            string returnVal = "";
            COMSVCSLib.MtsGrp GrpObj =
null;
            Type dcomType = Type.GetTypeFromProgID("mts.MtsGrp");
            Object dcomObj = Activator.CreateInstance( dcomType );
            GrpObj = (COMSVCSLib.MtsGrp) dcomObj;
            object obj = null;
            COMSVCSLib.COMEvents eventObj =
null;
            for (int i = 0 ;i < GrpObj.Count ; ++i)
            {
                GrpObj.Item (i,
out obj);
                eventObj = (COMSVCSLib.COMEvents) obj;
                if (eventObj.GetProcessID()==intPid)
                    returnVal=eventObj.PackageName;
                Marshal.ReleaseComObject(obj);
                obj =
null;
                Marshal.ReleaseComObject(eventObj);
                eventObj =
null;
           }
           Marshal.ReleaseComObject( dcomObj );
           dcomObj =
null;
           return returnVal;
      }
  }
}

// Usage:
string strComPlusId=ComPlusHelper.GetPidByName(strComPlusName).ToString();

string strComPlusName=ComPlusHelper.GetNameByPid(intComPlusId);

listbox1.Items.AddRange(ComPlusHelper.GetApplicationList().ToArray());

Posted: Aug 16 2004, 12:35 AM by Ohad Israeli | with 4 comment(s)
Filed under:
Drive Free Space

There are several ways to get the drive free space:

1. The interop way.

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
public static extern bool GetDiskFreeSpaceEx(
        string lpDirectoryName,
        out UInt64 lpFreeBytesAvailable,
        out UInt64 lpTotalNumberOfBytes,
       
out UInt64 lpTotalNumberOfFreeBytes);

ulong freeBytesAvailable = 0;
ulong totalNumberOfBytes = 0;
ulong totalNumberOfFreeBytes = 0;

GetDiskFreeSpaceEx(
   "c:\\",
   out freeBytesAvailable,
   out totalNumberOfBytes,
   out totalNumberOfFreeBytes);

2. The WMI Way

We can use WMI by connecting to the “root\\cimv2” namespace and using the “Win32_LogicalDisk” class.  Programming WMI isn’t pretty, but you can use the WMI extensions for VS ‘03 Server Explorer which makes it tolerable. Once installed, you’ll get a list of the management classes in server explorer and you can simply drag and drop the disk volume that you want to pull information from onto your application designer.

You can then show free space on the volume with one line of code: MessageBox.Show(logicalDisk1.FreeSpace.ToString());

using System;
using System.Management;

tatic void Main(string[] args)
{
   
WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = 'C:'");
   
ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery);

   foreach (ManagementObject mobj in wmifind.Get()) 
   
{
      Console.WriteLine("Description: " + mobj["Description"]);
      Console.WriteLine("File system: " + mobj["FileSystem"]);
      Console.WriteLine("Free disk space: " + mobj["FreeSpace"]);
      Console.WriteLine("Size: " + mobj["Size"]);
   }
}

3. The Whidbey Way

System.IO.DriveInfo.AvailableFreeSpace

Posted: Aug 08 2004, 11:43 AM by Ohad Israeli | with 3 comment(s)
Filed under:
WSE 2.0 Encryption vs. SSL

 I was wondering what will be the best method to encrypt communication/soap message between client and web service should I use WSE encryption or SSL ?

 

Well after digging in the area a little I came up with the following comparison table:

 

Feature

WS-Security

SSL

 

Complete security solution

End-to-end solution
WSE is designed so that a request can maintain security across multiple hops without explicit knowledge of those intermediary hops.

Point-to-point solution

SOAP Router to dispatch messages

Using ws-messaging WSE can route the message to the destination.

The router would have to decrypt the message in order to identify the end-point of that given message.

Partly message encryption

You can decide what parts of the message you want to encrypt

All the communication / message is being encrypted

Key Management

requires coding to handle the key management and exchange protocol or using policy wizard to do this part without any coding

requires a server certificate

Binding to specific protocol

You are now able to encrypt *independent* of the underlying protocol as WSE presently supports TCP. The underlying protocol that you might want to leverage becomes a config setting in an XML file.

SSL “binds” you to the HTTP protocol

Deployment

requires deploying your code to the client machine (compiled code if using WSE)

SSL does not requires deploying, as most common browsers support it

Production Deployment

There aren’t any hardware accelerators

There are hardware SSL accelerator cards

 

Comments and more comparison features are welcomed!

Posted: Aug 08 2004, 10:54 AM by Ohad Israeli | with 1 comment(s)
Filed under:
Programming Language Popularity
Which programming language is currently the most popular?
 
Developer.com published the rankings according to the TIOBE Programming Community (TPC) Index.
 
Developing Identity-Aware ASP.NET Applications

Developing Identity-Aware ASP.NET Applications, a new paper in the Microsoft Identity and Access Management Series.

Organizations today are looking for guidance on how to avoid introducing new directories and authentication schemes that increase complexity and undermine the goals of a successful identity and access management strategy. They want to develop applications that are tightly integrated with their identity infrastructure.

This paper provides guidelines for developing applications that use the directory and security services of the Microsoft® Windows® platform. Specifically, the paper discusses identity considerations and guidelines when developing Microsoft ASP.NET multi-tier intranet and extranet Web applications using Microsoft Visual Studio® .NET and Microsoft Windows Server™ 2003 directory and security services. It provides detailed implementation guidance and ASP.NET code samples in Microsoft Visual C#® and Microsoft Visual Basic® .NET for:

Intranet Web applications that use Windows-integrated authentication and Windows Authorization Manager.

Extranet Web applications for B2B, B2C, and B2E scenarios using Windows authentication (including Forms-based authentication, X.509 certificates, and Microsoft Passport) and Windows Authorization Manager.

Posted: Aug 05 2004, 11:10 PM by Ohad Israeli
Filed under:
More Posts