.NET Binary Numbers

by jason25. July 2006 15:06

The following code snipit will get you all of the binary numbers from zero to fifteen:

string message = string.Empty;
for (int i = 0; i <= 15; i++)
{
message += Convert.ToString(i, 2) + "\r\n";
}
MessageBox.Show(message);

Tags:

Development

.NET Code To Set OpenFileDialog Initial Folder With a String

by jason18. July 2006 12:37

This code uses a string to set the initial folder of an OpenFileDialog.

class Test
{
const string MyComputer = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
const string MyDocuments  = "::{450D8FBA-AD25-11D0-98A8-0800361B1103}";
const string MyNetworkPlaces = "::{208D2C60-3AEA-1069-A2D7-08002B30309D}";
const string Printers = "::{2227A280-3AEA-1069-A2DE-08002B30309D}";
const string RecycleBin = "::{645FF040-5081-101B-9F08-00AA002F954E}";
const string Tasks = "::{D6277990-4C6A-11CF-8D87-00AA0060F5BF}";
[STAThread]
static void Main(string[] args)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = MyComputer;
ofd.ShowDialog();
}
}

Tags:

Development

.NET Script to Find Work Week Start and End

by jason13. July 2006 00:50

If you need to find the Monday of a given week or a Friday of a given week, this is the solution for you:

private DateTime WorkWeekStart(DateTime date)
{
DateTime result = date.AddDays(-((int)date.DayOfWeek)).AddDays(1); //Sunday + 1 = Monday
return result;
}
private DateTime WorkWeekStop(DateTime date)
{
DateTime result = date.AddDays(6 - ((int)date.DayOfWeek)).AddDays(-1); //Saturday - 1 = Friday
return result;
}

Tags: , ,

Development

SQL Script to Find Work Week Start and End

by jason13. July 2006 00:23

If you are looking for the Monday that starts a work week and/or the Friday that ends the work week, this is how you do it in SQL:

DECLARE @Today AS DATETIME
SET @Today = GETDATE()
SELECT DATEADD(wk, DATEDIFF(wk, 0, @Today), 0) AS Monday, DATEADD(wk, DATEDIFF(wk, 4, @Today), 4) AS Friday

Tags: , , ,

SQL

SQL Script to Find Last Day of the Month

by jason10. July 2006 23:42

This Microsoft SQL script figures out what the last day of the month is (28, 30, or 31) so that you don't have to recite the "30 days has September, April, May, and November..." poem or do the "knuckle trick."

DECLARE @Date DATETIME
SET @Date = '1/1/2006'
SELECT DAY(DATEADD(d, -DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date))) AS LastDayOfMonth

Tags: , ,

SQL

Microsoft SQL Reporting Services URL Query Parameters and Commands

by jason9. July 2006 22:02

There are several parameters that can be passed in to the SRS Report viewer through query string parameters. Some of them are listed below:

Change the way it is rendered:
rs:Command=Render& (4 types of re:Commands)

Pass in parameter values:
PARAMNAME1:isnull=true&PARAMNAME2=PARAMVALUE2&

Control the type of output:
rs:Format=PDF

Control what toolbar(s) show in the viewer:
rc:Toolbar=False
rc:Parameters=False

 

Tags: , ,

SQL | SSRS

.NET Class to Export Query Results to Microsoft Excel

by jason9. July 2006 20:57

This class uses an ODBC connection to create an Microsoft Excel Workbook from the results of a Microsoft SQL query.

/// 
/// Export data to an excel workbook
/// 
/// 
/// The example below creates an excel workbook with a single worksheet containing information from the Northwind sample database.
/// 
/// string file = "C:\\workbook.xls";
/// string sql = "SELECT * FROM Customers";
/// string dbConn = "server=(local);database=Northwind;uid=sa;password=;";
/// 
/// Excel ex = new Excel(file, sql, dbConn);
/// ex.WorksheetName = "Customers";
/// ex.Export();
/// 
/// 
public class Excel
{
private string _WorkbookPath, _ExcelConnString, _Worksheet, _SqlQuery, _SqlConnection;
private SortedList _types;
/// 
/// The name of the worksheet to export data to within the Excel workbook.
/// 
public string WorksheetName
{
get
{
if (_Worksheet == null) _Worksheet = "Export";
return _Worksheet;
}
set { _Worksheet = value; }
}
/// 
/// Create a new instance of the Excel class
/// 
/// The full-physical path (including the file name) of the excel workbook to export to
/// The command text / query that retrieves data from the sql server
/// The connection string to the sql database used to run the query
public Excel(string workbookPath, string query, string sqlConnection)
{
this._WorkbookPath = workbookPath;
this._SqlQuery = query;
this._SqlConnection = sqlConnection;
if (File.Exists(workbookPath))
{
_ExcelConnString = "Driver={Microsoft Excel Driver (*.xls)};READONLY=FALSE;DBQ=" + workbookPath;
}
else
{
_ExcelConnString = "Driver={Microsoft Excel Driver (*.xls)};READONLY=FALSE;CREATE_DB=\"" + workbookPath + "\";DBQ=" + workbookPath;
}
this._types = new SortedList(128);
this._types.Add("System.Boolean", "TEXT");
this._types.Add("System.DateTime", "DATE");
this._types.Add("System.Decimal", "NUMBER");
this._types.Add("System.Double", "NUMBER");
this._types.Add("System.Guid", "TEXT");
this._types.Add("System.Int64", "NUMBER");
this._types.Add("System.Int32", "NUMBER");
this._types.Add("System.Int16", "NUMBER");
this._types.Add("System.String", "TEXT");
}
/// 
/// Export the data defined in the constructor to the excel workbook specified
/// 
/// True if export was succesfull; False otherwise
public bool Export()
{
bool returnVal = true, WorkbookExists = false;
OdbcConnection conn = new OdbcConnection(this._ExcelConnString);
SqlConnection SqlConn = new SqlConnection(this._SqlConnection);
string sql = "", colList = "";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(this._SqlQuery, SqlConn);
SqlConn.Open();
da.Fill(ds);
SqlConn.Close();
da.Dispose();
conn.Open();
//check to see if the worksheet already exists
sql = "SELECT * FROM [" + this.WorksheetName + "$]";
OdbcCommand comm = new OdbcCommand(sql, conn);
try
{
//this will error out if the table doesn't exist
OdbcDataReader dr = comm.ExecuteReader();
dr.Close();
WorkbookExists = true;
}
catch
{
WorkbookExists = false;
}
if (! WorkbookExists)
{
//the worksheet doesn't exist, so create it
sql = "CREATE TABLE " + this.WorksheetName + " (";
colList = "(";
//get a list of columns to create from the sql query
foreach (DataColumn col in ds.Tables[0].Columns)
{
string t = this._types[col.DataType.ToString()].ToString();
sql += "[" + col.ColumnName + "] " + ((t == null || t == string.Empty) ? "TEXT" : t) + ", ";
colList += col.ColumnName + ", ";
}
//remove the last comma from the column lists and close the parenthesis
sql = sql.Remove(sql.LastIndexOf(", "), 2) + ")";
colList = colList.Remove(colList.LastIndexOf(", "), 2) + ")";
//execute the create table command
comm.CommandText = sql;
comm.ExecuteNonQuery();
//iterate through the sql query and insert each row into the excel worksheet
foreach (DataRow row in ds.Tables[0].Rows)
{
sql = "INSERT INTO " + this.WorksheetName + " " + colList + " VALUES (";
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
//iterate through each column in the row and get the value
sql += "'" + row[i].ToString().Replace("'", "''") + "', ";
}
sql = sql.Remove(sql.LastIndexOf(", "), 2) + ")";
//execute the insert command
comm.CommandText = sql;
comm.ExecuteNonQuery();
}
}
else
{
//the worksheet does exist, so change the worksheet name to be unique
this.WorksheetName = this.WorksheetName + "_1";
returnVal = Export();
//throw new Exception("The worksheet name specified already exists in the specified workbook.");
}
ds.Dispose();
comm.Connection.Close();
comm.Dispose();
return returnVal;
}
}

Tags: , ,

Development

.NET Class to Read XML Config File

by jason1. July 2006 18:07

There are some instances where you may need your dll to have its own .config file. Of course, the .NET framework only uses a config file for the executing assembly (exe's) and not satalite assmeblies (dll's). Here is a class that can be used to read an XML file that follows the .config file schema:

 /// 
/// Accessor for a configuration file when System.Configuration methods are not supported
/// 
/// 
/// 
/// [Use Example]
/// string file = "C:\\config.xml";
///
/// Configuration config = new Configuration(file);
/// string dbConn = config.AppConfig["dbConn"].ToString()
///
/// SqlConnection conn = new SqlConnection(dbConn);
/// ...
///
/// [Xml Configuration File Format]
/// 
/// 
///  
///   
///   
///  
/// 
/// 
/// 
public class Configuration
{
private SortedList _AppConfig;
private string _FilePath;
/// 
/// The full physical file path to the configuration file
/// 
public string FilePath
{
get { return _FilePath; }
set { _FilePath = value; }
}
/// 
/// The primary key/value collection of the parsed config file
/// 
public SortedList AppConfig
{
get { return _AppConfig; }
set { _AppConfig = value; }
}
/// 
/// Initialize the Configuration class
/// 
public Configuration()
{
this.FilePath = "config.xml";
ParseConfigFile();
}
/// 
/// Initialize the Configuration class
/// 
/// The full physical path to the configuration file
public Configuration(string filePath)
{
this.FilePath = filePath;
ParseConfigFile();
}
/// 
/// Parse the configuration file set in the FilePath property.
/// 
/// This method is called by the initializer, but should be re-called if the FilePath property is reset.
public void ParseConfigFile()
{
if (File.Exists(this.FilePath))
{
XmlDocument xml = new XmlDocument();
xml.Load(this.FilePath);
this.AppConfig = new SortedList(xml.GetElementsByTagName("add").Count);
foreach (XmlNode xnode in xml.GetElementsByTagName("add"))
{
this.AppConfig.Add(xnode.Attributes["key"].Value, xnode.Attributes["value"].Value);
}
}
else
{
throw new FileNotFoundException("The configuration file '" + this.FilePath + "' could not be found.");
}
}
/// 
/// Save the configuration settings back to the file set in the FilePath property.
/// 
public void SaveConfigFile()
{
if (File.Exists(this.FilePath))
{
XmlDocument xml = new XmlDocument();
xml.Load(this.FilePath);
foreach (XmlNode xnode in xml.GetElementsByTagName("add"))
{
xnode.Attributes["value"].Value = this.AppConfig[xnode.Attributes["key"].Value].ToString();
}
xml.Save(this.FilePath);
}
}
}

Tags:

Development

About

Jason Williams is a .NET developer in Lincoln, Nebraska.

The name "Centrolutions" came out of a long search for a domain name. The goal was to create a name that conveyed an ideology of writing software centered (Centr--) on a solution (--olutions) for a particular problem. In other words, it was the only name in a long list that wasn't already registered on the internet.

If you're looking for the products I have for sale, you should go here.