TSQL: Nested Select with multiple results to one (comma separated) string

by Pieter Brinkman 25. August 2009 03:22

For this example I will use the default asp.net Membership tables.

Let say: I need to return all users with their roles (comma separated) in one query. After a long time Googling I found the following solution.

[code:tsql]

select
  UserName,
  (select roles.RoleName + ', '
    FROM aspnet_Roles roles
    join aspnet_UsersInRoles usersInRole on roles.RoleId = usersInRole.RoleId
    WHERE usersInRole.UserId = aspUser.UserId
    for xml path('')) as roles
from
    aspnet_Users aspUser

[/code]

Don't know if this is the best way, but it works.

Tags: , ,

TSQL

TSQL: Use common table expression

by Pieter Brinkman 23. August 2009 03:04

With common table expressions you can save the results to a temporary result set and use this results set for other queries.

[code:tsql]

WITH temporaryNamedResultSet
AS
(
  select UserName from aspnet_Users
)
select * from temporaryNamedResultSet

[/code]

 

Tags: , ,

TSQL

Linq Casting: ToDictionary()

by Pieter Brinkman 23. June 2009 04:03

In this post I will give an example how to cast a GenericList to Dictionary.

This example will use the following Blogger class.

[code:c#]

public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}

[/code]

 

The example will cast a List<Blogger> to a dictionary with key FirstName, Lastname and value the Age of the blogger.

[code:c#]

// DECLARE PERSONLIST

List<Blogger> personList = new List<Blogger>();
personList.Add(new Blogger { FirstName = "Pieter", LastName = "Brinkman", Age = 27, Blog = "http://blog.newguid.net" });
personList.Add(new Blogger { FirstName = "Mark", LastName = "van Aalst", Age = 26, Blog = "http://www.markvanaalst.com/" });
personList.Add(new Blogger { FirstName = "Bas", LastName = "Hammendorp", Age = 32, Blog = "http://www.hammendorp.net/" });


// CREATE NEW DICTIONARY FROM LIST
// with key FirstName + LastName and value Age

Dictionary<string, int> AgeDictionary =
 personList.ToDictionary(x => x.FirstName + " " + x.LastName,
       x => x.Age,
       StringComparer.OrdinalIgnoreCase);


// GENERATE OUTPUT

foreach (KeyValuePair<string, int> item in AgeDictionary)
 Response.Write("key: " + item.Key + " - value: " + item.Value + "<br />");


//// OUTPUT
//key: Pieter Brinkman - value: 27
//key: Mark van Aalst - value: 26
//key: Bas Hammendorp - value: 32

[/code]

 Hope it helps.

Tags: , , ,

Linq

.Net: Example basic consoleapplication with parameters

by Pieter Brinkman 20. February 2009 08:01

This is a basic example of an console-application with parameters used for a scheduled tasks.

The application will be scheduled to run every day with the -n parameter. But the application can also run on a specific date by using the -d parameter.

class Program
{
 //Parameters
 private static DateTime theDate;
 private static RunMode mode = RunMode.NotSpecified;

 static void Main(string[] args)
 {
  if (CollectParameters(args))
  {
   Console.WriteLine("Beginning appliation in mode \"{0}\" with date {1}.", mode, theDate);
   Logger.LogEvent("Starting StatisticConsoleApp", args, (int)Logger.LogType.Message);

  }
 }

 private static bool CollectParameters(string[] args)
 {
  if (args.Length > 0)
  {
   for (int ii = 0; ii < args.Length && mode == RunMode.NotSpecified; ii++)
   {
    //Default commands for support -h and /?
    if (args[ii].ToLower().Trim() == "-h" || args[ii].Trim() == "/?")
    {
     PrintHelpText();
     return (false);
    }
    else
    {
     //Get clear input params
     string inputParam = args[ii].ToLower().Trim();
     inputParam = Regex.Replace(inputParam, "[/-]", "");

     switch (inputParam)
                    {
                        case "n":
                            mode = RunMode.Normal;
                            theDate = DateTime.Now;
                            break;

                        case "d":
                            mode = RunMode.SpecificDate;
                            if ((ii + 1) < args.Length)
                            {
                                theDate = Convert.ToDateTime(args[ii + 1]);
                            }
                            break;
       default:
        if(args[ii].Substring(0,1) == "-")
         Console.WriteLine("Unknown switch {0}. Ignoring this switch.", args[ii]);
        break;
      }
    }
   }

   if (mode != RunMode.NotSpecified)
   {
    return true;
   }
   else
   {
    Console.WriteLine("No valid parameter specified. Aborting processing.....");
    return false;
   }
  }
  else
  {
   PrintHelpText();
   return false;
  }
 }


 private static void PrintHelpText()
 {
  Console.WriteLine("\nUsage: Statisticprocess application");
  Console.WriteLine("");
  Console.WriteLine("  -n");
  Console.WriteLine("    The application will run in normal mode.");
  Console.WriteLine("    The statistics will be processed with the current date.");
  Console.WriteLine("  -d");
  Console.WriteLine("    The application runs in 'specific date' mode.");
  Console.WriteLine("    The statistics will be processed with the input date");
  Console.WriteLine("    The date may be specified in any format as long as it can be ");
  Console.WriteLine("    translated unambiguously into a proper date.");
  Console.WriteLine("");
  Console.WriteLine("");
  Console.WriteLine("    Note: Only one mode can be specified.");
  Console.WriteLine("          If two modes are specified, the second mode is ignored.");
  Console.WriteLine("");
  Console.WriteLine("    Example: In this example application runs in \"specific date\" mode ");
  Console.WriteLine("             for the date \"10-sep-2006\".");
  Console.WriteLine("");
  Console.WriteLine("    TOOLNAME [-d 1-jan-2009]");
  Console.WriteLine("");
 }
}

[/code]



If you copy this class into your program.cs you will get some errors concerning my own loghandler and the missing RunMode enum. To fix this delete the code lines for the logging and add the following enum to your console application.

public enum RunMode : byte
 {
  NotSpecified,
  Normal,
  SpecificDate
 }


This is not the clearest example but if you have any questions don't hesitate to ask.  

Tags: ,

Microsoft

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Me

My name is Pieter Brinkman I am a .NET Software Engineer for Achmea IT in De Meern, The Netherlands. My interests are mainly web applications created with ASP.NET, MSSQL and Silverlight.

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

RecentComments

Comment RSS

Most comments

club penguin cheats club penguin cheats
4 comments
us United States
Web Design Company Web Design Company
2 comments
Web design Web design
2 comments
gb United Kingdom