instruction stringlengths 0 30k ⌀ |
|---|
The ASP.NET Sitemap feature is built for that and works well in a lot of cases. If you get in a spot where you want your [Menu to look different from your Sitemap, here are some workarounds][1].
If you have a dynamic site structure, you can [create a custom sitemap provider][2]. You might get to the point where it's more trouble than it's worth, but in general populating your menu from your sitemap gives you some nice features like security trimming, in which the menu options are appropriate for the logged-in user.
[1]: http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security-trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx
[2]: http://msdn.microsoft.com/en-us/library/aa479320.aspx#custsit_topic4 |
How should I handle a situation where I need to store several unrelated types but provide specific types on demand? |
|.net|generics| |
I'm working on an editor for files that are used by an important internal testing tool we use. The tool itself is large, complicated, and refactoring or rewriting would take more resources than we are able to devote to it for the forseeable future, so my hands are tied when it comes to large modifications. I must use a .NET language.
The files are XML serialized versions of four classes that are used by the tool (let's call them A, B, C, and D). The classes form a tree structure when all is well. Our editor works by loading a set of files, deserializing them, working out the relationships between them, and keeping track of any bad states it can find. The idea is for us to move away from hand-editing these files, which introduces tons of errors.
For a particular type of error, I'd like to maintain a collection of all files that have the problem. All four classes can have the problem, and I'd like to reduce duplication of code as much as possible. An important requirement is the user needs to be able to get the items in sets; for example, they need to get all A objects with an error, and telling them to iterate over the whole collection and pick out what they want is unacceptable compared to a <code>GetAs()</code> method. So, my first thought was to make a generic item that related the deserialized object and some metadata to indicate the error:
public class ErrorItem<T>
{
public T Item { get; set; }
public Metadata Metadata { get; set; }
}
Then, I'd have a collection class that could hold all of the error items, with helper methods to extract the items of a specific class when the user needs them. This is where the trouble starts.
None of the classes inherit from a common ancestor (other than <code>Object</code>). This was probably a mistake of the initial design, but I've spent a few days thinking about it and the classes really don't have much in common other than a GUID property that uniquely identifies each item so I can see why the original designer did not relate them through inheritance. This means that the unified error collection would need to store <code>ErrorItem<Object></code> objects, since I don't have a base class or interface to restrict what comes in. However, this makes the idea of this unified collection a little sketchy to me:
Public Class ErrorCollection
{
public ErrorItem<Object> AllItems { get; set; }
}
However, this has consequences on the public interface. What I really want is to return the appropriate <code>ErrorItem</code> generic type like this:
public ErrorItem<A>[] GetA()
This is impossible because I can only store <code>ErrorItem<Object></code>! I've gone over some workarounds in my head; mostly they include creating a new <code>ErrorItem</code> of the appropriate type on-the-fly, but it just feels kind of ugly. Another thought has been using a <code>Dictionary</code> to keep items organized by type, but it still doesn't seem right.
Is there some kind of pattern that might help me here? I know the easiest way to solve this is to add a base class that A, B, C, and D derive from, but I'm trying to have as small an impact on the original tool as possible. Is the cost of any workaround great enough that I should push to change the initial tool? |
There's no "process explorer" kind of tool for Firefox; but there's http://developer.mozilla.org/en/docs/Venkman with profiling mode, which you could use to see the time spent by chrome (meaning non-content, that is not web-page) scripts.
From what I've read about it, DTrace might also be useful for this sort of thing, but it requires creating a custom build and possibly adding additional probes to the source. I haven't played with it myself yet. |
I don't know that there is a property to control this (can't find one on MSDN), but I'd think you could just iterate through the Controls property of the LoginView and hide that panel/label/whatever. |
How do you open a file in C++? |
|c++|file|io| |
I want to open a file for reading, the C++ way. I need to be able to do it for text files, which would involve some sort of read line function, and a way to do it for binary files, which would provide a way to read raw data into a char* buffer. |
There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen/fread/fclose, or you could use the C++ fstream facilities (ifstream/ofstream), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations.
All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:
int nsize = 10;
char *somedata;
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata,nsize);
myfile.close();
Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing). |
There will be no performance hit, both statements are perfectly equal.
HTH |
Note that the != operator is not standard SQL. If you want your code to be portable (that is, if you care), use <> instead. |
If it's only two users, then Access should do just fine if you put the .mdb on a shared drive.
Have you tried it first rather than just assume it will be a problem.
I believe the recommended max concurrent users for Access is 5 but on occasion I've pushed it past this and never come unstuck.
On the other hand I did once use Access as the front end to MySQL in a single user environment (me). It was a singularly unpleasant experience, I can't imagine it would become nicer with two users. |
These 3 will get the same exact execution plan
declare @id varchar(40)
select @id = '172-32-1176'
select * from authors
where au_id <> @id
select * from authors
where au_id != @id
select * from authors
where not(au_id = @id)
It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself |
This will just allow you a little more flexibility in your web server setup. Using safe_mode_gid, you should be able to run individual PHP/httpd processes for each user on your system, but give each process the ability to read some shared files as long as they are all run as the same group (GID) and the shared files are owned by this group. |
Best css generator lanugage? |
|css|maintainability| |
Reusing values in css (particularly colors) has always been a problem for me when it comes to maintaining that css. What are the best tools for creating variables, or generally improving maintainability with css? |
You can quote if you like, or you can escape the spaces with a preceding \\, but most UNIX paths (Mac OS X aside) don't have spaces in them.
/Applications/Image\ Capture/Contents/MacOS/Image\ Capture
"/Applications/Image Capture/Contents/MacOS/Image Capture"
/Applications/"Image Capture"/Contents/MacOS/"Image Capture"
All refer to the same executable under Mac OS X.
|
You can quote if you like, or you can escape the spaces with a preceding \\, but most UNIX paths (Mac OS X aside) don't have spaces in them.
/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture
"/Applications/Image Capture.app/Contents/MacOS/Image Capture"
/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"
All refer to the same executable under Mac OS X.
|
You can quote if you like, or you can escape the spaces with a preceding \\, but most UNIX paths (Mac OS X aside) don't have spaces in them.
/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture
"/Applications/Image Capture.app/Contents/MacOS/Image Capture"
/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"
All refer to the same executable under Mac OS X.
I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.
|
Do you have the <machinekey> node on both servers set to the same value?
You can override the machine.config file in web.config to set this. This needs to match otherwise you can get strange situations like this.
|
I would probably make a batch file, something like this (untested):
dir /b /S *.cs > allcsfiles.txt
svn add --targets allcsfiles.txt
I believe svn won't mind you trying to add files which are already versioned..
Anyway, that's probably about as automatic as you will easily get. |
I'm not sure exactly what you are trying to accomplish. Telnet is usually thought of as a character-at-a-time protocol, so when you say "incoming messages" do you mean each character is a message? Or the entire user's session is a message?
I'll make some assumtions.
You have users logging in via telnet and you want to capture everything they do while they are logged in. Later, you want to be able to associate the stuff they did with that user and the time and date they did it. You'll need to be able to search later to find out "who did 'rm *' as root?"
I would store each user's session as a separate file, with a naming convention that includes the user's login and a timestamp.
e.g. 2008_09_08_14_52_07_nidonocu
Within the the file, I would capture each byte received, assuming they will mostly be plain text characters.
e.g.
ls
cd www
ls
vi index.html
/copyright 2007
llllllllllllr8:wq
exit
Write the 8-bit ANSI characters to the file as well. You should be able to use a text editor and grep to do basic audits and searches. You could use a binary file viewer or get more sophisticated later if you need to actually read the 8-bit data.
Backups, archiving, purging, etc. can all be done using regular file system tools and scripting.
My apologies if my assumptions are wrong.
--
Bruce
|
I needed to pass id and password to a cmd (or bat) file at the time of running rather than hardcoding them into the file.
Here's how I do it.
echo off
fake-command /u %1 /p %2
Here's what the command line looks like:
test.cmd admin P@55w0rd > test-log.txt
The %1 applies to the first parameter the %2 (and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.
Afterward: This is my first attempt to answer my own question which, to hear Jeff discuss it is a "...perfectly acceptable...." way of using SO. I'm just not certain if there's already a format for doing it.
----------
## Additional Notes from the Community ##
**Per Frank Krueger**
>Yep, and just don't forget to use variables like %%1 when using if and for and the gang.
>
>If you forget the double %, then you will be substituting in (possibly null) command >line arguments and you will receive some pretty confusing error messages.
**Per Greg Hewgill**
>Another useful tip is to use %* to mean "all the rest". For example,
> echo off
> fake-command /u %1 /p %2 %*
>When you run:
> test-command admin password foo bar
>the above batch file will run:
> fake-command /u admin /p password foo bar
>Edit: Actually, %* means "all", so one would actually need to use shift to do the above:
> echo off
> set arg1=%1
> set arg2=%2
> shift
> shift
> fake-command /u %arg1% /p %arg2% %*
>I may still have the syntax slightly wrong, but this is the general idea. It's been a >very long time since I've written a batch file, and my brain keeps thinking "shell script"!
**Per thelsdj**
>If you want to intelligently handle missing parameters you can do something like:
> IF %1.==. GOTO No1
> IF %2.==. GOTO No2
> ... do stuff...
> GOTO End1
> :No1
> ECHO No param 1
> GOTO End1
> :No2
> ECHO No param 2
> GOTO End1
> :End1 |
How do you change the default homepage in a Grails application? |
|grails| |
What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way. |
A good [blog post here][1] but basically prefix local temp tables with # and global temp with ## - eg
CREATE TABLE #localtemp
[1]: http://techahead.wordpress.com/2007/09/27/sql-temporary-tables/ |
I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db.
This felt better than the usual "run a script to setup my test db, then after the tests run do a cleanup of the junk/test data". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of "everything in the db needs to be 'just so' before I run these tests".
**Here is a snippet of the abstract base class used for data access**
Public MustInherit Class Repository(Of T As Class)
Implements IRepository(Of T)
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
Private mConnection As IDbConnection
Private mTransaction As IDbTransaction
Public Sub New()
mConnection = Nothing
mTransaction = Nothing
End Sub
Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
mConnection = connection
mTransaction = transaction
End Sub
Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)
Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader
Dim entityList As List(Of T)
If Not mConnection Is Nothing Then
Using cmd As SqlCommand = mConnection.CreateCommand()
cmd.Transaction = mTransaction
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
Else
Using conn As SqlConnection = New SqlConnection(mConnectionString)
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
conn.Open()
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
End Using
End If
Return Nothing
End Function
End Class
**next you will a sample data access class using the above base to get a list of products**
Public Class ProductRepository
Inherits Repository(Of Product)
Implements IProductRepository
Private mCache As IHttpCache
'This const is what you will use in your app
Public Sub New(ByVal cache As IHttpCache)
MyBase.New()
mCache = cache
End Sub
'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test
Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
MyBase.New(connection, transaction)
mCache = cache
End Sub
Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts
Dim Parameter As New Parameter()
Parameter.Type = CommandType.StoredProcedure
Parameter.Text = "spGetProducts"
Dim productList As List(Of Product)
productList = MyBase.ExecuteReader(Parameter)
Return productList
End Function
'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object
Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)
Dim productList As New List(Of Product)
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = reader("ProductID")
product.SupplierID = reader("SupplierID")
product.CategoryID = reader("CategoryID")
product.ProductName = reader("ProductName")
product.QuantityPerUnit = reader("QuantityPerUnit")
product.UnitPrice = reader("UnitPrice")
product.UnitsInStock = reader("UnitsInStock")
product.UnitsOnOrder = reader("UnitsOnOrder")
product.ReorderLevel = reader("ReorderLevel")
productList.Add(product)
End While
If productList.Count > 0 Then
Return productList
End If
End Using
Return Nothing
End Function
End Class
**And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis**
**below is the simple testing base class I used**
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Public MustInherit Class TransactionFixture
Protected mConnection As IDbConnection
Protected mTransaction As IDbTransaction
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
<TestInitialize()> _
Public Sub CreateConnectionAndBeginTran()
mConnection = New SqlConnection(mConnectionString)
mConnection.Open()
mTransaction = mConnection.BeginTransaction()
End Sub
<TestCleanup()> _
Public Sub RollbackTranAndCloseConnection()
mTransaction.Rollback()
mTransaction.Dispose()
mConnection.Close()
mConnection.Dispose()
End Sub
End Class
**and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly**
**I know this doesn't test the "spGetProducts" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs**
Imports SampleApplication.Library
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> _
Public Class ProductRepositoryUnitTest
Inherits TransactionFixture
Private mRepository As ProductRepository
<TestMethod()> _
Public Sub Should-Insert-Update-And-Delete-Product()
mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)
'** Create a test product to manipulate throughout **'
Dim Product As New Product()
Product.ProductName = "TestProduct"
Product.SupplierID = 1
Product.CategoryID = 2
Product.QuantityPerUnit = "10 boxes of stuff"
Product.UnitPrice = 14.95
Product.UnitsInStock = 22
Product.UnitsOnOrder = 19
Product.ReorderLevel = 12
'** Insert the new product object into SQL using your insert sproc **'
mRepository.InsertProduct(Product)
'** Select the product object that was just inserted and verify it does exist **'
'** Using your GetProductById sproc **'
Dim Product2 As Product = mRepository.GetProduct(Product.ID)
Assert.AreEqual("TestProduct", Product2.ProductName)
Assert.AreEqual(1, Product2.SupplierID)
Assert.AreEqual(2, Product2.CategoryID)
Assert.AreEqual("10 boxes of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(14.95, Product2.UnitPrice)
Assert.AreEqual(22, Product2.UnitsInStock)
Assert.AreEqual(19, Product2.UnitsOnOrder)
Assert.AreEqual(12, Product2.ReorderLevel)
'** Update the product object **'
Product2.ProductName = "UpdatedTestProduct"
Product2.SupplierID = 2
Product2.CategoryID = 1
Product2.QuantityPerUnit = "a box of stuff"
Product2.UnitPrice = 16.95
Product2.UnitsInStock = 10
Product2.UnitsOnOrder = 20
Product2.ReorderLevel = 8
mRepository.UpdateProduct(Product2) '**using your update sproc
'** Select the product object that was just updated to verify it completed **'
Dim Product3 As Product = mRepository.GetProduct(Product2.ID)
Assert.AreEqual("UpdatedTestProduct", Product2.ProductName)
Assert.AreEqual(2, Product2.SupplierID)
Assert.AreEqual(1, Product2.CategoryID)
Assert.AreEqual("a box of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(16.95, Product2.UnitPrice)
Assert.AreEqual(10, Product2.UnitsInStock)
Assert.AreEqual(20, Product2.UnitsOnOrder)
Assert.AreEqual(8, Product2.ReorderLevel)
'** Delete the product and verify it does not exist **'
mRepository.DeleteProduct(Product3.ID)
'** The above will use your delete product by id sproc **'
Dim Product4 As Product = mRepository.GetProduct(Product3.ID)
Assert.AreEqual(Nothing, Product4)
End Sub
End Class
I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;) |
I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db.
This felt better than the usual "run a script to setup my test db, then after the tests run do a cleanup of the junk/test data". This also felt closer to unit testing because these tests could be run alone w/out having a great deal of "everything in the db needs to be 'just so' before I run these tests".
**Here is a snippet of the abstract base class used for data access**
Public MustInherit Class Repository(Of T As Class)
Implements IRepository(Of T)
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
Private mConnection As IDbConnection
Private mTransaction As IDbTransaction
Public Sub New()
mConnection = Nothing
mTransaction = Nothing
End Sub
Public Sub New(ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
mConnection = connection
mTransaction = transaction
End Sub
Public MustOverride Function BuildEntity(ByVal cmd As SqlCommand) As List(Of T)
Public Function ExecuteReader(ByVal Parameter As Parameter) As List(Of T) Implements IRepository(Of T).ExecuteReader
Dim entityList As List(Of T)
If Not mConnection Is Nothing Then
Using cmd As SqlCommand = mConnection.CreateCommand()
cmd.Transaction = mTransaction
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
Else
Using conn As SqlConnection = New SqlConnection(mConnectionString)
Using cmd As SqlCommand = conn.CreateCommand()
cmd.CommandType = Parameter.Type
cmd.CommandText = Parameter.Text
If Not Parameter.Items Is Nothing Then
For Each param As SqlParameter In Parameter.Items
cmd.Parameters.Add(param)
Next
End If
conn.Open()
entityList = BuildEntity(cmd)
If Not entityList Is Nothing Then
Return entityList
End If
End Using
End Using
End If
Return Nothing
End Function
End Class
**next you will see a sample data access class using the above base to get a list of products**
Public Class ProductRepository
Inherits Repository(Of Product)
Implements IProductRepository
Private mCache As IHttpCache
'This const is what you will use in your app
Public Sub New(ByVal cache As IHttpCache)
MyBase.New()
mCache = cache
End Sub
'This const is only used for testing so we can inject a connectin/transaction and have them roll'd back after the test
Public Sub New(ByVal cache As IHttpCache, ByVal connection As IDbConnection, ByVal transaction As IDbTransaction)
MyBase.New(connection, transaction)
mCache = cache
End Sub
Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductRepository.GetProducts
Dim Parameter As New Parameter()
Parameter.Type = CommandType.StoredProcedure
Parameter.Text = "spGetProducts"
Dim productList As List(Of Product)
productList = MyBase.ExecuteReader(Parameter)
Return productList
End Function
'This function is used in each class that inherits from the base data access class so we can keep all the boring left-right mapping code in 1 place per object
Public Overrides Function BuildEntity(ByVal cmd As System.Data.SqlClient.SqlCommand) As System.Collections.Generic.List(Of Product)
Dim productList As New List(Of Product)
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = reader("ProductID")
product.SupplierID = reader("SupplierID")
product.CategoryID = reader("CategoryID")
product.ProductName = reader("ProductName")
product.QuantityPerUnit = reader("QuantityPerUnit")
product.UnitPrice = reader("UnitPrice")
product.UnitsInStock = reader("UnitsInStock")
product.UnitsOnOrder = reader("UnitsOnOrder")
product.ReorderLevel = reader("ReorderLevel")
productList.Add(product)
End While
If productList.Count > 0 Then
Return productList
End If
End Using
Return Nothing
End Function
End Class
**And now in your unit test you can also inherit from a very simple base class that does your setup / rollback work - or keep this on a per unit test basis**
**below is the simple testing base class I used**
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Public MustInherit Class TransactionFixture
Protected mConnection As IDbConnection
Protected mTransaction As IDbTransaction
Private mConnectionString As String = ConfigurationManager.ConnectionStrings("Northwind.ConnectionString").ConnectionString
<TestInitialize()> _
Public Sub CreateConnectionAndBeginTran()
mConnection = New SqlConnection(mConnectionString)
mConnection.Open()
mTransaction = mConnection.BeginTransaction()
End Sub
<TestCleanup()> _
Public Sub RollbackTranAndCloseConnection()
mTransaction.Rollback()
mTransaction.Dispose()
mConnection.Close()
mConnection.Dispose()
End Sub
End Class
**and finally - the below is a simple test using that test base class that shows how to test the entire CRUD cycle to make sure all the sprocs do their job and that your ado.net code does the left-right mapping correctly**
**I know this doesn't test the "spGetProducts" sproc used in the above data access sample, but you should see the power behind this approach to unit testing sprocs**
Imports SampleApplication.Library
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
<TestClass()> _
Public Class ProductRepositoryUnitTest
Inherits TransactionFixture
Private mRepository As ProductRepository
<TestMethod()> _
Public Sub Should-Insert-Update-And-Delete-Product()
mRepository = New ProductRepository(New HttpCache(), mConnection, mTransaction)
'** Create a test product to manipulate throughout **'
Dim Product As New Product()
Product.ProductName = "TestProduct"
Product.SupplierID = 1
Product.CategoryID = 2
Product.QuantityPerUnit = "10 boxes of stuff"
Product.UnitPrice = 14.95
Product.UnitsInStock = 22
Product.UnitsOnOrder = 19
Product.ReorderLevel = 12
'** Insert the new product object into SQL using your insert sproc **'
mRepository.InsertProduct(Product)
'** Select the product object that was just inserted and verify it does exist **'
'** Using your GetProductById sproc **'
Dim Product2 As Product = mRepository.GetProduct(Product.ID)
Assert.AreEqual("TestProduct", Product2.ProductName)
Assert.AreEqual(1, Product2.SupplierID)
Assert.AreEqual(2, Product2.CategoryID)
Assert.AreEqual("10 boxes of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(14.95, Product2.UnitPrice)
Assert.AreEqual(22, Product2.UnitsInStock)
Assert.AreEqual(19, Product2.UnitsOnOrder)
Assert.AreEqual(12, Product2.ReorderLevel)
'** Update the product object **'
Product2.ProductName = "UpdatedTestProduct"
Product2.SupplierID = 2
Product2.CategoryID = 1
Product2.QuantityPerUnit = "a box of stuff"
Product2.UnitPrice = 16.95
Product2.UnitsInStock = 10
Product2.UnitsOnOrder = 20
Product2.ReorderLevel = 8
mRepository.UpdateProduct(Product2) '**using your update sproc
'** Select the product object that was just updated to verify it completed **'
Dim Product3 As Product = mRepository.GetProduct(Product2.ID)
Assert.AreEqual("UpdatedTestProduct", Product2.ProductName)
Assert.AreEqual(2, Product2.SupplierID)
Assert.AreEqual(1, Product2.CategoryID)
Assert.AreEqual("a box of stuff", Product2.QuantityPerUnit)
Assert.AreEqual(16.95, Product2.UnitPrice)
Assert.AreEqual(10, Product2.UnitsInStock)
Assert.AreEqual(20, Product2.UnitsOnOrder)
Assert.AreEqual(8, Product2.ReorderLevel)
'** Delete the product and verify it does not exist **'
mRepository.DeleteProduct(Product3.ID)
'** The above will use your delete product by id sproc **'
Dim Product4 As Product = mRepository.GetProduct(Product3.ID)
Assert.AreEqual(Nothing, Product4)
End Sub
End Class
I know this is a long example, but it helped to have a reusable class for the data access work, and yet another reusable class for my testing so I didn't have to do the setup/teardown work over and over again ;) |
Many issues can cause that error. It's usually a Response.Write call, but anything that modifies the response can cause it.
We probably won't be able to help you unless you post some pertinent code-behind. |
You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph...
In order to find your graph in the list, you have to register it in the running object table:
void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister )
{
IMoniker* pMoniker;
IRunningObjectTable* pROT;
GetRunningObjectTable( 0, &pROT );
WCHAR wsz[256];
swprintf_s( wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() );
CreateItemMoniker( L"!", wsz, &pMoniker );
pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister );
// Clean up any COM stuff here ...
}
After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke |
Does it make any difference if you put non-breaking spaces immediately before and after the anchor element?
<p> ... <a ... >Link text</a> ... </p>
Admittedly a workaround at best but it might buy you some time to research a real solution. |
Look at [http://www.yammer.com][1] for a corporate version of twitter.
[1]: http://www.yammer.com |
Is there a need to destroy char * = "string" or char * = new char[6] |
|c++|c|memory| |
I assume when I do **char* = "string"** its the same thing as **char* = new char[6]**. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves. |
Apache XML-RPC Exception Handling |
|exception|xml-rpc| |
What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC? |
What about confidentiality and information security? I'm certain a company run IM service would be a better alternative.
I've viewed Twitter and similar services to be used as marketing tools to engage customers and prospects. |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) |
|sql|optimization|aggregate|olap|python| |
I need a real DBA's opinion here:
Using Postgres 8.3 I've built a table with 350,000 rows (responses to a survey):
CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from 'responses.csv' delimiter as ','
On my Macbook Pro it takes about 200 ms to execute this query:
SELECT count(id), avg(a),avg(b),avg(c), avg(d) FROM tuples;
I assumed that databases were really darn good at simple queries like this, but obviously I'm missing something...
I wrote some tests in Java and Python for context and they crush SQL (except for pure python):
java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)
Tunings i've tried without success include (blindly following some web advice):
increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous.
Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.
|
What are the differences between htmlspecialchars and htmlentities. When should I use one or the other? |
How to encrypt email addresses using JQuery |
|jquery|email| |
Is there a way to use JQuery to cloak or encrypt email addresses on an HTML page without changing the syntax in the HREF? |
After some research, I think I'll go with the **ISO 7064 Mod 97,10** formula. It seems pretty solid as it is used to validate IBAN (International Bank Account Number).
The formula is very simple:
- Take a number : `123456`
- Apply the folowing formula to obtain the 2 digits checksum : `mod(98 - mod(number * 100, 97), 97)` => 76
- Concat number and checksum to obtain the code => 12345676
- To validate a code, verify that `mod(code, 97) == 1`
Test :
- `mod(12345676, 97) = 1` => GOOD
- `mod(21345676, 97) = 50` => BAD !
- `mod(12345678, 97) = 10` => BAD !
Apparently, this algorithm catches most of the errors.
Another interesting option was the [Verhoeff algorithm][1]. It has only one verification digit and is more difficult to implement (compared to the simple formula above).
[1]: http://en.wikipedia.org/wiki/Verhoeff_algorithm |
Are you referring to the concept of a free database to distribute with an application, or an Access-like "single file, no installation" database?
As in, things like SQL Server Express Edition require things like runtimes to be installed, databases to be created and mounted, entries on people's Start menus that they won't recognize (my wife asked why SQL Server was on her laptop the other day) whereas an Access database can be run in a single file.
I guess what I'm asking is do you want to think of the database as a document you write to or as an instance of something on someone else's machine? |
Referencing Embedded resources from other resources in c# |
|c#|asp.net|javascript| |
In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using `ClientScriptManager.GetWebResourceUrl()`. However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.
this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';
Could become something like:
this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';
|
From the PHP documentation for [htmlentities][1]:
>This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
From the PHP documentation for [htmlspecialchars][2]:
>Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use htmlspecialchars whenever possible.
[1]: http://us2.php.net/htmlentities
[2]: http://us.php.net/htmlspecialchars |
|oracle|content-management|ucm| |
What I normally do in this case is to have a single thread that is responsible for putting the data into the database, and have all auxiliary threads report to that thread, which then queues up the data, and writes it either serially, or in batches (depending on the requirements, and how much database activity I'm willing to put up with). |
The only significant pitfall to long cache times occurs when you want to update that data. To be safe, you have to assume that it will take up to a week for the new version to become available. Intermediate hosts such as a ISP level proxy servers often do cache aggressively so this delay will happen.
If there are large files to be cached, I'd look at ensuring your content engine supports If-Modified-Since.
For smaller files (page content, CSS, images, etc), where reducing the number of round-trips is the key, having a long expiry time (a year?) and changing the URL when the content changes is the best. This lets you control when user agents will fetch the new content.
Yahoo! have published a two part article on [reducing HTTP requests][1] and [browser cache usage][2]. I won't repeat it all here, but these are good reads which will guide you on what to do.
My feeling is to pick a time period high enough to cover most users single sessions but low enough to not cause too much inconvenience should you wish to update the content. Be sure to support If-Modified-Since if you have a Last-Modified for all your content.
Finally, if your content is cacheable at all and you need to push new content out now, you can always use a new URL. This final cachable content URL can sit behind a fixed [HTTP 302 redirect][3] URL should you wish to publish a permanent link to the latest version.
[1]: http://yuiblog.com/blog/2006/11/28/performance-research-part-1/
[2]: http://yuiblog.com/blog/2007/01/04/performance-research-part-2/
[3]: http://en.wikipedia.org/wiki/HTTP_302 |
Long-term Static Page Caching |
|caching|asp.net|c#|static| |
I maintain several client sites that have no dynamic data whatsoever, everything is static asp.net with c#.
Are there any pitfalls to caching the entire page for extreme periods of time, like a week? |
|c#|asp.net|caching|static| |
I maintain several client sites that have no dynamic data whatsoever, everything is static asp.net with c#.
Are there any pitfalls to caching the entire page for extreme periods of time, like a week?
Kibbee, We use a couple controls on the sites (ad rotator, some of the ajax extensions) on the sites. They could probably be completely written in html but for convenience sake I just stuck with what we use for every other site. |
Another "it depends". However, I can also think of a very common scenario where static just won't work. If you have a web site that gets a decent amount of traffic, and you have a static database layer with a shared connection, you could be in trouble. In ASP.Net, there is _one_ instance of your application created by default, and so if you have a static database layer you may only get _one_ connection to the database for _everyone_ who uses your web site. |
|reporting|exchange-server|scripting| |
Namespace/solution structure |
|namespace| |
I apologize for asking such a generalized question, but it's something that can prove challenging for me. My team is about to embark on a large project that will hopefully drag together all of the random one-off codebases that have evolved through the years. Given that this project will cover standardizing logical entities across the company ("Customer", "Employee"), small tasks, large tasks that control the small tasks, and utility services, I'm struggling to figure out the best way to structure the namespaces and code structure.
Though I guess I'm not giving you enough specifics to go on, **do you have any resources or advice on how to approach splitting your domains up logically**? In case it helps, most of this functionality will be revealed via web services, and we're a Microsoft shop with all the latest gizmos and gadgets.
I'm debating one massive solution with subprojects to make references easier, but will that make it too unwieldy? Should I wrap up legacy application functionality, or leave that completely agnostic in the namespace (making an "OurCRMProduct.Customer" class versus a generic "Customer" class, for instance)? Should each service/project have its own BAL and DAL, or should that be an entirely separate assembly that everything references? I don't have experience with organizing such far-reaching projects, only one-offs, so I'm looking for any guidance I can get. |
|namespaces| |
How do you spawn another process in C? |
|c|api|process| |
How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux. |
|c|api|process| |
How do you properly use namespaces in C++? |
|c++|qt|namespace| |
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.
How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces? |
|c++|qt|namespaces| |
Of Ways to Count the Limitless Primes |
|prime|primes|language-agnostic| |
Recently I've been cobbling together a little library of prime checks. **"Why?"** you ask? **"Well, just because."** I respond.
I've implemented a couple and have seen the post on the [the most efficient way to find the first 10000](http://stackoverflow.com/questions/622/most-efficient-code-for-the-first-10000-prime-numbers), but what I'm wanting to know is:
- **How many unique ways are there of finding primes and what are they?**
And by _unique_ I mean bearing enough difference as to make it useful for them to be different functions within the same library.... |
The accepted answer wasn't quite correct, but it pointed in the right direction.
There is a hotfix for VS2k5 SP1 described in KB article 947315 that addresses this issue. |
Also be careful with double-quotes -- on the Unix shell this expands variables. Some are obvious (like `$foo` and `\t`) but some are not (like `!foo`).
For safety, use single-quotes! |
#line and jump to line |
|text-editor|preprocessor| |
Do any editors honer C #line directives with regards to goto line features?
*Context:*
I'm working on a code generator and need to jump to a line of the output but the line is specified relative to the the #line directive I'm adding.
I can drop them but then finding the input line is even a worse pain |
Do any editors honer C #line directives with regards to goto line features?
*Context:*
I'm working on a code generator and need to jump to a line of the output but the line is specified relative to the the #line directives I'm adding.
I can drop them but then finding the input line is even a worse pain |
How to push data to variety of different client types in near real time? |
|push| |
We need is to push sports data to a number of different client types such as ajax/javascript, flash, .NET and Mac/iPhone. Data updates need to only be near-real time with delays of several seconds being acceptable.
How to best accomplish this?
|
See the answers to the following questions
* [Create a variable in .CSS file for use within that .CSS file][1]
* [Avoiding repeated constants in CSS][2]
[1]: http://stackoverflow.com/questions/47487/create-a-variable-in-css-file-for-use-within-that-css-file
[2]: http://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css |
I think the Apple guidelines sum it up nicely.
If you're writing a control that will be used in multiple applications and is completely generic, then creating a custom object is a good idea. You'll be able to visualize the look and set properties directly from Interface Builder.
If your control is limited to one application, or is tightly coupled with your data, then moving it into a custom object really won't buy you much.
It's not difficult to create a custom view, there's a lot of easy to follow guides out there. |
Can't you just force them to allocate all their memory on the stack? This way it would be garanteed to be freed after the function exits. |
The first example is not valid XML, the declaration has to be the first thing in a XML document.
But besides that, comments can go anywhere else.
Correcting your first example:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Queries used: ... -->
<dataset>
</dataset>
|
A better solution than attempting to log mallocs might be to sandbox the functions when you call them—give them access to a fixed segment of memory and then free that segment when the function is done running.
Unconfined, incompetent memory usage can be just as damaging as malicious code. |
The main thing that I've seen with regards to complaints about Active Record is that when you create a model around a table, and you select several instances of the model, you're basically doing a "select * from ...". This is fine for editing a record or displaying a record, but if you want to, say, display a list of the cities for all the contacts in your database, you could do "select City from ..." and only get the cities. Doing this with Active Record would require that you're selecting all the columns, but only using City.
Of course, varying implementations will handle this differently. Nevertheless, it's one issue.
Now, you can get around this by creating a new model for the specific thing you're trying to do, but some people would argue that it's more effort than the benefit.
Me, I dig Active Record. :-)
HTH |
Because of budget constraints I think it will have to beta-tester's approch,i tried following the guide and cant seem to get it working. Before I spend time getting it to work, I just confrim, Replicating between SqlServer 2005 and Compact Edition is something that can be done? |
You'll want to familiarize yourself with [repository hooks][1], particularly the [post-commit hook][2]
[1]: http://svnbook.red-bean.com/en/1.4/svn-book.html#svn.ref.reposhooks "The Subversion Book: Repository hooks"
[2]: http://www.petefreitag.com/item/244.cfm "Using Subversion hooks to send out build emails" |
No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.
Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.
If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension). |
You use the [post-commit hooks][1]. Here's a guide: [http://builddeploy.blogspot.com/2008/01/implementing-subversion-post-commit.html][2]
Here's a sample script that sends an email after each commit: [commit-email.rb][3]
[1]: http://svnbook.red-bean.com/en/1.4/svn.reposadmin.create.html#svn.reposadmin.create.hooks
[2]: http://builddeploy.blogspot.com/2008/01/implementing-subversion-post-commit.html
[3]: http://svn.collab.net/repos/svn/trunk/tools/hook-scripts/commit-email.rb |
I would also take a look at [Passenger][1]. It's a lot easier to get going than the traditional solution of Apache/nginx + Mongrel.
[1]: http://modrails.com/ |