Rob Kraft's Software Development Blog

Software Development Insights

Archive for the ‘Visual Studio 2008’ Category

The Correct Way to Re-Throw An Exception – .Net Tip

Posted by robkraft on March 6, 2013

When catching and re-throwing an exception, you should include the original exception as a 2nd parameter.  Including the original exception may provide a deeper stack trace that will assist you with solving the exception.

This syntax may not include the full stack trace.

This syntax may not include the full stack trace.

In the code above, if an error occurs in methodWithoutCatch(), the call stack returned will show “methodWithTryCatch” as the deepest method in the stack.

System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object.
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 34 at WindowsFormsApplication6.Form1.button1_Click
This example will include the full call stack.

This example will include the full call stack.

However, if you include the original exception in the throw as shown in the second throw example, then the call stack returned will show “methodWithoutCatch” as the deepest method in the stack.

System.Exception: Additional Error Info: blah blahObject reference not set to an instance of an object.
---> System.NullReferenceException: Object reference not set to an instance of an object.
at WindowsFormsApplication6.Form1.methodWithoutCatch(String z) in ...\Form1.cs:line 40
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 29
--- End of inner exception stack trace ---
at WindowsFormsApplication6.Form1.methodWithTryCatch(String y) in ...\Form1.cs:line 35
at WindowsFormsApplication6.Form1.button1_Click

Including the original exception as the second parameter of your new exception provides you with a better call stack.  In this example, it allows you to determine that the error occurred in the methodWithoutCatch method.  In the first case, you are left wondering if the methodWithTryCatch really caused the error, or if one of the three methods it called (method1, methodWithoutCatch, or method3) caused the error.

Posted in Code Design, Visual Studio 2005, Visual Studio 2008, Visual Studio 2010 | 1 Comment »

Fiddler DOES work on your local/cassini/webdevserver/Visual Studio sites

Posted by robkraft on April 7, 2010

If you want to use Fiddler to monitor against the web traffic on your localhost when running in Visual Studio, change your URL to start with ipv4.fiddler: 

http://ipv4.fiddler:2296/Default.aspx

instead of

http://localhost:2296/Default.aspx

Posted in Visual Studio 2005, Visual Studio 2008 | 2 Comments »

Run the same C# program in a Console or a Windows Form

Posted by robkraft on March 9, 2010

I’ve seen a few complicated solutions for writing a C# application to run as both a console application and a windows application, but I’d like to share a simpler example.

  1. Create a new project by selecting a C# “Windows Forms Application”.  This will add references to the project and some starter code necessary for displaying the windows part of your program.
  2. Choose the “Application” tab from your project properties, and set the “Output type” equal to “Console Application”.  This will cause your program to start out running as a console app.
  3. The program I am creating here is a shell to allow you to call the same logic (perhaps generate the SQL Script for a table) and send the script out to the console or have it display in a text box on a form.
  4. Change the Main method in Program.cs to accept the command line arguments as input:
  5.  

[STAThread]
static void Main(string[] commandLineArgs
{
    if (commandLineArgs.Length > 0) //then we have command line args
    {
        Console1.ProcessCommandLineArgs(commandLineArgs);
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

5. For this example, I created 2 classes in addition to Form1 which was created for me.  I created a class called MyScripter.cs, which has all the code to “do the work”.  And I created Console1.cs.  I will have code in both Console1.cs and in Form1.cs that can call MyScripter.cs.  Here is the simple console class:

public class Console1
{
    public static void ProcessCommandLineArgs(string[] commandLineArgs)
    {
        MyScripter scripter = new MyScripter();
        foreach (string tablename in commandLineArgs)
        {
            string output = scripter.ScriptMyTable(tablename);
            Console.WriteLine(output);
        }
    }
}

6. I added two text boxes and a button to Form1.cs along with this event:

private void buttonScript_Click(object sender, EventArgs e)
{
    MyScripter scripter = new MyScripter();
    textBox2.Text = scripter.ScriptMyTable(textBox1.Text);
}

7. Finally, an example of the shell MyScripter.cs, which is where the real work is done:

public class MyScripter
{
    public string ScriptMyTable(string tablename)
    {
        string scriptIGenerate = "This is the script of my table named: " + tablename;
        return scriptIGenerate;
    }
}

8. You can now run this compiled program from a command prompt. If you pass in a command line argument, the program will use that as input to generate output to the console. If no command line argument is provided, the application will display the form you created.

Posted in Code Design, Visual Studio 2005, Visual Studio 2008 | Tagged: , , | Leave a Comment »

Eliminating some of the foreign language resource files

Posted by robkraft on February 8, 2010

I’m all in favor of the use of resource files for strings and other elements of our programs, but I don’t like seeing all the subfolders for various foreign language resource builds in projects where I will never need them.
Our Silverlight projects were creating 8 foreign language subfolders (de, es, fr, it, ja, ko, zh-Hans, and zh-Hant). Not only does this clutter my hard drive, complicate my version control, and annoy me; but it requires a little longer to compile, and it nearly doubles the size of my nant output log. I know that it doubles the size because when I caused it to stop, the log file size was cut in half.
I managed to stop the creation of all the foreign language resource versions of the files by deleting the foreign language subfolders with those names from C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Libraries\Client.

Posted in Visual Studio 2008 | Tagged: , , | Leave a Comment »

When CopyLocal=True means CopyLocal=False

Posted by robkraft on February 8, 2010

We have learned that CopyLocal = true is misleading. CopyLocal is set to true by default, but that does not always cause the DLL to get included in the .xap. However, if you change it to false, then back to true, it does get included in the .xap. We have experienced this many times in VS2008 with Silverlight 3.

Also, after you do this, you will notice that it does cause a change in the .csproj file. It sets the Private Tag explicitly to true, rather than relying on the msbuild default value of true.
I hope this post helps others resolve this xap file problem more quickly.

Posted in Visual Studio 2008, Visual Studio 2010 | Tagged: , | Leave a Comment »

Great free tool: CodeRushExpress

Posted by robkraft on September 9, 2009

CodeRush now provides a free version of their tool called CodeRush Express. You can download it from this URL:
http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX

They also provide a nice list of features and short tutorials on each.

If you are not familiar with the features that CodeRush or ReSharper provide that can increase developer productivity in Visual Studio .Net, this is a great way to learn.

Posted in Code Design, Free tools, Visual Studio 2008 | 2 Comments »

Getting values back from Oracle Procedures in C# .Net

Posted by robkraft on January 14, 2009

We have an application that uses Oracle Procedures for modifying data.  We decided that we wanted to get the number of records affected from each procedure.  We discovered that you cannot get that information if you are using Oracle Procedures.  Yes, you read that correctly, Oracle Procedures are incapable of returning values to the calling program.  Coming from a SQL Server background this was very surprising to me, but I found this truth in several places, including (http://it.toolbox.com/blogs/oracle-guide/learn-plsql-procedures-and-functions-13030).  Let me be clear though, Oracle Procedures can return values in output parameters, they just don’t provide a “return” value.  They also cannot return result sets.

 

Therefore, with Oracle, you have 3 ways to get the number of records affected.

  1. Use Output parameters on a Procedure,
  2. Use Return parameters on a Function,
  3. Wrap a Procedure in a Package and return the value from the Package.

 

For our development, we are using C# and we are using the Oracle provided .Net DLLs, not the Microsoft version of the Oracle .Net DLLs.

 

We decided to use Procedures to return the values, although we could have just as easily used functions.  I include here examples of each approach.

 

Oracle Functions

1) Functions CAN return values.  Here is an example of one of our functions.

CREATE OR REPLACE FUNCTION “MYSCHEMA”.”FUNC_CUSTOMERUPDATE”

(

  P_VER_TARGET IN CUSTOMER.VER_TARGET%TYPE

)

RETURN NUMBER

AS

BEGIN

  UPDATE CUSTOMER

  SET VER_TARGET = P_VER_TARGET

  WHERE VER_ID < 4;

RETURN SQL%ROWCOUNT ;

END FUNC_CUSTOMERUPDATE;

 

CREATE OR REPLACE PUBLIC SYNONYM “FUNC_CUSTOMERUPDATE”

FOR “MYSCHEMA”.”FUNC_CUSTOMERUPDATE”;

GRANT EXECUTE ON FUNC_CUSTOMERUPDATE TO ACCTGROUP;

 

2) In the function, we tell it to return the value in the SQL%ROWCOUNT reserved function.

 

3) To test our function in Oracle we use SQL Developer. Here is the query to test our function:

 

exec dbms_output.enable(1000);

declare var1 NUMBER;

BEGIN

  var1 := FUNC_CUSTOMERUPDATE(‘abcde’);

dbms_output.put_line( var1);

END;

 

4) Now that we know we get the output we expect in Oracle, we can try to make it work in our C# program.

 

     private Oracle.DataAccess.Client.OracleConnection _cnOra;

     private Oracle.DataAccess.Client.OracleCommand _cmOra;

     //Connection open was called…

     _cmOra = _cnOra.CreateCommand();

     _cmOra.CommandType = System.Data.CommandType.StoredProcedure;

     _cmOra.CommandText = “FUNC_CUSTOMERUPDATE”;

     _cmOra.BindByName = true; //I don’t recall why we do this – including it just in case it is relevant    

     _cmOra.Parameters.Add(“VER_TARGET”), “abcde”);

     Oracle.DataAccess.Client.OracleParameter oraParm = new Oracle.DataAccess.Client.OracleParameter();

     oraParm.OracleDbType = Oracle.DataAccess.Client.OracleDbType.Int32;

     oraParm.Direction = System.Data.ParameterDirection.ReturnValue;

     _cmOra.Parameters.Add(“RETVAL“);

     _cmOra.ExecuteNonQuery();

     Int32 recordsAffected = Convert.ToInt32(Parameters(“RETVAL”));

 

 

Procedures

1) After finally getting all that working; we then easily made it work with procedures by using an OUT parameter on the procedure:

CREATE OR REPLACE PROCEDURE “MYSCHEMA”.”PROC_CUSTOMERUPDATE”

(

  P_VER_TARGET IN CUSTOMER.VER_TARGET%TYPE,

  P_RETVAL OUT NUMBER

)

IS

BEGIN

  UPDATE CUSTOMER

  SET VER_TARGET = P_VER_TARGET

  WHERE VER_ID < 4;

P_RETVAL:= SQL%ROWCOUNT ;

END FUNC_CUSTOMERUPDATE;

 

CREATE OR REPLACE PUBLIC SYNONYM “FUNC_CUSTOMERUPDATE”

FOR “MYSCHEMA”.”FUNC_CUSTOMERUPDATE”;

GRANT EXECUTE ON FUNC_CUSTOMERUPDATE TO ACCTGROUP;

 

     private Oracle.DataAccess.Client.OracleConnection _cnOra;

     private Oracle.DataAccess.Client.OracleCommand _cmOra;

     //Connection open was called…

     _cmOra = _cnOra.CreateCommand();

     _cmOra.CommandType = System.Data.CommandType.StoredProcedure;

     _cmOra.CommandText = “FUNC_CUSTOMERUPDATE”;

     _cmOra.BindByName = true; //I don’t recall why we do this – including it just in case it is relevant    

     _cmOra.Parameters.Add(“VER_TARGET”), “abcde”);

     Oracle.DataAccess.Client.OracleParameter oraParm = new Oracle.DataAccess.Client.OracleParameter();

     oraParm.OracleDbType = Oracle.DataAccess.Client.OracleDbType.Int32;

     oraParm.Direction = System.Data.ParameterDirection.Output;

     oraParm.ParameterName = “RETVAL“;

     _cmOra.Parameters.Add(oraParm);

     _cmOra.ExecuteNonQuery();

     Int32 recordsAffected = Convert.ToInt32(Parameters(“RETVAL”));

Posted in Visual Studio 2008 | Tagged: , , | 3 Comments »

How to create a Password column using the DataGridView

Posted by robkraft on December 19, 2008

If you want to hide the password value in a Visual Studio DataGridView control, you can use the code below.  If a user clicks into the cell to edit the value, then the current value becomes visible.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (
dataGridView1.Columns[e.ColumnIndex].Name == “passwordDataGridViewTextBoxColumn” && e.Value != null)
    {
       
dataGridView1.Rows[e.RowIndex].Tag = e.Value;
        e.Value = new String(
‘*’, e.Value.ToString().Length);
    }
}

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (
dataGridView1.CurrentRow.Tag != null)
        e.Control.Text =
dataGridView1.CurrentRow.Tag.ToString();
}

I found the example above on this web page, in a non-english language:

Posted in Visual Studio 2005, Visual Studio 2008 | Tagged: , | 3 Comments »

A bug in retrieving css from cache in IE7?

Posted by robkraft on September 14, 2008

I have a web site with .css files that I tried to cache for 30 days.  However, tools like Fiddler and HTTPWatch indicated that my css files were not being retrieved from the cache in IE7, but they were in Firefox.  I finally managed to get the .css files to be pulled from the IE7 browser cache by setting the Last Modified property of the .css header files.

context.Response.Cache.SetLastModified(DateTime.Now); //9/10/2008 – I added this line to SetLastModified to fix what looks like a bug in IE7. IE7 appears to request and receive css files that are cached (200) – even though it should pull them from cache. Worse – they then fail to render. By setting the LastModified (which previously had no value), the CSS now seems to load from cache, and the screen uses them to render, and it does not call back to the server.

Posted in Visual Studio 2008 | Tagged: , , | Leave a Comment »

Inheritance or Interfaces or Just One Big Class?

Posted by robkraft on May 27, 2008

I often struggle with choosing between interfaces, inheritance, or just a big class with switch statements. Here are some scenarios along with my suggested design. Real world scenarios vary, and there are good arguments for not using my suggested approach in similar situations.

1) Create a class or classes to contain products for my Tier 1 and Tier 2 customers”. “All of my Tier 1 customers can purchase all products, but my Tier 2 customers can only purchase products priced less than $10,000.

  • Incorrect – Interface. An interface should not be used to provide similarity across classes when the classes also can share code.
  • Incorrect – Inheritance. It is difficult to determine which class would inherit from the other; though both classes could inherit from the same base class. The only difference may be the source of the data retrieved. Having separate classes, even inherited, may require the UI to code additional logic to access the two differently named classes.
  • Correct – One big class. The UI would prefer to treat each class using the same code. If I use the same class, then the UI won’t need conditional logic to instantiate and handle the objects of the correct type. At the data retrieval level, you will need to run a different query to get the correct set of products, but that can probably be handled by passing in a paramater on the constructor.

2) Create a class or classes for Products, OnOrderProducts, and ObsoleteProducts.

  • Incorrect – Interface. An interface should not be used to provide similarity across classes when the classes also can share code.
  • Incorrect – One big class. Assuming that the 3 classes share a lot of business rules, yet have a few slightly different business rules and properties, then one big class should not be used because it does not clearly separate the different business logic for each class, and it does not allow the UI to easily work differently with the different rules for each.
  • Correct – Inheritance. You may have all 3 product classes inherit from a single abstract base class, or you may have 2 of the product classes inherit from the 3rd and simply add additional properties and methods. In many cases, it is better to inherit from a base abstract class as that makes it simple to exclude properties and methods from any class, as well as include properties and methods unique to one class. 

3) Add a SaveAsXML method to several classes.

  • Incorrect – Inheritance. Because the code to persist each class may be different, and because most of the other properties and methods in the classes are not the same, we should not use inheritance to add this feature.
  • Incorrect – A separate function that receives the class as input. Generally each class should implement its own behavior. The UI should call a method on the class to save it as XML; the UI should not call a function and pass the class to it because the former technique is a more object-oriented approach.
  • Correct – Use an interface. Create an Interface that includes the SaveAsXML and any other related methods. Have each class that will be able to SaveAsXML implement the interface. They could also possibly share the same bit of code from an existing base class they already share, or each class could call a common SaveAsXML class from within their own code. This approach allows the UI to identify which classes implement the interface, and to safely cast any such class to that interface and perform the SaveAsXML operation on them.

Some guidelines I use to help me choose which approach to use are:

  1. When I am considering multiple classes, and all the classes will have a lot of the same properties and methods, then I should probably use inheritance instead of an interface.
  2. When I am considering multiple classes, and all the classes can use the same code, then I should probably use inheritance instead of an interface.
  3. When I have some functionality that I would like to apply to classes that already have (or will have) different properties and methods, then I should probably use an interface.
  4. When I am considering multiple classes, and all the classes will have the same properties and methods, then I may want to use a single class instead of inheritance.

Posted in Code Design, Visual Studio 2008 | Tagged: , | Leave a Comment »