Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries for the ‘C#’ Category

Call SQLCMD and get the exit code(return code/%ErrorLevel%)

In my last post Call SQLCMD to run SQL script via C#, we know how to call SQLCMD via C#. But in most scenarios, we also need the exit code(%ErrorLevel%) or the sub SQLCMD thread. It is simple, use ‘-b’ in sqlcmd can do this!

-b on error batch abort

Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs. The value that is returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error message has a severity level greater than 10; otherwise, the value returned is 0. If the -V option has been set in addition to -b, sqlcmd will not report an error if the severity level is lower than the values set using -V. Command prompt batch files can test the value of ERRORLEVEL and handle the error appropriately. sqlcmd does not report errors for severity level 10 (informational messages).

If the sqlcmd script contains an incorrect comment, syntax error, or is missing a scripting variable, ERRORLEVEL returned is 1.

So, just add a –b parameter when call the SQLCMD!

Here are more parameters in error reporting,

-V severitylevel

Controls the severity level that is used to set the ERRORLEVEL variable. Error messages that have severity levels less than or equal to this value set ERRORLEVEL. Values that are less than 0 are reported as 0. Batch and CMD files can be used to test the value of the ERRORLEVEL variable.

-m error_level

Controls which error messages are sent to stdout. Messages that have a severity level less than or equal to this level are sent. When this value is set to -1, all messages including informational messages, are sent. Spaces are not allowed between the -m and -1. For example, -m-1 is valid, and -m -1 is not.

This option also sets the sqlcmd scripting variable SQLCMDERRORLEVEL. This variable has a default of 0.

Call SQLCMD to run SQL script via C#

Usually, we need to call some sql script to update our database in our application(C#), and it is a good way to call SQLCMD to execute the sql scripts. One important reason is that our scripts always contains the GO statement which is is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. Since the SQLCMD and SQL Server Management Studio will do the same thing, the scripts edited by SQL Server Management Studio will be 100% supported by SQLCMD.

Here is a block of code to call SQLCMD:

 

string tmpFile = Path.GetTempFileName();

string argument = string.Format(@" -S {0} -d {1} -i ""{2}"" -o ""{3}""",
    ServerName, DatabaseName, fileName, tmpFile);

// append user/password if not use integrated security
if (!connection.IsIntegratedSecurity)
    argument += string.Format(" -U {0} -P {1}", User, Password);

var process = Process.Start("sqlcmd.exe", argument);
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
while (true)
{
    // wait for the process exits. The WaitForExit() method doesn't work
    if (process.HasExited)
        break;
    Thread.Sleep(500);
}

Optional Parameters in C# 4.0

Some members of the C# community were discussing optional parameters and the implications for future versions when optional parameter values change.  In short, you need to realize that changing the value of optional parameters in a public API is a change that is observable at client code. The ramifications vary greatly, from “no big” to “stop the world”. I’ll give a brief explanation of how the feature works, and what you need to watch for and how to separate reasonable caution from irrational fear from using a feature.

While most modern programming languages provide some way of declaring optional function parameters, C# doesn’t provide a way of directly doing so, despite the fact that VB.NET and .NET’s attribute system both support this functionality. This is a subject of some debate currently in the C# community. The C# development team’s position seems to boil down to the following: When provided, this feature is usually nothing more than dressing up method overloading with a little syntactic sugar.

When you get right down to it, their position makes some sense. A function with an optional parameter is in reality two different functions: one that assumes some default behavior if the optional parameter is omitted, and another that performs more specific behavior based on the value of the optional parameter if provided. But that doesn’t change the fact that using overloaded methods to provide optional parameter support feels a little clunky. It works, but you always wind up writing more code, and you pollute your object interface with the extra method signatures required to support all of your optional parameters. Let’s look at some alternatives.

Displaying Markers on the Chart via Microsoft Chart Controls

01 private void BindData() {
02
03 var exams = new List<Exam>()
04 {
05 new Exam() { Name = "Exam 1", Point = 10 },
06 new Exam() { Name = "Exam 2", Point = 12 },
07 new Exam() { Name = "Exam 3", Point = 15 },
08 new Exam() { Name = "Exam 4", Point = 2 }
09 };
10
11 var series = ExamsChart.Series["ExamSeries"];
12
13 foreach (var exam in exams) {
14
15 var point = new DataPoint();
16 point.SetValueXY(exam.Name, exam.Point);
17
18 point.Label = exam.Point.ToString();
19 series.Points.Add(point);
20 }
21
22 ExamsChart.DataSource = exams;
23 ExamsChart.DataBind();
24 }
Microsoft Chart

Microsoft Chart

Entity Framework 4

Some of the big improvements in EF4 include:

  • POCO Support: You can now define entities without requiring base classes or data persistence attributes.
  • Lazy Loading Support: You can now load sub-objects of a model on demand instead of loading them up front.
  • N-Tier Support and Self-Tracking Entities: Handle scenarios where entities flow across tiers or stateless web calls.
  • Better SQL Generation and SPROC support: EF4 executes better SQL, and includes better integration with SPROCs
  • Automatic Pluralization Support: EF4 includes automatic pluralization support of tables (e.g. Categories->Category).
  • Improved Testability: EF4’s object context can now be more easily faked using interfaces.
  • Improved LINQ Operator Support: EF4 now offers full support for LINQ operators.

EF4 enables you to:

  • Develop without ever having to open a designer or define an XML mapping file
  • Define your model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping

C# Code Function: Converting List of strings to string

=== Program that converts List (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> dogs = new List<string>(); // Create new list of strings
        dogs.Add("Aigi");                       // Add string 1
        dogs.Add("Spitz");                      // 2
        dogs.Add("Mastiff");                    // 3
        dogs.Add("Finnish Spitz");              // 4
        dogs.Add("Briard");                     // 5

        string dogCsv = string.Join(",", dogs.ToArray());
        Console.WriteLine(dogCsv);
    }
}

=== Output of the program ===

Aigi,Spitz,Mastiff,Finnish Spitz,Briard