Living .NET...

Musings on .NET, and the like - Manoj G [MVP, Connected Systems Developer]
Posted: by

Comments

Manoj G said:

Good one.. Still holds good even for Whidbey....
# January 8, 2004 12:26 PM

Manoj G said:

I think on the first point, you're trying to say that VB won't allow you to reimplement an interface that a base class has already implemented. This is currently the case, but will be changed in the future. See: http://www.panopticoncentral.net/PermaLink.aspx/7db41c57-62fc-4aa1-af96-1cb3d5be10ef
# January 30, 2004 11:55 PM

Manoj G said:

It is true that you can pass System.Reflection.Missing.Value to force the default value to be taken, but ONLY if the type of the optional argument is 'object'. If the type is for example 'string', you realy have a problem calling that method from c#. The only solution I have found is to wrap the methods in Visual Basic witout using optional arguments. This is really frustrating.
# March 10, 2004 5:00 PM

Manoj G said:

I thought this was already in the community releases, but I lose track of what's in which release. Anyway, VB will have build events and you'll get to them from the Compile tab of the application designer. There'll be a button called "Build Events" that will let you set them.
# June 16, 2004 3:20 AM

Manoj G said:

Thanks for the correction Paul. It was rather clumsy on my side to not have seen the Build Events button on the compile tab. I am correcting the post right away.
# June 16, 2004 12:11 PM

Manoj G said:

hi manoj,
nice blog.
a few things on this :-
1. When the compiler inlines a method, it almost certainly does it in case of
loops.( i would certainly like a counter-arg[0])
2. The most important use is debugging. Even though u may have VS.net on ur
machine, i guess its much easier for u to know which line throws an error, and
fix the error(if possible) without pressing F5.
3. When u r checking the method call depth( even for security purposes) ,
will this be able to track if a COM client calls this method?

There may be many other uses, but i guess a call stack profiler would be the most
useful application with this, as u mentioned.


# June 30, 2004 4:45 AM

Manoj G said:

thats a nice list of articles on various topics..
# August 2, 2004 5:34 PM

Manoj G said:

I don't understand why everyone thinks VB programmers are too stupid to do advanced programming. I keep hearing references about features such as "well, that's too hard for a VBer to do but C#ers expect it." Does everyone think VB programmers just graduated from HTML programming school? Sure, VB6 made programming so easy that a lot of non-programmers jumped into the field. C++ was so hard that only programmers with a formal education would work with it. But that doesn't mean that ALL VBers don't know anything about programming. I have a Masters degree and can obviously program in VB.NET or C#. Know which one I choose? The one the client is paying me to program in. I've worked on contracts with plenty of hardcore programmers who were writing VB6 COM objects. Give me the tools I need to do my job. Quit questioning my IQ.
# August 12, 2004 3:06 AM

Manoj G said:

Brian, those are very valid thoughts and I do agree with you. The comparison between languages must always be made in an academic sense and nothing else As you have pointed out, it should not create a divide between programmers based on their abilities.
It is kind of racism in the developer world that way.

To that end, I have just tried to compare languages (C# V/s VB) in my blog, for more of an academic interest. If, by any chance, any entry portrays discrimination of any sort, I need to change that right away.
# August 12, 2004 11:30 AM

Manoj G said:

good article. but do you not forsee the problem of deciding which type an assembly falls in. now the developer needs to understand what type of assembly that he is going to write and how to mark it.

and more over..i think this feature raised from VB, where a dll can be specified with a compatability (server,binary..those 3 options in project properites).

if you check the naming convension, do i need to put in the version in my file name?? does that look good?

anyway..when i thought of a solution for easy to switch back to previous version, when new version breaks any app, the administrator should be able to select which version to bring back in. as i visualize, the admin should open up the properties of the assembly, and select the version he wants. this may be diff to implement, but eases deployment and maintenance.
# August 19, 2004 1:17 PM

Manoj G said:

"In VB6, as you all know, applications are compiled into P-Code (Pseudo Code) and not native code."

This statement is not true. VB6 has a P-Code option but
a decent developer will use the Native Code option.

VB6 is one of the best IDE tool in terms of development speed for the compilation to native code. Except for VC.Net,
the rest of .Net series (including VB.Net) cannot compile to native code.

From this point, VB6 is far superior than VB.Net for windows application development.
# August 20, 2004 7:20 AM

Manoj G said:

Thanks for the correction, Josiah. I suppose, I just need to add the phrase "in debug mode" to that sentence. I'll change that right away.
# August 20, 2004 12:11 PM

Manoj G said:

Another use would be to use StackFrame and StackTrace to do whitebox testing.
# September 24, 2004 1:10 AM

Manoj G said:

This is so the previous version can be compared with the version in the form collection to determine if the TextChanged event needs to be fired.
# September 29, 2004 3:21 AM

Manoj G said:

Thanks for the tip.
# November 29, 2004 11:57 AM

Manoj G said:

Nice aricle for the beginers.
# November 30, 2004 6:32 PM

Manoj G said:

nice but i want to know how index is invoked
# December 10, 2004 6:38 PM

Manoj G said:

Hi,
My application has registered a file type with it so if i double click its file in Windows Explorer, the application is launched.

Now once I have an applicaiton launched, I would like that when next time some other file of same application is double-clicked, instead of loading a new instance of application is loaded, the same old instance is launched showing contents of new file.

How do I do that? It would be a great help if you can mail me the solution on my email address ginve above in the Name field.


Thanks.
# December 22, 2004 1:18 PM

Manoj G said:

Can indexer declarationion take parameter other than int.
Can we write like this?
public int this [string index] {

}

What properies of arrary does indexer support?

# December 23, 2004 3:59 PM

Manoj G said:

# December 30, 2004 1:10 AM

Manoj G said:

Good One ! Thanks!
# January 4, 2005 4:23 PM

Manoj G said:

I do not think its less error prone, in fact I'd suggest for basic cases like this it is more error prone. However I do agree that it is a better method, especially when it comes to updating code or making certain string formats configurable from outside the method that it will be called in.
# January 13, 2005 8:12 AM

Manoj G said:

Hi

I want to start a console application which takes an command line argument from the windows service.

The code is given below
ProcessStartInfo processStartInfo = new ProcessStartInfo('abc.exe', '434');
processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
processCollection.Add(Process.Start(processStartInfo), false);

The above throws an error :

{System.InvalidOperationException}
System.SystemException: {"The Process object must have the UseShellExecute property set to false in order to use environment variables."}

The console application is in the same path as the windows service.
To solve this problem if i use processStartInfo.StartInfo.UseShellExecute = False ;
stmt will it solve the purpose ???

Pls reply to sugaz@rediffmail.com

Thanks
Sugavaneswaran S






# January 13, 2005 10:57 AM

Manoj G said:

Sugavaneswaran

Simply, don't fill processStartInfo.WorkingDirectory. The started process will default start in current dir.
# January 27, 2005 4:24 AM

Manoj G said:

sorry but this is comment spam from a fellow MVP.
it was posted by an automated bot i wrote.
it uses AI to beat the CAPTCHA test.
i have written an article about it here.
http://www.brains-N-brawn.com/aiCAPTCHA
# January 30, 2005 11:20 PM

Manoj G said:

Hi..

I create a window service and override the onStart method with these lines:

eventLog1.WriteEntry("testttt");
try
{
ProcessStartInfo psi= new ProcessStartInfo(@"E:\test.txt");

Process.Start(psi);
eventLog1.WriteEntry("started");
}

catch(Exception e)
{
eventLog1.WriteEntry(e.ToString());
}

I started the service and check the event viewer. Two log entries is created, "tessstt" and "started" is there, but the test.txt file never appear...

I have tried to start the process( E:\test.txt) in console application and it works fine.

Is there any difference and how to start a process in the window service

Thank u in advance for the help ,
Marissa
# February 27, 2005 8:35 PM

Manoj G said:

Hi
how to start the IE.exe from within a C# application with a specific location, hight and width for example?
Thanks
# March 4, 2005 7:42 PM

Manoj G said:

Have you had any experience with .NET 2.0 systems.transactions namespace?
# March 7, 2005 8:19 PM

Manoj G said:

Just came across this post while looking for the "{{" escape format... Thanks! But I couldn't help but see you were using string.Format to construct a SQL statement. :O I have just given a talk with the ASP.NET team about SQL Injection attacks (http://www.styledesign.biz/weblogs/macinnesm/archive/2005/03/07/312.aspx) and while I appreciate this is just an example, developers might come across this usage and think its ok. NEVER use string.Format to construct SQL statement as this leads to a major security vulnerability in which users may take complete control of the database.
# March 15, 2005 3:39 PM

Manoj G said:

I have the same problem with windows service. When i run Process.Start("notepad.exe"), i cant open a notepad window but the i see the process running in task manager. Pls email me at prasad32377@yahoo.com if you have a solution.
# April 15, 2005 4:55 AM

Manoj G said:

You need to allow services explicitly to interact with the desktop if you want to display a notepad when you execute Process.Start("notepad.exe") from windows service. Inorder to do this, right click on the service that you are running and click on properties. Under LogOn tab, check "Allow Service to interact with Desktop". This should do the trick. If you have any questions, email me to prasad32377@yahoo.com
# April 15, 2005 5:32 AM

Manoj G said:

Don't forget, ReSharper 2.0 *WILL* support VB.NET and ASP.NET -- ReSharper 2.0 will be released for both VS .NET 2003 & 2005 ...

You can see the complete ReSharper 2.0 plan at:

http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+2.0+Plan

All the best,

David Stennett
JetBrains, Inc.
# April 15, 2005 2:11 PM

Manoj G said:

Thanks for the update, David. 2.0 would be even more promising and I am eagerly looking forward to it!
# April 15, 2005 2:37 PM

Manoj G said:

very well written!
# April 22, 2005 6:45 AM

Manoj G said:

Hi

I try to run a bat file in aspx but It doesn't work. I tested with imporsonation but still the process uses ASPNET account. Do you know how can I specify which user the process should use?

thank you
# April 26, 2005 8:01 PM

Manoj G said:

Another example of Strategy within the BCL:

http://blogs.ugidotnet.org/adrian/archive/2004/05/04/1353.aspx

In this category of posts on my blog (http://blogs.ugidotnet.org/adrian/category/309.aspx?Show=All) you can find some other patterns implemented within the BCL
# April 30, 2005 7:05 PM

Manoj G said:

Thanks for the lines:

...you can specify a name by means of an attribute as shown below:

[System.Runtime.CompilerServices.CSharp.IndexerName("Widget")]


I'm new to C# and still finding my way around :-)
I'd like to have the option to use either syntax:
Collection.Item(counter).Name
or
Collection[counter].Name

but after I'd added the indexer the complier kept on complaining that my code already contains a definition for 'Item'.
I added the attribute:

[System.Runtime.CompilerServices.IndexerName("Widget")]

and they were both able to co-exist.

Thanks again
# May 12, 2005 8:29 PM

Manoj G said:

Just wondering how could that make difference to building sql statements using string.format v/s. a simple method of constructing string using sinlge quote and double quotes.

:)
# May 15, 2005 3:15 AM

Manoj G said:

For anyone running anything behind a windows service, you have to allocate a console handle in order to see the window. An easy way to do this is to select the "Interact with desktop" setting on the service. Hope that helps...
# May 20, 2005 10:28 PM

Manoj G said:

I'm not sure a different slot for CallContext is used only in crossing different AppDomains; it might appens the same in crossing a Context or even a Thread.

If you disassemble HttpContext.Current.get, you'll notice it does a "return CallContext.GetData("HtCt");", but if you check Thread.CurrentContext in a ASP.NET application, it's always 0 -- default context. And same AppDomain.

So the named-slot for CallContext is thread-aware, not only Context- and AppDomain-aware.

Unfortunately, MSDN does not documents this clearly.

If you have feedback my email is systemshock AT tiscali.it.

Thanx, bye!
# May 22, 2005 7:36 PM

Manoj G said:

Great to know to that you are moving towards test-driven development. I am also in the process of moving towards test driven development. Whatever you have mentioned is very true, that we need to write the test cases before we start writing our code. Otherwise, no point in writing test case, i have experienced it very much.

Previously i hate testing. Though, it is functional testing or unit testing... but after reading/trying test driven development, i realized the importance of unit testing...

In future, we will share about some of our learning in test driven development..

In addition, i am working on VSTS unit testing framework. It rocks.. if you get time, try it out....

# May 24, 2005 10:18 AM

Manoj G said:

Simple and Easy to understand
# June 16, 2005 4:56 PM

Manoj G said:

Don't use String.Format --OR-- string concatenation. To protect from SQL Injection as mentioned above, always use Parameters. You can even use Parameters in text commands, they don't have to be stored procedures. Parameters also have a convention as easy to use as the {n} format used in String.Format. With SQL Server, use regular SQL variable like @EmployeeID and with others use the ODBC ? as a placeholder.
# June 19, 2005 8:54 AM

Manoj G said:

> For anyone running anything behind a windows service,
> you have to allocate a console handle in order to see the
> window. An easy way to do this is to select the "Interact
> with desktop" setting on the service. Hope that helps...

Is there any way to have this option as the default using a .Net setup project?

It would be annoying to expect an end user to have to modify a service after an install.
# July 18, 2005 1:11 AM

Manoj G said:

Hi,

sorry but I think I am bit too slow to understand the advantages of this pattern.

What do you get by using the strategy pattern instead of defining an interface and a bunch of classes implementing the interface?

Thanks.
# July 29, 2005 4:59 PM

Manoj G said:

Ken:

The ServiceInstaller class doesn't offer you an easy way to do this, oddly enough. You have to set the registry key yourself. Here's a code snippet that you can put in an overridden Install() method of your project installer class (after calling base.Install())

Microsoft.Win32.RegistryKey ckey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + this.serviceInstaller1.ServiceName, true);

if(ckey != null)
{
if(ckey.GetValue("Type") != null)
ckey.SetValue("Type", ((int)ckey.GetValue("Type") | 256));
}

You do a bitwise OR with 256 on the Type value. That sets that little flag!
# August 4, 2005 10:21 PM

Manoj G said:

I have some problems with redirecting StandardOutput of process under windows service.

Here is code that starts the process:

Dim proc As Process = New Process
Dim output As String = ""

proc.StartInfo.FileName = "backup.cmd"
proc.StartInfo.Arguments = args
proc.StartInfo.RedirectStandardOutput = True
proc.StartInfo.UseShellExecute = False
proc.StartInfo.CreateNoWindow = True

proc.Start()
output = proc.StandardOutput.ReadToEnd()
proc.WaitForExit()

proc.Close()

Return output

Can you recommend something to solve this problem ?
# August 17, 2005 5:17 PM

Manoj G said:

Ops... Just forgot to mention the problem itself.

In case that code executes under regular application everything is ok, but when it is executed under windows service output is empty

May be processes under services has some restrictions ?
# August 17, 2005 5:28 PM

Manoj G said:

Hi,

ive got similar problems that the ones above. I have a Windows Service which downloads a msi file from a server. After downloading the file it has to be installed/executed. I'm not able to have it installed properly. The problem is, that the Directories are created correctly and the files are also copied to the right place, but somehow the Application is not installed properly. It doesnt appear in Add/Remove Programs and the entry into the startmenu is also missing.

If i run the msi file manually within a shell using msiexec or using directly the msi file everthing works great.

Does anyone know what the problem is here? Any help is greatly appreciated.

Thanks in advance

Jens
# August 25, 2005 8:38 PM

Manoj G said:

Is there a Max to SetMaxThreads?
# October 14, 2005 5:20 PM

Manoj G said:

Hi Manoj

I have been reading your articles for the past 6 months fasicnated by it.I am influenced by your efforts and motivated to get an MVP.Let me know how i can reach you.I appreciate your efforts towards the Microsoft World

Arun
# October 22, 2005 8:15 AM

Manoj G said:

In general the threadpool does a good job of not creating extraneous threads where they are not needed, using internal heuristics. Thus I would expect that most people won't need to modify the max value (unless it is too low).

Yes, there is a logical max to SetMaxThreads -- it is a C# int.
# November 12, 2005 12:36 AM

shayke said:

Hi
Is this the best way to switch context between threads??

Shayke
# December 18, 2005 5:31 AM

Dave Reed said:

It's also because, say you have the textbox in a placeholder or panel that is only visible at certain times during the usage of the control. Without viewstate the textbox would lose its value if the users posts the form while it is not visible.
# February 18, 2006 11:12 AM

Dmytro said:

Thanks a lot, really handy technique.
# March 1, 2006 4:25 AM

saptarshi dutta said:

Good article...
Keep it up..

Saptarshi dutta
Kalyani
# March 6, 2006 3:44 AM

akshay said:

Thats cool...
I was looking at creating a MSMQ listner... This will help a lot.

One question I have : Is can you share any ideas; if I wish to create multiple listener to the same queue, is there are way to synchronize these listners sitting on different machines...
i.e.
Server A and Server B are listening to the same queue, will both the servers recieve an event when a messge arrives on the queue. Yes they would. - How can I ask one of the servers to process and the other to stand down...

Any Ideas ???

Thanks
Akshay.
# April 25, 2006 9:45 AM

Geoff Tewksbury said:

I just recently started playing without Message Sinks and interception. I am impressed with how much control you have. However, I have run across a situation I need some help with. I understand that interception works within a particular 'Context'. What I want to be able to do is intercept private methods on an object. However, since these methods are called from within a 'Context' of the object, I can only intercept the public method that calls into the private methods, but not the private methods themselves. Is there a way to do this? Can I somehow create new 'Contexts' for the object and intercept the private method calls that way?
# May 11, 2006 11:28 AM

Ravi said:

Hi,

i am tryig to do an async peek, by calling BeginPeek, the Peek Complete event get triggered immediatly after a call to BeginPeek, even though the Queue is empty.
and when endPeek is called, it throws an exception, with no message, but, it has a MessageQueueErrorCode : 0xC0000120

I was getting this exception.
Then after Searching found ur code. then again i am getting the same exception.
Any Idea?

Regards
B, Ravi Shankar
# June 27, 2006 6:44 AM

sloan said:

manoj g,

thanks.. that really, really helps with my msmq development.

I added one overloaded constructor.... since I binary format my objects. (below)
(and theres a small spelling error: FireReceiveEvent)

but minus my caveat, this thing works great.

There's probably a hole with .. if you use the overload and set the Types[] , so don't trust my implementation too far.

public MSMQListener(string queuePath)
{
this.ConstructorCommon(queuePath);
}

private void ConstructorCommon(string queuePath)
{
_queue = new MessageQueue(queuePath);    


//non manoj stuff//MessageQueue.EnableConnectionCache = false;
//non manoj stuff//this._queue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
}

public MSMQListener(string queuePath , System.Messaging.IMessageFormatter formatter)
{
this.ConstructorCommon(queuePath);
this._queue.Formatter = formatter; // Customize the formatter type
}
# July 21, 2006 4:10 PM

Sharath M.S said:

Hi Manoj,

Wouldn't LINQ simplify this even further with lambda expressions? I think the following piece of code does the same

var accounts = GetAllAccounts();
var mailList = accounts.Where(a => a==0);
mailList.ForEach(account => SendMail(account, "Be aware, you now have a zero balance"));
# August 29, 2006 9:26 AM

Manoj G said:

Well, I got the clarification from the man himself..Paul Wilson. The Text property of the Textbox control is stored in ViewState cos it is required by the OnChnage server side event.
# August 30, 2006 12:23 AM

sloan said:

Ravi, I was able to put the fix in this way: In the OnPeekCompletedMethod .. I added the following (extra exception handling) code: catch (MessageQueueException msmqex) { switch ( (int)msmqex.MessageQueueErrorCode ) { case -1073741536: Console.WriteLine("Msmq Error -1073741536 : Sleeping, and then ReListening"); System.Threading.Thread.Sleep(3000); StartListening(); break; default: trans.Abort(); throw msmqex; //break; } } catch { trans.Abort(); } The issue is that there is a missing enum value for -1073741536 See this url: http://www.koders.com/csharp/fidE632059BF610D9D912C019A96DCF7A2DD76C847F.aspx
# September 18, 2006 4:56 PM

uuyytt said:

I have the same problem with windows service. When i run Process.Start("notepad.exe"),event I allow services explicitly to interact with the desktop. PS. This problem occur only on windows 2003
# October 4, 2006 3:35 AM

uuyytt said:

I have a Windows service from which I want to start Internet Explorer with a particular URL as an argument. It can work well except when I run it on windows 2003 I allowed services explicitly to interact with the desktop and I tested with imporsonation but still not work. I don't know why my code (shown below) doesn't work. I know that IExplore.exe starts as I can see it in my task manager, but it is not visible. Can anyone explain what is happening? My code: protected override void OnStart(string[] args) { Process p = Process.Start(@"C:\Program Files\Internet Explorer\IEXPLORE.EXE", m_strURL); }
# October 4, 2006 4:09 AM

Nits said:

I am trying to print a pdf file using the following code... It does not throw an error but does not print either when the applicationo s hosted in a web server and is executed from a client machine Please help... System.Security.SecureString secureData = new System.Security.SecureString(); secureData.AppendChar('B'); secureData.AppendChar('l'); secureData.AppendChar('a'); secureData.AppendChar('c'); secureData.AppendChar('k'); ProcessStartInfo process; Process adobeProcess; Boolean isRunning; DateTime startTime; DateTime timeOutTime; string arguments = "/t" + " " + filename + " " + printerName; process = new ProcessStartInfo(acrobatReaderPath, arguments); process.CreateNoWindow = true; process.RedirectStandardOutput = true; process.UseShellExecute = false; process.WindowStyle = ProcessWindowStyle.Hidden; adobeProcess = new Process(); adobeProcess.StartInfo = process; adobeProcess.StartInfo.UserName = System.Configuration.ConfigurationManager.AppSettings['reportusername'].ToString(); adobeProcess.StartInfo.Password = secureData; adobeProcess.StartInfo.Domain = 'itlinfosys'; startTime = DateTime.Now; adobeProcess.Start(); Thanks
# November 4, 2006 12:10 AM

Albert said:

Is it possible to get a reference to the instance  where the method is being called?

# November 14, 2006 10:30 AM

Roark said:

One good thing about using an anonymus method is that it allows you to access locals from the enclosing scope. With a first class delegate you cannot pass in any search parameters to the collection, but with anonymity you can easily use whatever local variables you need from the outer method as your search parameters

# November 30, 2006 5:09 AM

Dharan Prakash said:

Hi Manoj,

Can you please give me an answer or references for Akshay's question? i.e

Server A and Server B are listening to the same queue, will both the servers recieve an event when a messge arrives on the queue. Yes they would. - How can I ask one of the servers to process and the other to stand down...

Thanks

# December 1, 2006 5:50 AM

Manoj G said:

Hi Akshay,

Transactional Receive should solve your problem.

Thanks,

Manoj

# December 2, 2006 8:48 AM

swnuwangyun said:

Applications should be capable of hosting ASMX without having to rely on the services of IIS.

# December 18, 2006 11:19 PM

Simon said:

Interoperations allows import the Kernel DLL functions CreateFileMapping and MapViewOfFile and use them even in C#. However related pointers should be defined inside the unsafe blocks. I've never seen that a pointer, which has been allocated by native Kernel function was

moved - vice versa would be strange.

The only, that must be added are mutexes, in order to control access to the shread memory files.

Of course, it is against ideology of C# and the

direction, but it is the case,when it must be done to solve serios tasks.No one of C# IPC methods does not provide same performance as shared memory for example-when a writer process

writes data and reader process uses it. Generally the "management" ideolgy and super wrapping of C# seems to me like a car with automated transmission for a driver, which can use only automated transmission. Could the tandem participate in a serios rallies?

# December 20, 2006 11:30 AM

Simon said:

Interoperations allows import the Kernel DLL functions CreateFileMapping and MapViewOfFile and use them even in C#. However related pointers should be defined inside the unsafe blocks. I've never seen that a pointer, which has been allocated by native Kernel function was

moved - vice versa would be strange.

The only, that must be added are mutexes, in order to control access to the shread memory files.

Of course, it is against ideology of C# and the

direction, but it is the case,when it must be done to solve serios tasks.No one of C# IPC methods does not provide same performance as shared memory for example-when a writer process

writes data and reader process uses it. Generally the "management" ideolgy and super wrapping of C# seems to me like a car with automated transmission for a driver, which can use only automated transmission. Could the tandem participate in a serios rallies?

# December 20, 2006 11:31 AM

. said:

The ProgressChanged and RunWorkerCompleted Events will not allways be handled on the thread the BackgroundWorker was created on.

This depends on the SynchronizationContext of the thread where the Backgroundworker was created on. For Windows.Forms threads this is true, because the WindowsFormsSynchronization Context actually uses Control.Invoke and Control.BeginInvoke to marshall calls to the coresponding thread.

But from a thread with just has a standard SynchronizationContext, the send and post method of this context do not marshall the call to a specific thread!

Regards

# December 28, 2006 5:14 AM

TRe said:

TLS serves storage for physical threads, not logical threads.

You should store the transaction in manner that is logical thread specific:

<ThreadStatic()> _

Private Shared _Transaction As IDbTransaction

# January 22, 2007 8:32 AM

Rahul said:

I am using the same code and created windows services in my local system but if i run my windows service to receive the message. Access denaid the  error message i got.

Can u specify the the format name for the Queue Path. Or any security setting has to be enabled.

# February 28, 2007 11:11 PM

Jay said:

Hello MVPs,

I have a problem where opening a word document using Process.Start("filename") throws a Win32Exception as below

See the end of this message for details on invoking

just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************

System.ComponentModel.Win32Exception: Access is denied

  at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)

  at System.Diagnostics.Process.Start()

  at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)

  at System.Diagnostics.Process.Start (String fileName)

I tried using Regmon to track any registry access denied, but could not find any problem,

or may be there is some other error i should be looking for.

This error occurs only on specific machines (laptops) and works well for other machines.

Any help on this topic is highly appreciated :)

Thanks,

Jay

# March 14, 2007 10:00 PM

anonimoatacante@yahoo.es said:

Have you sample code ??

# April 18, 2007 3:52 PM

carry said:

i m facing the same problem..my process is not running any application in windows service and run under normal applicatin..can u tell me the solution please..i need it urgent

# April 19, 2007 10:43 PM

Željko said:

This works for winforms apps only, since there is only one implementation of sync context. In a console application, SynchronizationContext.Current is always null.
# April 24, 2007 7:35 AM

Filip said:

Nice code, would you be able to provide an example of the test class as well on how to call this? (Sorry, I'm a c# beginner)
# June 3, 2007 9:08 PM

Dave said:

In a response to Ken, and also to fix the issue, I would like to know why I have to tick and untick the Interact checkbox to make it work. (The code does make it ticked but as no effect).

I've also noticed other ControlSet in the registry,

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\MYSERVICE

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Services\MYSERVICE

Should I change the value for these also.  

Why do I need to go under services and untick, tick again, apply to make it work ???

floyd us 27 a t hotmail d o t com

Thanks.

# July 20, 2007 9:37 AM

VIRAJ said:

It's a really nice explanation to the point. Thnks in advance

Regards

VIRAJ

# July 26, 2007 2:43 AM

JM said:

I worte a Q listener as a window service, it is working for read the local transactional Q. But when I cluster the MSMQ, the Q listenser service can not read the Q any more.

any idea why?

# August 7, 2007 8:55 PM

kamran said:

winservice starts the process (Application) but does not bring it to interface. i ve checked Interact with desktop

but doesn't work

using win-XP

VS-2003

# August 26, 2007 6:34 AM

roberto said:

I have a problem with windows service. When i run Process.Start("iexplore.exe"), i cant open a iexplore window but the i see the process running in task manager. This services running under windows server 2003, and have checked Interact with Desktop, but doesnt work. My email is roberto@t2o.es . If someone can help me, send me a email please. Thank you for you colaboration.

# September 26, 2007 6:37 AM

Roiy zysman said:

SNIP is not always the best way to protect your code.

Check out this article

blogs.msdn.com/.../196590.aspx

Thanks

Roiy

# September 30, 2007 2:14 AM

Sloan said:

//Quote//

I am using the same code and created windows services in my local system but if i run my windows service to receive the message. Access denaid the  error message i got.

Can u specify the the format name for the Queue Path. Or any security setting has to be enabled.

//End Quote

You have to go thru "Manage Computer" and find the Queue.  And give permissions ON THE QUEUE...to the "SYSTEM" account (the SYSTEM account local to that computer).

You don't have to do "Full Control", but Send/Receive are necessary.  I usually give Get/Set Permissions as well.

# October 3, 2007 9:16 AM

Neeraj said:

Hi,

I have the ollowing code running for runing a console application:

Process myProcess = new Process();

           ProcessStartInfo info = new ProcessStartInfo(appName);

           myProcess.StartInfo = info;

           myProcess.StartInfo.UseShellExecute = false;

           myProcess.StartInfo.RedirectStandardOutput = true;

           myProcess.StartInfo.RedirectStandardInput = true;

           myProcess.Start();

           myProcess.WaitForExit();

Here I am passing the names of different console applications in the ProcessStartInfo.

My Problem is that the console application starts, but within a second closes, though when I run this application as a standalone, it runs properly.

Please Help somebody

# October 17, 2007 1:30 AM

Wei said:

Nice to read that..  I was confused about mybase and myclass.

# October 31, 2007 9:56 AM

Zeina said:

Dear,

I have a batch file that runs Adobe.exe application. Executing this batch file from a Windows Application worked fine and the output of the Batch successfully achieved whereas the same code called from an ASP.NET application doesn’t work. The exe is displayed in the Task Manager but doesn’t execute the code it should and the user runing this service is the Administrator.

Apparently it is a security issue sine the problem occurs when hosting the application in IIS but I have tried working with all the permissions and it didn’t work. The Identity of the pool of the web site is Configurable with the System Administrator Credentials.

Many have the same problem but none has listed the solution. This is very urgent, so pleaseeeeeeeeeeeee help :(

Thank you,

Zeina

# November 2, 2007 10:52 AM

Laoujin said:

You could just use string concatenation you just have to be careful to escape any possible attacks.

string.Format("SELECT * FROM table WHERE field='{0}'", userInput.Replace("'", "''"))

I'm sure there are better methods then the Replace in .NET but that would be perfectly save.

# December 19, 2007 5:05 AM

Darrin said:

This article's attitude is indicative of the overall contempt that C/C++/C# developers had for VB6, even though it filled a need for quick business application development. (where requirements change constantly... hello, real world)

Thus, we ended up with lack of path from VB6 to VB.NET, all because a bunch of eggheads at Microsoft thought they new better than the marketplace!

E.g. Optional parameters

Ok, its somehow better that I write a dozen overloaded methods when a single method with Optional parameters would've done... VB.NET creates the overloads behind the scenes for you.

Why do you C# guys like writing so much code?  I can't figure it out?

# December 21, 2007 12:08 PM

Keith said:

[assembly:InternalsVisibleToAttribute("MyFriendAssembly, PublicKeyToken=45cb56a45e0a69a1")]

You cannot use PublicKeyToken with a signed assembly

you need to use public key.

Keith

# January 6, 2008 12:51 PM

Rohit said:

Does any one know a way in which the new process just created can be debugged (in Visual studio) ?

# January 9, 2008 12:23 PM

Threading in .Net 2.0 said:

Pingback from  Threading in .Net 2.0

# January 15, 2008 7:04 AM

Jeremy said:

Hello,

i'm trying to do something like this, and i want to acces to the argument's instance of the invoked method.

I can access to the metadata (Type, Name) but i can't access to the value when the method is invoked.

How to do this ?

(Sorry for langage i'm not english :P)

# January 17, 2008 4:22 AM

Martin Golding said:

>>But from a thread with just has a standard

>>SynchronizationContext, the send and post method of

>>this context do not marshall the call to a specific

>>thread!

Does a standard SynchronizationContext enable the ability to marshall to the original thread?

All of my test code says no, If I output Thread.GetHashCode() and write test code I can see when using ctx.Post, it always uses the running thread ID and not the one I want to marshal to.

# February 14, 2008 8:12 AM

Ulf said:

Hi,

I have a question or need to get some thing confirmed because I'm a bit unsure about this.

Looking at Lance Hunts guideline paragraph 4.4 the example says

// Bad!

catch(Exception ex)

{

Log(ex);

throw ex;

}

// Good!

catch(Exception)

{

Log(ex);

throw;

}

As I understand it is not possible to do as in the good example, since ex is not declared. Or am I wrong?

If I do the good example as you do it, it seems that I get the same result. I'm I right about that?

// Good! (Modified)

catch(Exception ex)

{

Log(ex);

throw;

}

# March 12, 2008 11:07 AM

visitor said:

2 points.

1. watch out for {0) which looks a lot like {0} which if you're typing fast can happen quite frequently...will result in a very strange message you could end up surfing around for hours trying to find what's wrong...not that that's happened to me or anything.

2. as far as sql injection we do something like this:

String.Format("sql goes here where id = {0}", SqlTool.StringToSQL(m_String));

and have a separate class that handles the '' stuff... this allows you to escape things neatly behind the scenes, still use string.format, and keep code consistent, and still use intellisense to make things speedy...

# April 23, 2008 9:50 PM

Nicolas Repiquet said:

FindAll allocate, populate and return a new List, plus the syntax is quite unclear.

foreach( Account account in GetAllAccounts() ) {

 if( account.Balance == 0 ) {

   SendMail( account, "Be aware, you now have a zero balance" );

 }

}

Done.

# October 1, 2008 9:33 AM

Satpal said:

Thanks for support

# October 25, 2008 12:16 AM

mani said:

nice work.......

nice explanation with good examples..

# December 25, 2008 2:00 AM

Seb said:

Same probleme... It's impossible to start a program when i user windows service. ( Even if i check interract with destok)

# June 25, 2009 3:20 AM

Akansha said:

very helpful post - used this info to get powershell commands to run from a C# app!!

# September 3, 2009 2:08 PM