Archive for category How To

Hyper-V: Creating and Managing a Minimal 2012 installation from Windows 7

This is the process I used to create and install a Hyper-V 2012 minimal installation on my network on its own machine and manage it from a different machine running Windows 7. This installation targets two machines on a Workgroup network. Below are the steps taken for each of the machines.

Step Server Client Summary/Links
1 Install Hyper-V on the Server Install Windows 7
2 Rename (Option 2) Name your server something meaningful. I named my “HyperV”. Smile
3 Get IP Address Add Server IP to Hosts file
Windows\System32\Drivers\etc
Allows for quicker access during remote desktop. Note this step may ignored if the Server gets a dynamic IP. If that is the case the suggested option is to change the DNS server/gateway/router or whatever it is on the system to make it static.
4 Enable Remote Desktop for all clients
7) Remote Desktop
Remote to Server If you have issues at this point, pinging the server won’t tell you anything. The server is behind its firewall. See the below section miscellaneous commands to turn off the firewall.
5 5) Do Windows Update Full Get the latest and greatest
6 Download / Install
Remote Server Administration Tools For Windows 7 With Service Pack 1
(link)
This allows you to create VMs from windows 7. Verify that there is not a new version since this blog was written.
7 Follow install instruction’s on the download page (or the W7 Remote admin tools window which pops up after install) to turn on the newly installed windows 7 feature:
Remote Server Administration Tools
Control Panel –> Programs –> Programs and Features –> Turn Windows features on or off –> Remote Server Administration tools –> Select the tools needed (Hyper-V tools)
8 3) Create Local Admin Account the step #3 on the sconfig.cmd shell. This account will be used to access the sever either during remote sessions. Note you might want to use the name of the client computer’s account for the name/password. Otherwise you will need to do an additional step #11 on the client.
9 -Install On Server- -Install on Client- Hyper-V Remote Management Configuration Utility
This is helps minimize the number of operations needed to configure a hyper-v setup on both the server and a remote server operation. Note this will help deduce any problems which might occur. This utility was made for a previous version of Hyper-V and for Windows 7. As of this writing it is being updated to be used on Windows 8. We will be following the 10-second guide on its page for “Client and Server both workgroup” but skipping steps no longer needed since this version of Hyper-V server has some of those commands offered on the initial boot screen.
9 cscript hvremote.wsf /add:{account name used in #8} This step prepares for the remote admin access for hyper-v.
10 cscript hvremote.wsf
/anondcom:grant
Check the script for “Granted Remote DCOM Access to Anonymous Logon” for success
11 cmdkey
/add:servername
/user:servername\account
/pass
This step is only needed if either the client’s account  or even just the password is different than what is done.  (/pass is the actual, though in some situations to save the password use /pass:{actual passsword}
12 cscript hvremote.wsf
/show
/target:{clinetComputerName}
cscript hvremote.wsf
/show
/target:{ServerName}
Identifies problems on either the client or the server.
13 Run Hyper-V manager
Connect to Server
If there is a problem here and one cannot connect to the server got step 12 and investigate.
14 (Hyper-V Manager)
Virtual Network Manager
Setup networking for victuals to access the network. See next step in Virtual Network Manager (VNM)
15 (Hyper-V Manager – VNM )
Add “External” virtual network
Just name the network to use with Virtuals and accept that pending changes may disrupt the network. This may take awhile..so give it time.
16 (Hyper-V Manager)
Create a Virtual!
Dust off that old ISO and create a virtual to remember. Just realize that the browse operation is from the server and not your client.

 

Misc commands

NET SHARE Images=D:\Images /GRANT:Everyone,FULL Create a Share drive.
Get-VMSwitch Lists all the virtual switches
netsh advfirewall set allprofiles state off Turn off the firewall. Note that the firewall on a Hyper-V machine will block any ping from your internal network.
Share

Tags: ,

Silverlight (How To): Manipulation of Dynamic Selection Rubber Band in C#

Large group of women exercising in the parkOne of the basic tenets of WYSIWYG is to be able to create a rubber band region using the mouse to give the user the ability to create a selectable region. This article demonstrates how to do that in any version of Silverlight and the user is given the tools to create such a bounding rectangle in any circumstances via the usage of some basic building blocks in Silverlight.

The below picture (not the one on the left) shows our goal, the dynamic creation of a bounding rubber band (a rectangle control for this demonstration) in a canvas. The below canvas is drawn in black (visually grey due to the opacity set) while the bounding rectangle shows itself in red.

RubberBanding

The user starts the process with an initial click which designates a start location of an upper left point for our bounding box with a mouse click.  Once the click happens the mouse cursor changes to a hand (if moving to the lower right) as a visible indicator that the process has started. While user continues to move to the lower right the band grows and while the mouse button has yet to be let go or released. For the demo a bounded number is shown is which relates the actual dynamic change in the X (horizontal) position. That is done for this article only and the above picture shows the rectangle with an X size of 123 pixels and can still be grown as shown by the hand icon.

Initial Xaml

In the page’s xaml we add a grid and a canvas as such this:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="33*" />
        <RowDefinition Height="267*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="32*" />
        <ColumnDefinition Width="568*" />
    </Grid.ColumnDefinitions>
    <Canvas x:Name="cMain"
            MouseLeftButtonDown="cMain_MouseLeftButtonDown"
            MouseLeftButtonUp="cMain_MouseLeftButtonUp"
            MouseMove="cMain_MouseMove"
            Grid.Row="1"
            Grid.Column="1">
        <TextBlock Width="100"
                    Height="30"
                    Text="{Binding XValue, ElementName=userControl}"
                    />
        <Rectangle Fill="Black"
                    Width="550"
                    Height="200"
                    Opacity=".25"/>
    </Canvas>
</Grid>

The things to note are that the canvas is in a grid which is offset from the initial by 30 pixels in both axis. We then place a rectangle on the canvas which is our area which will be our strike zone where we will intercept the messages mouse events. We have a strike zone because individual controls in a canvas, such as texblocks have whitespace between them and the canvas will not get the mouse clicks and we want to be able to capture the process at all locations on the canvas; hence we fill up the canvas with our strike zone as to be ensured that the events are consumed properly by the code. 

When the user clicks within the strike zone the process starts as signified by a cursor change to the hand, as the user moves within the zone the rubber banding increases and when the mouse button is let up the process ends and the cursor is returned to its previous state.

Initial Properties

Here are the three variables we will use during this process:

private int _xValue;

public int XValue
{
    get { return _xValue; }
    set
    {
        _xValue = value;
        OnPropertyChanged( "XValue" );
    }
}

private Point OriginatingPostionOnCanvas { get; set; }

private Rectangle RubberBandBox { get; set; }

Since the XValue property is reflected on the screen in a text box it reports all changes by using  INotifyPropertyChanged which our class handles in a standard way for notify property (not shown). Followed by that is our initial click location named OriginatingPostionOnCanvas which will dictate the upper left (or lower right) location of the rubber band rectangle which we will dynamically create. The last variable is the actual dynamic rectangle control named RubberBandBox which will be created and modified during the process.

Event Mouse Left Button Down

We will handle three events during this process. The first is the when the user clicks and begins to hold down the mouse button:

private void cMain_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
{
    OriginatingPostionOnCanvas = e.GetPosition( cMain );

    RubberBandBox = new Rectangle() { Width = 1, 
                                      Height = 1, 
                                      Fill = new SolidColorBrush( Colors.Red ), 
                                      Opacity = .1
                                    };

    RubberBandBox.SetValue( Canvas.LeftProperty, OriginatingPostionOnCanvas.X);
    RubberBandBox.SetValue( Canvas.TopProperty,  OriginatingPostionOnCanvas.Y );

    cMain.Children.Add( RubberBandBox );
}

Our goals here are simple:

  1. Get and store the location where the user clicked in relation to the canvas.
  2. Create  and store the rectangle in red and with an opacity which does allows the user to see what is being selected.
  3. Setting the initial location of the rectangle and adding it to the children of the canvas.

Event Mouse Move

The user is moving and we must adjust the rectangle as appropriate for the target direction. Note we also have to handle when the user moves to the upper left instead of the lower right…. So when that happens we will change the cursor to a Stylus (the dot) for visual indication that we are getting a reverse band situation.

private void cMain_MouseMove(object sender, MouseEventArgs e)
{
    if (RubberBandBox == null)
        return;

    Point pointMovedTo = e.GetPosition( cMain );

    double xDelta = pointMovedTo.X - OriginatingPostionOnCanvas.X;
    double yDelta = pointMovedTo.Y - OriginatingPostionOnCanvas.Y;

    LayoutRoot.Cursor = ((xDelta > 0) && (yDelta > 0)) ? Cursors.Hand : Cursors.Stylus;

    if (LayoutRoot.Cursor == Cursors.Hand)
    {
        RubberBandBox.Height = yDelta;
        RubberBandBox.Width  = xDelta;
    }
    else if (LayoutRoot.Cursor == Cursors.Stylus)
    {
        RubberBandBox.Height = Math.Abs( yDelta );
        RubberBandBox.Width = Math.Abs( xDelta );

        if (xDelta < 0)
            RubberBandBox.SetValue( Canvas.LeftProperty, pointMovedTo.X );

        if (yDelta < 0)
            RubberBandBox.SetValue( Canvas.TopProperty, pointMovedTo.Y );
    }

    XValue = (int) (e.GetPosition( cMain ).X - OriginatingPostionOnCanvas.X);
}
Explanation
Line 3 The mouse can move through the canvas during times we are not processing. We need to check that and only process when we have an actual rectangle on the canvas.
Line 6 Extract the current location in relation to the canvas.
Line 8-9 Get the change differences for x and y as named deltas.
Line 11 If the deltas retrieved are in the positive we have a drag to the lower right and that is designated by or specifying the cursor to a hand. If not, the deltas indicate that movement is upwards and to the left; regardless change the  cursor to the stylus.
Line 13 If we are in the hand state, we want to grow (or decrease) the rectangle in that direction towards the lower right.
Line 18 If we are in the stylus state, there is a negative growth either in the x or y axis. Handle the negatives while changing the height and width. Depending on which delta is negative, handle the new location position of the upper left hand position of our bounding rectangle which will follow the mouse.
Line 30 Inform the user of the current X axis location of the mouse whether positive or negative.

Event Mouse Left Button Up

This is our final event we have to handle. We do a safety check on whether we are actually in operations, and if we are then we simply return the cursor to its original state and remove the rectangle from the canvas’ children.

private void cMain_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
{
    if (RubberBandBox == null)
        return;

    // Return to the previous state; whatever it is, the OS handles it.
    LayoutRoot.Cursor = null; 

    cMain.Children.Remove( RubberBandBox );

    // Show that we are not processing by making this null.
    RubberBandBox = null; 
}
Share

Tags: , , ,

Visual Studio: Downloaded Assembly Gives "ValidateXaml" task failed unexpectedly Error or FileLoadException

This is a How To Fix when you have downloaded a foreign (to your computer) assembly which can occur when dealing with Silverlight assemblies but it applies to all assemblies downloaded. Here is more of the errors:

error MSB4018: The "ValidateXaml" task failed unexpectedly.

error MSB4018: System.IO.FileLoadException: Could not load file or assembly ‘… \ImageSequence.dll’ or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)

System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

The situation is that the OS has identified that the assembly was not made on the computer and has been blocked. This is usually the case with downloaded assemblies and is a security feature.

Steps To Resolve

  1. In Visual Studio in the Solution Explorer Window right click on the project which contains the dll and select Open Folder in Windows Explorer.
  2. In Windows Explorer find the dll in question and right click and select Properties.
  3. Select Unblock and select OK. (As shown below)

    BlockedFile

  4. Rebuild.

Once you see the properties and this text its more self explanatory than the Visual Studio error.

This file came from another computer and might be blocked to help protect this computer.

Why?

Remember that .Net is an Xcopy install. Meaning that any .Net application can be installed by simply copying over the assemblies. The OS recognizes the assemblies and categorizes them for running. When one copies code over and tries to manipulate it in Visual Studio the OS blocks for safety reasons and it subsequently fails during a Visual Studio build.

Share

Tags: , ,

C#: How to Detect if a Workstation has been Locked and Unlocked

Here is a quick little console program which demonstrates how to detect if a computer has been either locked or unlocked using C#.  We simply subscribe to the SessionSwitchEventHandler Delegate for the lock or unlock reasons.

// using Microsoft.Win32;
public class CheckForWorkstationLocking : IDisposable
{
    private SessionSwitchEventHandler sseh;
    void SysEventsCheck( object sender, SessionSwitchEventArgs e )
    {
        switch ( e.Reason )
        {
            case SessionSwitchReason.SessionLock: Console.WriteLine( "Lock Encountered" ); break;
            case SessionSwitchReason.SessionUnlock: Console.WriteLine( "UnLock Encountered" ); break;
        }
    }

    public void Run()
    {
        sseh = new SessionSwitchEventHandler( SysEventsCheck );
        SystemEvents.SessionSwitch += sseh;
    }


    #region IDisposable Members

    public void Dispose()
    {
        SystemEvents.SessionSwitch -= sseh;
    }

    #endregion
}

Here is a the code in a console application code to run it:

CheckForWorkstationLocking workLock = new CheckForWorkstationLocking();

workLock.Run();

Console.WriteLine("Press ESC to exit...");
while ( true )
{
    ConsoleKeyInfo key = Console.ReadKey( true );
    if ( key.Key == ConsoleKey.Escape )
        break;
};
Share

Tags:

C# Tribal Knowledge: Use of the Conditional Attribute for Conditional Compilation For Object and and Argument Validation during Development

stockxpertcom_id14589271_jpg_013ced4118ce4854e1935aeaa12684ecThis is another one of of my topics which I deem to be Tribal Knowledge type information. For me it seems that such information seems be known by only the privileged few. In this article I present for your reading perusal details on how to handle different state errors found in classes and arguments during debug/development activities. The premise is that such checks for object or argument correctness is only needed for development and not for production level code. By using the Conditional attribute in ones C# code such checks can be utilized for object and state correctness but not be a burden in a production program or web site.

Development State Errors Checking

For example, and yes its a basic example,  say one is writing a database layer and the requirement is that the connection string be be properly filled with with a database name a user name and a password. You happen to know that this code will be reused by others on the development staff and they will most likely fail to provide such values the first time they hook up the code. So you don’t have to go to their desks to hand hold and debug the error, wouldn’t it be nice if the object checked its own state of correctness?

Once working the checks will really become superfluous and will be removed. This scenario speaks to the fact that the user has two options, or two roads to failure, of loading the values. Say it can be done either during construction or after via the exposed properties. Just ripe for someone to forget to do one or the other.

Code Speaks Conditionally

For the code we will create a connection object which checks for the validity, to the best of its ability, of those values before their use, and if a problem exists throw an application exception during development time only.

Here is our code and the highlight lines are related to the state checking:

using System.Diagnostics;

public class ConnectionManager
{
    public string DatabaseName { get; set; }
    public string UserName     { get; set; }
    public string Password     { get; set; }

    public ConnectionManager() { }

    public ConnectionManager( string databaseName, string userName, string password )
    {
        DatabaseName = databaseName; UserName = userName; Password = password;
    }

    public string GenerateConnectionString()
    {
        // This is only called during debug builds and *not compiled*
        ValidateState(); // during Release builds.

        return string.Format( "{0};User={1};Password={2}", DatabaseName, UserName, Password );
    }

    [Conditional( "Debug" )]
    private void ValidateState()
    {
        if ( string.IsNullOrEmpty( DatabaseName ) )
            throw new ApplicationException( "Development Error: DatabaseName Empty" );

        if ( string.IsNullOrEmpty( UserName ) )
            throw new ApplicationException( "Development Error: UserName Empty" );

        if ( string.IsNullOrEmpty( Password ) )
            throw new ApplicationException( "Development Error: Password Empty" );

    }

}

So if this class is instantiated and the proper variables are not setup an application exception is thrown during debug mode only when a call to generate a connection string occurs. The magic is done by the highlighted lines but the second one with Conditional attribute tells the compiler to only use this in debug builds

Summary

Now this example is a bit contrived, but the idea is that if one has unique business state requirements which may need to be met before an object’s operation can be used, this methodology can be used to catch all actions, but not hamper runtime operations. It obviously shouldn’t be used to catch unique runtime scenarios such as user validation, those should be handled directly and possibly not by generating an exception.

Share

Tags: , ,

C#: Connect To Oracle Database With No Oracle Client Install Needed (Winform DataGridView Loading Example)

Oracle_smallUpdate 1/14/2014 : Updated Oracle Instant Client Link

This article demonstrates in a step by step fashion the easiest, and frankly fastest way to connect to an Oracle database using C#. The goal is to not have to install the huge Oracle Client either on the development machine nor the target machine the code will run on. This example creates a winform and inserts the content into a DataGridView for quick viewing. The code below is base on .Net 3.5.

Steps

  1. Oracle has an Oracle Database Instant Client (download link)which is a set of Dlls which can be XCopy installed onto the development and target PC to allow Oracle database access without installing the full Oracle client. In future steps we will include those target Dlls to be copied to the target output folder with the executable. Download the appropriate package and add Dlls to a folder of your choice on the PC.
  2. In Visual Studio create a Winform Project. From the Solution Explorer and within the project create a subfolder named Oracle Dlls. Update: This step should not be done, for the dlls will end up being copied into a subfolder of the same name and when running the client an error may come up stating “System.Data.OracleClient requires Oracle client software
    version 8.1.7 or greater”.
  3. Add the reference to the project of System.Data.OracleClient to the project..
  4. In Studio again select the folder created in step 2 (highlight the project root) and from the right click menu select Add->Existing Item, and insert all the top level Oracle Dlls from step one into the directory into the folder project. Note the below picture shows into a folder, they do not go into a folder but at the root of the project.
    OracleFolder2
  5. Highlight all the inserted DLLs and select Properties to bring up the properties window. Change the Build Action to be Content and the Copy To Output Directory to be Copy If Newer. This allows the dlls to reside with the created executable program. By doing this it allows the program to run on another computer, as well as this one, that does not have the Oracle Client installed because all the Oracle specific dlls reside with the output executable.
  6. On the design view of the form add a button, label, binding source and a DataGridView. The names used for each in the example (Label as lbState, Binding Source as bsOracle and DataGridView as gvOracle).
  7. Create in the forms code a method to handle the connection string and add the target Oracle db/instance items (Note: Replace { xxx } including the curly braces the specifics to your db) :
    private string GenerateConnectionString()
    {
       return "Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = ( PROTOCOL = TCP )( HOST = {Insert Host Here} )( PORT = {Insert Port Here} ) ) )( CONNECT_DATA = ( SERVER = DEDICATED )( SERVICE_NAME = {Service Name Here } ) ) ); User Id= {DB ID Here}; Password = {Password Here};";
    }
  8. In the button’s onclick event wire up the controls and access the Oracle database as such:
    try
    {
        using ( OracleConnection connection = new OracleConnection( GenerateConnectionString() ) )
        {
            connection.Open();
            lblState.Text = connection.State.ToString();
    
            OracleCommand oc = connection.CreateCommand();
            oc.CommandText = "SELECT * FROM {Your Table Here}";
    
            OracleDataReader reader = oc.ExecuteReader();
    
            bsOracle.DataSource = reader;
            gvOracle.DataSource = bsOracle;
    
            gvOracle.BorderStyle = BorderStyle.Fixed3D;
            gvOracle.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
    
        }
    }
    catch ( Exception ex )
    {
    //  MessageBox.Show( "Exception: " + ex.Message );
        lblState.Text = ex.Message;
    }
  9. Run and compile the program and if all goes well it should attach…but there are other possible failure points see the next section as to a couple of them.

Note for a more involved explanation of this process check out the article Instant Oracle Using C# which has a console example and does not provide the advice of using the build options in Studio for the Oracle Dlls. That will be our little secret. HTH

Possible Errors Encountered

System.Data.OracleClient requires Oracle client software version 8.1.7 or greater

If this is encountered it could be a permission problem accessing the location where the oracle dlls are…but most likely the dlls are not in the same directory as the executable or found within the environment path of the system.

ORA-12541: TNS:no listener

 

This one could mean that one of the connection settings is incorrect and the database could not be connected to and this generic error comes back. Try tweaking the settings, port, instance

Share

Tags: , ,

C#: Launch Hidden Commandline Process and Retrieve its Output

Sometimes there may be a need to launch a command line operation which calls either an executable or a windows command and make it hidden. Within that operation data will be returned and the main code can process it. Here is a quick example to do that where a call to IPConfig is made. By simply setting the window style to hidden one can execute something without a window flashing at the user.

ProcessStartInfo psInfo = new System.Diagnostics.ProcessStartInfo(@"ipconfig");

psInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
psInfo.RedirectStandardOutput = true;
psInfo.UseShellExecute        = false;

Process GetIPInfo;
GetIPInfo = Process.Start( psInfo );

// We want to get the output from standard output
System.IO.StreamReader myOutput = GetIPInfo.StandardOutput;
GetIPInfo.WaitForExit( 3000 );

if ( GetIPInfo.HasExited )
    Console.WriteLine(myOutput.ReadToEnd());

Note This requires System.Diagnostics namespace to be included.

Share

Tags: ,

Tribal Knowledge: C# XDocument Copy Xml But Remove the Pesky DocType

stockxpertcom_id7474751_jpg_882845b5f523a87946c1e89ba7bb9621 In another of my series of Tribal Knowledge articles, this one discusses the basics of loading an XDocument and creating a different document from that original.

There may be a need for one to remove the document type from the original XDocument in C#, or do a basic copy and this is presented here.

How-To

Here is the Xml in a classic before:

<?xml version='1.0' encoding='utf-8'?>
<!-- Generator: AVG Magician 1.0.0, AVG Exports Plug-In . AVG Version: 2.00 Build 8675309)  -->
<!DOCTYPE svg PUBLIC '-//W3C//DTD AVG 1.1//EN' 'http://www.w3.org/Graphics/AVG/1.1/DTD/avg11.dtd'[]>
<avg version='1.1' id='Layer_1' x='0px' y='0px' xml:space='preserve'>
    <rect x='100.143' y='103.714' fill='none' width='87.857' height='12.143' />
</avg>

and this is what we want to achieve:

<?xml version='1.0' encoding='utf-8'?>
<avg version="1.1" id="Layer_1" x="0px" y="0px" xml:space="preserve">
    <rect x="100.143" y="103.714" fill="none" width="87.857" height="12.143" />
</avg>

Since we only care about the AVG node, its the main root, we will simply get that node and append it to our new clone. Here is the full code:

string xml = @"<?xml version='1.0' encoding='utf-8'?>
<!-- Generator: AVG Magician 1.0.0, AVG Export Plug-In . AVG Version: 2.00 Build 8675309)  -->
<!DOCTYPE svg PUBLIC '-//W3C//DTD AVG 1.1//EN' 'http://www.w3.org/Graphics/AVG/1.1/DTD/avg11.dtd'[]>
<avg version='1.1' id='Layer_1' x='0px' y='0px' xml:space='preserve'>
    <rect x='100.143' y='103.714' fill='none' width='87.857' height='12.143' />
</avg>";

XDocument loaded = XDocument.Parse( xml, LoadOptions.SetLineInfo );

XDocument clone = new XDocument( new XDeclaration( "1.0", "utf-8", "yes"),
    loaded.LastNode
    );

Console.WriteLine( clone );

The above achieves the after Xml which we seek, no DocType, we didn’t add it and no first node which is the comment line. I hope this little example helps.

Share

Tags: ,