Monday, October 27, 2008

Formatting Blogger posts with c# code in them

Very cool tool right here: http://www.manoli.net/csharpformat/format.aspx but you have to change the page header to reference a CSS file but I am not sure how to upload the CSS file so I entered it in to the HTML template manually.

Wordpress has a cool plugin that makes this even easier.

How to serialize an object to/from xml

I copied the below almost entirely from this page but didn't want to risk it going away before I had it committed to memory, so read that page not mine! I am not sure why you just wouldn't create a method on the object to do that but all the examples I have seen use a separate void class.
[csharp]


//Serialize:
static public void SerializeToXML(Movie movie)
{
XmlSerializer serializer = new XmlSerializer(typeof(Movie));
TextWriter textWriter = new StreamWriter(@"C:\movie.xml");
serializer.Serialize(textWriter, movie);
textWriter.Close();
}

//Deserialize:
static List<Movie> DeserializeFromXML()
{
XmlSerializer deserializer =
new XmlSerializer(typeof(List<Movie>));
TextReader textReader = new StreamReader(@"C:\movie.xml");
List<Movie> movies;
movies = (List<Movie>)deserializer.Deserialize(textReader);
textReader.Close();

return movies;
}

Wednesday, October 22, 2008

How to create a collection of classes in .net

To create a collection, capable of:

being used in a foreach loop,
being returned from a webmethod

etc, you need to create a class that inherits CollectionBase and iEnumerable.

Both of these classes require you implement several methods, and you also need to create an Enumerator class, see the code below and put your class in instead.

Note the default following: public OrderLine this[int i]{...} is required to automatically return each element of the collection when used as a return value for a webmethod.



using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace OfficeOps.SalesOrdering.SalesOrder
{
public class OrderLines : CollectionBase, IEnumerable
{

public void Add(OrderLine ordLine)
{
List.Add(ordLine);
}
public void Remove(int index)
{
if (index > Count - 1 || index < 0)
{
throw new Exception("Index out of bounds");
}
List.RemoveAt(index);
}

public OrderLine this[int i]
{
get { return (OrderLine)List[i]; }
}
public class OrderLineEnumerator : IEnumerator
{
int nIndex;
OrderLines collection;
public OrderLineEnumerator(OrderLines coll)
{
collection = coll;
nIndex = -1;
}
public void Reset()
{
nIndex = -1;
}
public bool MoveNext()
{
nIndex++;
return (nIndex < collection.Count);
}
public OrderLine Current
{
get
{
return ((OrderLine)collection[nIndex]);
}
}
object IEnumerator.Current
{
get
{
return (Current);
}
}
}
public new OrderLineEnumerator GetEnumerator()
{
return new OrderLineEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

}

}

Tuesday, October 21, 2008

SSIS is Buggy

I spent 2 days creating a package to move data from a Dynamics NAV SQL database to our ActionPak database and got it working.

2 weeks later I decided to break the single package into multiple smaller packages since the execution frequency was not the same on all of them only to find that one of the objects would crash Visual Studio if I tried to delete it.

I had to copy and paste all the variables and other objects out into new packages, then re-assign the data sources on all of them. Then I had to re-write the object that was crashing visual studio by hand. That cost 8 hours.

The offending object had a data viewer on one of the connectors that was causing the crash so from now on I am not leaving any viewers in my projects, I will delete them before saving and exiting, and I am going to make my packages as small as possible so I don't loose 100% of my work if one glitch like that happens again.

SSIS is also very slow to refresh the screen, and the properties are very painful to edit. I hope the next release is a lot smoother.

SSIS Scripts

I have been working with SSIS for a couple weeks, and while I understand a few of the common tools I am really a novice in many areas.

Today I needed to prevent the Available Quantity on inventory from going negative since we don't want to expose that to users of the site I am working on. There are no build in commands to do that in the "Derived Column" object, so I had to use a script object.

For some reason VB is the only language supported, but it was really easy. After identifying which columns were available and whether they were read-only or not, the only code I had to write was:Row.AvailableQty = Max(Row.AvailableQty, 0).

The entire script follows, all but one line was generated by the system.

' Microsoft SQL Server Integration Services user script component
' This is your new script component in Microsoft Visual Basic .NET
' ScriptMain is the entrypoint class for script components

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Public Class ScriptMain
Inherits UserComponent

Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
'
' Add your code here
'
Row.AvailableQty = Max(Row.AvailableQty, 0)

End Sub

End Class

Monday, October 20, 2008

SQL Case

Select
CASE [World Wide Service]
WHEN 1 then [Shipping Agent Code] + '-W'
ELSE [Shipping Agent Code]
end,
Description, [World Wide Service] from [COMPANYNAME$E-Ship Agent Service]

LINQ:Update record

DCMS.net.LINQClasses.DCMSDataClassesDataContext db = new DCMS.net.LINQClasses.DCMSDataClassesDataContext();
var content =
(from cont in db.Contents
where cont.contentID == Convert.ToInt32(editedItem.GetDataKeyValue("contentID").ToString())
select cont).First();

//Custom class to load values into class and apply business logic
ContentMgr.LoadContentFromHash(content, newValues);

//To assign the values directly:
//
// content.contentName = "Content Name";
//
try
{
db.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}

LINQ: Delete single record

DCMS.net.LINQClasses.DCMSDataClassesDataContext db = new DCMS.net.LINQClasses.DCMSDataClassesDataContext();
var query = from content in db.Contents
where content.contentID == Convert.ToInt32(dataItem["contentID"].Text)
select new
{
content.contentID,
};
if (query.Any())
{
var content =
(from cont in db.Contents
where cont.contentID == Convert.ToInt32(dataItem["contentID"].Text)
select cont).First();
db.Contents.DeleteOnSubmit(content);
try
{
db.SubmitChanges();
}
catch (Exception ex)
{
throw ex;
}
}

LINQ:Query to data source on grid

Here is an example LINQ query that populates a gridview:

DCMS.net.LINQClasses.DCMSDataClassesDataContext db = new DCMS.net.LINQClasses.DCMSDataClassesDataContext();
var query = from content in db.Contents
where content.resourceID == Convert.ToInt32(HttpContext.Current.Cache.Get("FAMILY_RESOURCEID"))
select new
{
content.contentID,
content.resourceID,
content.contentName,
content.contentLastName,
content.contentFileName,
content.contentDetails,
content.contentModDate,
content.contentImage1
};
rgFamily.DataSource = query;

What I am listening to

I love to listen to music when coding. I can't do that in the office because if I play the music over the speakers it is very distracting to others, and if I wear headphones I am always having to remove them to respond to the constant minor comments and questions (which I don't really mind, but it is a hassle when headphones are on).

Fortunately I can work from home whenever I want so on the couple days a week that I do I listen to a really great sound system that was bumped from the living room when I upgraded the home theater system.

Today I am listing to One Republic "Dreaming Out Loud".

Backslashes in SQL Queries

I keep forgetting this one so I better write it down:

Brackets ([]) work on string constants (forgive the non sql terminology) as well as fieldnames.

When passing a fully qualified domain name into a sql query 'domain\userid', the backslash will cause errors and, at lease in the SQL Management studio, it can not be escaped via double-backslash 'domain\\userid'.

To pass a backslash in, surround the string in brackets inside the ticks: '[domain\userid]'