Showing posts with label tip. Show all posts
Showing posts with label tip. Show all posts

2010-04-12

Visual Studio 2010 installation

If you get
---------------------------
Microsoft Visual Studio 2010 Ultimate Setup
---------------------------
Some components must be installed in c:\Program Files\Microsoft Visual Studio 10.0\ directory. Check that you have write permissions and enough space in that directory.
---------------------------
OK
---------------------------
when you try to install Visual studio 2010; don't despair.
There is a big chance you try to install from a mounted virtual disc.

The resolution is to copy the files in the mounted disk to real files and run it from there. One could possibly also assign the mounted disk a letter but I haven't tried this.

I have learned that there is also some problem when installing from a network share. The symptom is something about a .cab file with a faulty digital signature.

2010-03-16

Coderush and camelCase and select

I am a long time fan of DPack. Some time ago Coderush stepped up to a must-have.

The other day I noticed that Coderush did camel case selection. It is like this:
Open the Vsnet editor with your favourite project and go to a camelCased or PascalCased word. Select it with ctrl-shift-right/left. This is old news.
Now instead use alt-shift-right/left; only a part of the word is highlighted. Perfect when copy-pasting variables like CustomerName and SerialNumber.

Coderush comes both in gratis and pay versions.

2010-03-04

Checking events in VBNet

Due to some reason unknown to man the team behind VBNet decided that the developer should not be able to see if someone listened to your event or not. It is good in most cases but very bad in another.

In Csharp raising an event goes something like this:
var ev = MyEvent;
if( null != ev ){ ev( this, args ); }


Just look through the snippets (look in the context menu in the editor) and you will find the correct way to raise an event in Csharp.

VBNet on the other hand hides the if statement and the temporary variable from the developer. It is enough to write
RaiseEvent Me, args
and the event will be raise if there is someone listening - no need to check for null.

But what if you want to check if someone is listening. In my case I needed to know if the custom control was properly wired into the scaffolding of the application; the user control sometimes whished for more information and I had to know if someone was listening.
In Csharp this would have been easy with a check for null. But VBNet...

The solution is hidden. Just check the variable "MyEventEvent". This means that your MyClick event has a hidden variable MyClickEvent that you can check for like this:
If MyClickEvent IsNot Nothing Then

I don't like to use hidden and unoffical solutions but this is the only way I know of.

Honor those who should.

2010-02-04

DesignMode in Visual Studio, inheritance, process name and a work around

The text and code below is only tested for Winform. WPF might behave differently; hopefully behaves differently.

I won't go into any details on why the ISite.DesignMode is good and sometimes even crucial to have. It is much better done in the link at the bottom.

First out there is unfortunately a caveat with DesignMode, it doesn't work with inherited forms and user controls. This is a problem since I always inherit from the base form in my projects and tell others to do the same. It also doesn't work inside the form's or the user control's constructor and then by any method that is called by the constructor. Long call chains to might make this hard to track down.
Secondly there is another way to check for design mode and that is to check for the LicenseManager.UsageMode but this in turn doesn't work in event handlers.
Thirdly one can set a flag in the base Form and base UserControl. But this doesn't solve the problem since we cannot be sure with what to set this value.
Fourthly is a workaround where one can check for the name of the process itself which is Visual Studio's process name (devenv) in case of design mode. This process name might change in future releases of Visual Studio and is also different for other IDEs.
Fifthly is other process information like the name of the module and stuff. Check into the Process and you'll see that the app is called MyApp.vshost.exe while being debugged.

The fourth solution (processname=devenv) seems to be the most viable but I believe there is something useful in the fifth (other process information). There must be a way to notice that the name of all your code doesn't match the name of the running environment; namespace, assembly name, whatever. I still haven't figured out how though.

Below is some code to copy-paste.
It is not 100% correct though since the DesignMode property isn't virtual. This might end with some really tough-to-track-down bugs where one iterates the forms but don't get the overloaded DesignMode flag. The code also doesn't promise to work forever since there is a magic string naming the name of the Visual Studio process.


public partial class MyAppForm : System.Windows.Forms.Form
{
protected new bool DesignMode
{
get
{
return HelperMethods.IsDesignMode(this);
}
}
}

public partial class MyAppUserControl : UserControl
{
protected new bool DesignMode
{
get
{
return HelperMethods.IsDesignMode(this);
}
}
}

class HelperMethods
{
public static bool IsDesignMode(System.ComponentModel.Component x)
{
var site = x as System.ComponentModel.ISite;
return
( null == site ? false : site.DesignMode ) ||
System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime ||
System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";
}
}
The code above is also in pastebin for easier copy-paste.
A good article is here: http://dotnetfacts.blogspot.com/2009/01/identifying-run-time-and-design-mode.html
There is a description of how to debug this here: http://brennan.offwhite.net/blog/2006/08/30/design-time-debugging-aspnet-20-in-visual-studio-2005/

2010-01-28

Share a file in Visual Studio

I didn't think it was possible but it has been for years; to share a file between projects in a solution.

Add a file the normal way but instead of pressing Open, use the little dropdown arrow next to.  Then you have the possibility to "link" instead of "add".

This makes it possible to have one and only one file for many places.  It can be a source code file or a readme or anything really.
I have yet to try it with TFS and SVN to make sure it doesn't mess upp the version management.

Honor those who should.

On a side note: Sourcesafe has linking ability within itself.  I miss it in TFS.  Though: It is easy to lose the master file and keep copies wich makes strange icons.  It also doesn't play well with the VB6 editor when a file will be checked out and another not, but they should be, but the VB6 ide doesn't understand it and you have to do an explicit checkout and... never mind.  It was a long time ago.

2010-01-24

Changed keyboard settings

In Windows 7 (and possibly Vista) the keyboard layout is sometimes changed back to some sort of default.

The problem shows itself like this - I use the 1337 keyboard layout in Visual Studio.  Then without warning the keyboard layout changes to US layout; a layout I don't even have installed.  The 1337 layout is based on US though so somehow it shines through.

To get back to 1337 I choose "Open the language bar" in the systray context menu.  The language bar then pops up in another place (top of screen for me) and I can then choose keyboard layout.

The problem will reappear more times until I reboot again.

2010-01-09

This is my visual setup of Visual Studio.

Notice how the real estate is used for tools I use and not for buttons that just happens to be there by default.

shift-alt-return maximises the window so not even the caption bar is visible.  I know which program I am working in so I don't need to waste the whole top for this.

I have removed all toolbars.  The buttons I need I have put to the right of the menu.

There are also two macros in the menu bar, one for connecting the bugger to nunit and ditto to IIS.

I have set all toolbars to auto hide.  When I debug, the call stack and autos (unfortunately hard to find among the menus with C# projects - open a VBNet project and see what it looks like), toolbox are visible.

I have also moved all toolbars to the right.  When one is working heavily with the forms designer it is good to have the Toolbox toolbar constantly open on the left but only then, and for the 2% of the project I handle the forms I can move it there manually.  The rest of the time I hack code and need nothing but code and debug tools.

I know shortcuts to almost all toolbars.  Those I don't know I don't use that often anyway.  I don't know why some banjo player at Microsoft decided that underlines and shortcut tips should be invisible as default.  Fix it through Tools->Customize.

This way I use all of the precious display area for stuff I have use of.



2009-12-14

String.IsNullOrEmpty

Instead of

    if( null == myString || string.Empty == myString ){...

one can use

    if( string.IsNullOrEmpty( myString ) ){...

There is nothing magic about it, just a more readable, and hence less error prone, syntax.

It would be nice of someone could solve the

    if( null == myCustomer.Address || null == myCustomer.Address.City || null == myCustomer.Address.City.Name ){...

-problem.

In Dotnet4 there will be a method similar to IsNullOrEmpty which also checks for whitespace.  It should come in handy.

2009-12-08

Database versioning

Since I have abandoned Visual studio database edition because of it not being able to handle tables with data I have returned to my old, proven, way; checking in/committing the update scripts and storing a database version number in a Setting table.

In Microsoft SQL Server Management Studio (or whatever it was called earlier) there is a setting to always create update scripts whenever a change is saved.

Then whenever a change is done, store the update scripts with consecutive version numbers.  These versions are not the same as the release versions but one version number per commit.

013_01_S_Customer_Added the CompanyColour field.sql
013_02_D_Customer_Set the CompanyColour to red except blue for McCarthysen.sql
013_03_S_Customer_Set CompanyColour to notnull and no default value.sql
013_99_D_Setting_Updated database version.sq
l

013 is the version number.  Next commit is 014 etc.
01, 02, 03 are consecutive numbers.
99 is the final number for this commit.  It always contains an update in the Setting (or whatever you call it) table and sets the version number record to 13.
S and D are Schema and Data respectively.  I have learned that it is good to see this already in the script's filename.
Customer and Setting are the names of the main manipulated tables.
The rest is free text that explains what the script does.

It is now very easy to see how far a database is in the development flow.  Select the the row from the Setting table and notice its number.  Then run all scripts with higher version numbers in the right order.  The scripts are easy to order by their names directly in the version manager or in the file explorer after a checkout/getlatest.

This technique works well with several developers.  Store the scripts locally until they you are ready to commit the code.  Update the version number if someone already used the version number.  Commit.

A tool like SQL compare does approximately the same job.  If you have only a few updates with a few databases it is way faster to just create a diff-script and run it.  Contrary to VSDatabase edition SQLcompare handles tables with data.  It costs money but 1) there is a trial version and 2) it is way cheaper than hacking the code yourself.
There are other tools as well and I have used one but I cannot remember the name of it.  It was not as easy to use as SQLcompare if I recall correctly.

If you have to handle several versions while developing the procedure I have described here is good since it is so easy to check the version of the database.

(I just stumbled upon a situation where saving a view and only updating the output fields from lower to upper case (customername -> CustomerName) did not result in a script file.  In this case there was no problem in scripting a drop/create script through the Object explorer tool box though.)

2009-11-29

IsNot in vbnet - a more readable way to check for Nothing

When I have written Vbnet and checked for Nothing I have chosen between 

    If Not( o Is Nothing ) Then
        ...

and

    If False = o Is Nothing Then
        ...

and

    If o Is Nothing Then
        '    NOP.
    Else
        ...

all ugly and/or hard to read but in their own way.

Some days ago I stumbled upon IsNot and since then my code looks nicer like so:

    If o IsNot Nothing Then
        ...

I have been writing Vbnet for years without finding IsNot so I thought there are more out there with the same problem.

2009-11-28

Edit project file in VSNet

There are mainly 3 ways to get to your Vsnet project file to edit it.  (disclaimer: I am running Vsnet2008 and haven't tried earlier nor later versions)

1) Open windows explorer and navigate to your project folder.  Open the project file (.csproj/.vbproj/...) in your favourite xml editor.

2) Install a tool that gives you an "Open folder in windows explorer" context menu item in the Solution explorer.  If I recall correctly the tool I am referring to is Microsoft's Team foundation server power tools.  Please correct me if I am wrong.

3) Unload the project.  Use the context menu in Solution explorer to edit the project file.  Load the project again.

2009-11-04

Traverse Corporate Firewalls

Sometimes a solution is so secure it becomes insecure.  The primary example of this is requirements for passwords that are so complex that people write them on a note and stick them under their keyboard.

I have several times been locked into a corporate network where the possibility to cooperate with the outside has made my work more complex and expensive.
Limited email storage and chat protocols that don't make it through the router are things that might hinder my work all the way to effectively stopping it.  A limit of 100 megs of email storage makes it impossible to send large emails without risking filling the mail box of a colleague.  Without chat my communication with competence peers is severed.

A slow internet connection makes every search take longer time or give less thorough result.

Then there are hinderances like forbidden FTP, an email washer that stops binaries and source code, or the stopping of youtube in the firewall.

I live in a world, a community, and we communicate.  A big part of my work is to gather information and spread it to interested parties.  Too many times the rules of a corporation network limits this.  Hence workarounds that don't always play well with security but makes my customer happy.  And that is what it is all about, helping your Customer.

Wired has an article http://howto.wired.com/wiki/Traverse_Corporate_Firewalls that explains some workarounds from the dead simple to way more complex.

2009-10-18

Unable to open the physical file Operating system error 5: "5(failed to retrieve text for this error. Reason: 15105)". (Microsoft SQL Server, Error: 5

Try to attach a database with Management Studio when using Windows 7 and SQLServer 2008 developer edition and one might get an error message similar to the title of the article.

Whether this is a bug or not is beyond my knowledge but the solution/workaround is to connect as SA and not as windows authentication.

Login failed for user 'IIS APPPOOL\DefaultAppPool'.

If one uses trusted connection to a sqlserver database under Windows 7 and II7 one might get the error message "Login failed for user 'IIS APPPOOL\DefaultAppPool'." when trying to run a web application.  There are several articles for this but all points to a different GUI than mine (earlier versions of Windows7/IIS7?).

Fire up Internet Information Services Manager.  (window-iis-return)

Find the Application Pools item in the Connections toolbar.  One can reuse the default application pool or create a new one.  Go for the latter since it is slightly more complicated and hence more fun.


I don't know what the settings above do but they seem to work.

Select your newly created application pool and the advanced settings.  Change the Process model to LocalSystem.
(I had planned to create a "better" account with the proper limited rights but ran out of time.  Someone else...?)



As one can see in the listing above the new application pool runs as different identity than the default ones.

Now change your web application to use this application pool.  This could be made simpler by moving the menu for this to the same place as the other menus.  To make the story short - select your site and look to the right of the IIS manager.



That is all there is to it.


2009-07-13

Xml comment check

In C#/VBNet there is a nifty thing called Xml comments.  I always use it to explain my methods and classes.  A good thing about Xml comments is that they pop up as intellisense.  Press ctrl-J at your method call and your comments are shown.  The comments survive project boundaries so your well crafted comments in the business layer pop up at the presentation method calls to aid the GUI programmers.

The comments don't travel C#->VBNet though.

In VBNet you get squiggly lines when the method call and the Xml comment don't match.  In C# you have to go through the Analyze->Run code analysis to get the differences.

Visual studio database edition - how to think to get started

Visual studio database edition is part of the "normal" Visual studio.  One cannot be totally sure of this since Microsofts licences are as comprehensible as scientology.

I made two tries at it before I got it to work.  Then it failed me anyway, but that is another posting.

The way to think is to think about the database as source code.  You make changes, compare them to the checked in/commited code and let the machine do its magic merge and check in the result.

2009-06-05

Slow sqlserver express

I got informed of something somewhat strange the other day.  Microsoft SQLServer Express runs (connects) faster if you have a query window to the database already.

Like this:

Have a freshly booted machine with only Visual studio running and your web application of choice.  The time for a refresh of you web page might take 5 seconds.

Now start Management Studio and open a query window.  Let it stay open.
Refresh your page and you are down to a second.

The figures might of course change but they are what I have on a dual core 2GHz 4MB machine for a project of size X and database of size Y.

----

I haven't checked if the same thing happens with another script editor like for instance AnySQLMaestro but guess it does.  I guess it has to do with connections - as long as there is a connection to SQLExpress, it doesn't close.  If so, it corresponds with the product's raison d'ĂȘtre, a database for applications.

----

I have noticed a correspondence between debug-start-delay and quality of code.  I say that every second wasted waiting on debug start makes the developer unwilling to test more thoroughly and leads to more bugs in the product.

----

Another trick to make web debug start faster here.

2009-04-17

Timer and GUI

One cannot use the System.Timers.Timer to update the GUI, instead one gets a cross-thread exception. The GUI can't be updated from another thread.

A nice trick to solve this is to use a method that is sensitive for if the call comes from another thread than the GUI is running on.



private delegate void SetTextDelegate(Label label, string text);

private void SetText(Label label, string text)
{
if (this.InvokeRequired)
{
IAsyncResult res = BeginInvoke(new SetTextDelegate(SetText), label, text);
EndInvoke(res);
}
label.Text = text;
}


Honor those who should.

2009-04-11

Attach to a process even faster

In an earlier article I mentioned a time saver for web projects where I recommended attaching to the process instead of restarting every time.

Today I invested time in creating a macro for attaching to the Nunit process.  It was easy.

- Instead of learning all commands just record a new macro (menu->tools->macro->record temporarymacro) and connect to the process of choice.

- Then open the macro explorer (menu->tools->menu->macro explorer) which opens a toolbox.  There is a (new) module called RecordingModule.  Open this.

A new IDE opens with something like:




Sub AttachToNUnitProcess()
' MsgBox("AttachToNUnitProcess.Start")
Try
Dim dbg2 As EnvDTE80.Debugger2 = DTE.Debugger
Dim trans As EnvDTE80.Transport = dbg2.Transports.Item("Default")
Dim dbgeng(1) As EnvDTE80.Engine
dbgeng(0) = trans.Engines.Item("Managed") ' Can be "Native".
Dim proc2 As EnvDTE80.Process2 = dbg2.GetProcesses(trans, "MDG-VILTERSTEN").Item("nunit.exe")
proc2.Attach2(dbgeng)
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
' MsgBox("AttachToNUnitProcess.Slut")
End Sub

- Testrun your macro in Visualstudio just to make sure it runs properly.

- In the macro editor, create a new Module and copy the code you just created.  Rename module and method.  Save.

- Back in Visualstudio, Macro explorer, your new module should be visible.  "Should" - one might have to restart Visualstudio or the toolbox or something.  It should be runnable directly from the Macro explorer toolbox.

- Create a new menu (menu->tools->customize ...) and attach your macro.  You find it under "Categories/Macros", just drag it to your new menu or the menu bar.

Now attaching to a process is just a click or keystroke away.

Some more info is found here: http://msdn.microsoft.com/en-us/library/hdf2d1z8(VS.80).aspx.

Update: I debugged a web app for a while yesterday and Wow! - what a difference between 3 clicks and 1 click, or 3 keystrokes and 1 keystroke.  Besides being simpler it also connected faster when the GUI didn't have to render and didn't have to wait for me.  Why haven't I done this years ago?  What else is there I should have done years ago?

Update: I created a new menu and items for every macro I use.  So Fast to use!
There is something that bothers me though.  Some menues dissappear after I restart VSNet, I don't know why.

The macros are easy to start also without having created a menu for them.  Just alt-F8 and then arrow keys to find the right macro and start it with return.

Macro for attaching to a process

When debugging aspnet solutions a lot of time is wasted on restarting the debugged application.  A real time saver is to connect to the process to avoid restarting.

This is done like so:

- When a new bug is found don't stop the web browser, instead detach from the process (menu->detach->detach all).
- Update the code to correct the bug.
- Set a breakpoint.
- Connect (menu->attach to process->[find the process, it is called something like iis or aspnet]->attach) to the process.
- Reload the web browser.

There are some caveats.  Like when using Webform the viewstate is tightly connected to the controls on the form so it is not always possible to connect.

But for the most times this is a great time saver.