2006-12-19
Is DTS dead?
http://msdn2.microsoft.com/en-us/library/ms141026.aspx
But i did find some links about how to create a basic DTS file, possibly that could be run from the command line.
http://www.15seconds.com/Issue/030909.htm
And then what files i would need on the running server
http://www.sqldts.com/default.aspx?225
Webservice Envelope Validation
I have got a extension that just logs soap packets, so its not too hard to plug the validator into that.
ASP.NET 1.1 and 2.0 Working Together
SVN Externals No Good
http://www.brunningonline.net/simon/blog/archives/002031.html
http://svn.haxx.se/dev/archive-2003-07/1617.shtml
A few other people tend to agree, or have found the smae problems that i have.
Its just a nightmare to try and manage them.
I'm actually starting to think that no software configuration information should be stored in the svn repository and that should be maintain by an outside program.
More Automated Software Process
There is maven and lunt build, but both are written in java. And i think they are more similar to cc.net then the linked tool.
If i can't find one written in .net, i might have to build one. A little bit of effort here saves both time and hassel in the future thats for sure.
Server backgrounds
SQL XML Not Required
var objConn = new ActiveXObject("ADODB.Connection");
//Provider=SQLXMLOLEDB.3.0;Data Provider=SQLOLEDB
var objComm = new ActiveXObject("ADODB.Command")
objComm.ActiveConnection = objConn
objComm.CommandText = tSQL
var objStream = new ActiveXObject("ADODB.Stream")
objStream.Open()
objComm.Properties("Output Stream") = objStream
objComm.Execute(null, null, 0x400)
objStream.Position = 0
This turns out not to be the case, you can use this as the connection string:
//Provider=SQLOLEDB;Data Provider=SQLOLEDB
And then you dont need to install the extra component, good for shared hosting!
Handling Nulls in Webservices
So this was where if nulls are passed into a .net 2.0 webservice, then the elements are removed from the soap envelope that is sent.
2006-10-08
Accessing Session in HttpApplication
public class global : System.Web.HttpApplication {
void Application_PreRequestHandlerExecute(object sender, EventArgs e) {
if(User.Identity.IsAuthenticated) {
if(Session != null) {
}
if(Context.Session != null) {
}
}
}
}
The first access to the Session throws this exception:
Session state is not available in this context.
But the second one succeeds, i assume that they would both be accessing the same underlying object. Weird.
2006-09-27
Spring.Net Schema
2006-09-25
Mem Usage vs VM Size
Design Time Master Page
GC.Collect not the solution
Many times i have come to situations where the memory usage in my program spirals out of control. Always i think it is a problem with anything but my program. I test the cleanups of the 3rd party libraries, and every other little thing. Then i resort to put GC.Collect statements around, thinky that it will magically free memory.
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Then i go searching for how to debug these things:
http://blogs.msdn.com/tess/archive/2006/09/06/742568.aspx
http://blogs.msdn.com/tess/archive/2006/08/11/695268.aspx
Finally i get stuck into reviewing my code with a fine tooth comb, and find one thing that was causing the leak, static array on a singleton, used in temporary processing, that didnt get cleared.
2006-09-23
HttpContext Items Strongly Typed
public abstract class AbstractObjectCacher<T> {
#region IoC
private IObjectCache<T> cache;
public IObjectCache<T> Cache {
set { cache = value; }
get { return cache; }
}
#endregion
public T Get() {
return cache.Get();
}
public void Set(T obj) {
cache.Set(obj);
}
public void Dispose() {
T obj = Get();
if(obj != null) {
Set(default(T));
if(obj is IDisposable) {
((IDisposable)obj).Dispose();
}
obj = default(T);
}
cache.Clear();
}
}
So for instance, the thread store i use for unit testing will look like this:
public class ThreadObjectCache<T> : IObjectCache<T> {
#region IoC
private string key;
public string Key {
set {
key = value;
ThreadStore.Initialise(key);
}
get { return key; }
}
#endregion
public T Get() {
return (T)ThreadStore.Get(key);
}
public void Set(T obj) {
ThreadStore.Set(key, obj);
}
public void Clear() {
ThreadStore.Set(key, null);
}
public void Dispose() {
ThreadStore.Dispose(key);
}
}
And the HttpContext store will look like this:
public class HttpContextCache<T> : IObjectCache<T> {
#region IoC
private string key;
public string Key {
set { key = value; }
get { return key; }
}
#endregion
public T Get() {
return (T)HttpContext.Current.Items[key];
}
public void Set(T obj) {
HttpContext.Current.Items[key] = obj;
}
public void Clear() {
HttpContext.Current.Items[key] = null;
}
public void Dispose() {
HttpContext.Current.Items.Remove(key);
}
}
2006-09-20
Changes are not allowed while code is running
Notice the lock icon next to the filename, showing its read only.
This is a feature of VS that allows you to change the code and continue running with the modified code.
It seems to be only useful for desktop applications, not web apps that we develop.
We know that if we change code in the binary then we will need to recompile anyway, so how do we turn off this annoying message.
To remove the message, turn off Edit and Continue by:
Going to options
Go to Debugging, Edit and Continue and uncheck the top box
By turning off Edit and Continue, you still can create and remove debug points why the process is paused.
And you can still edit aspx’s, ascx’s, and their code besides (in the web application) without problems.
db4o 5.7
2006-09-19
Updating Atlas
The other issue i had was i was gettting a debugger alert client side about
PageRequestManagerID not being an attribute on draggablelistitem. This is a custom drag item i have implemented, so i just went digging through AtlasControlToolkit and found something similar to what i wanted to do DragPanelProperties and it has go this code:
[EditorBrowsable(EditorBrowsableState.Never),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string PageRequestManagerID {
get { return null; }
set { throw new NotImplementedException(); }
}
So i just copied that into mine, and things worked. Its weird that there is no need to have the "new" keyword on this method. And why didnt it work in the first place.
ASX Partition Table
Now there may be a better way, by using Partitioning. I will be able to have the same tables, and then a view on top of them that i can query. The partitioning will happen on the stock code. With sql server 2005 this will happen automatically. Nice.
http://weblogs.sqlteam.com/dmauri/archive/2005/07/18/7147.aspx
http://searchtechtarget.techtarget.com/originalContent/0,289142,sid91_gci1207038,00.html
http://www.google.com/search?hl=en&lr=&q=partition+mssql+2005
Unicode Kanji Characters
Javascript Triple Equals (===)
http://www.flashinsider.com/2005/07/25/null-equals-undefined-but-null-doesn-t-strictly-equal-undefined/
http://blogs.msdn.com/ericlippert/archive/2004/07/26/197302.aspx
http://www.ejball.com/EdAtWork/PermaLink.aspx?guid=1a946f91-d37d-4104-a1d3-63e633afafba
So it does a comparison of the value, including the datatype. I don't know if i will ever use i, considering i have never used it, but it might come in handy later.
Output Stream Filtering
My prefered method would be to have a helper static class that references HttpContext.Current in runtime and something else a design time. Then use <%= HtmlHelper.AppRoot %> in templates instead.
Remember to wrapper the script tags in an asp:PlaceHolder if you get the can't add to controls collection error.
2006-09-18
Delete All Rows
Many a time i have wanted to delete all the rows from all the tables in the database. It usually involves a script getting all the names of the tables and deleting one at a time. This script is awesome where you can do it in one line:
EXEC sp_MSforeachtable @command1 = "TRUNCATE TABLE ?"
How many other things will this make easier.
2006-09-14
Random Selects
SELECT *
FROM MyTable
ORDER BY NEWID()
2006-09-11
.Net 2.0 RSA Encryption
The classes all exist in the System.Security.Cryptography namespace:
http://msdn2.microsoft.com/en-us/library/system.security.cryptography.aspx
I have choosen to use RSA asymmetric encryption:
http://msdn2.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx
Many examples helped over the basic msdn documentation:
http://www.codeproject.com/dotnet/RSACryptoPad.asp
http://www.codeproject.com/dotnet/SimpleEncryption.asp
http://www.eggheadcafe.com/articles/20020630.asp
http://www.codeproject.com/dotnet/ComboEncryption.asp
http://blogs.msdn.com/lcris/archive/2006/05/08/592868.aspx
One of the annoying things to remember is that on a shared hosting server, you will most likely not have access to the underlying COM object directories. I thought this would be a show stopper, but this only restricts you from decrypting the values, you can still encrypt items fine. So if your requirement is to collect data and store it securely with a public key, then download it remotely and process it with the private key, this should work.
Some issues that may arise:
http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q322/3/71.asp&NoWebContent=1
.Net Serializers
Interestingly though, the XmlSerializer does not implement the same interface as the BinaryFormatter, so i can't just sub in the constructor. The serialise method has the same parameters which is strange.
Heres the msdn doc on the XmlSerializer:
http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
And this explains the trust issue:
http://haacked.com/archive/2006/07/09/ConfiguringLog4NetWithASP.NET2.0InMediumTrust.aspx
I really thought there might be a way to set the properties that get serialized, but it looks like a LinkDemand and Security assert is performed right at the start of the internal serialization class, so theres no hope of ever getting this to work.
2006-09-06
Inline Server Script in Header
<html>
<head runat="server">
<title></title>
<asp:PlaceHolder runat="server">
<link href="<"%= SomeVariable %>/style.css" rel="stylesheet" type="text/css" />
</asp:PlaceHolder>
</head>
</html>
This way you can still add controls to the header by doing:
Page.Header.Controls.Add();
2006-08-31
c# Anonymous Method Syntax
http://www.theserverside.net/tt/articles/showarticle.tss?id=AnonymousMethods
http://msdn.microsoft.com/msdnmag/issues/06/00/C20/default.aspx
Working Days in T-SQL
http://aaronjohals.blogspot.com/2005/10/number-of-working-days-between-2-dates.html
http://classicasp.aspfaq.com/date-time-routines-manipulation/how-do-i-count-the-number-of-business-days-between-two-dates.html
drop function dbo.GetWorkingDaysDiff
go
create function dbo.GetWorkingDaysDiff(@start datetime, @end datetime)
returns int
as
begin
declare @countdays int
set @countdays = 0
while @start < @end
begin
if (select datepart(dw, @start)) < 6
begin
set @countdays = @countdays + 1
end
set @start = dateadd(d,1,@start)
end
return @countdays
end
GO
print(dbo.GetWorkingDaysDiff('2006/08/21', '2006/08/27'))
go
2006-08-30
NHibernate 1.2.0.Alpha1
As it turns out all collections and associations are lazy loaded in this new version:
http://forum.hibernate.org/viewtopic.php?t=960004&start=15&sid=ba44698acc40eaae77d6d73d7561ba83
http://dotnet.org.za/kuate/archive/2006/05/29/52751.aspx
So just put that attribute into my mapping file and everything went back to normal.
The real underlying cause of all this is that when things get lazy loaded they are a proxy type, not the actual type in the domain model. So when i debugged it like this:
Console.WriteLine(n.GetType());
I was getting a type name like this with these names all joined together with under scores
ProxyInterfaceSystemObject
INHibernateProxy
ISerializable
My tests for type (x is MyType) all fail silently, they really should be converted to proxy interfaces, but i don't need to atm, and i get 20% extra speed.
2006-08-29
ASP.NET 2.0 Medium Trust
nHibernate
http://forum.hibernate.org/viewtopic.php?t=963084&view=previous
<configuration>
<configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler" requirePermission="false"/>
</configSections>
<nhibernate>
<add key="hibernate.use_reflection_optimizer" value="false" />
</nhibernate>
</configuration>
log4net:
http://www.topxml.com/XML/re-37980_Configuring-Log4Net-with-ASP-NET-2-0-in-Medium-Trust.aspx
and just some medium trust explanations:
http://nayyeri.net/archive/2006/06/02/Medium-trust-issue-in-ASP.NET-2.0.aspx
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
Working Around Shared Hosting
Firstly, all calls to GetCompiledPageInstance MUST be replaced with CreateInstanceFromVirtualPath. I have provided the fix for this in a previous thread (http://forum.springframework.net/showthread.php?t=407). This is a must because the GetCompiledPageInstance method has an attribute on it, pretty much killing calls to it unless you are running in full trust mode. On shared servers this will be highly unlikely.
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
Now i had thought this had been commited into the main branch of SPring.Web, but the nightly build and the cvs repository on sourceforge both do not have the fix
The second step to take modifing the spring source, is to find the file src\Spring\Spring.Core\Core\IO\FileSystemResource.cs. This file has two calls like this
fileHandle.Directory.Root.ToString();
In the hosting trust mode, this bombs out with a FileIOPermission violation. The reason being, you don't have access to the root directory when you are on the shared host. The Root property of DirectoryInfo has this line in it causing the exception.
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[] { text1 }, false, false).Demand();
My solution is a little hacky at the moment but you get the idea. All it is doing is getting the root folder (ie c: or d:). This propably wont work on a network drive remember.
fileHandle.Directory.ToString().Substring(0, 3);
Third thing to do is to add requirePermission="false" to the configSections section in web.config. If you dont do this you will receive a Configuration security permission exception.
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"
requirePermission="false"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"
requirePermission="false"/>
</sectionGroup>
</configSections>
The last item on the list is probably the most obscure, and i will try to explain and give some background:
dll's can be signed, which gives them a strong name and a hash, which stops them being modified and re-distributed.
strong named dlls can be registered in the GAC.
From the GAC, dlls can be configured to run in full trust, depending on your .net framework configuration. (see somewhere in control panel -> administration tools).
When you run a web application in anything but full trust, all the dlls in the bin directory run in a partial trust mode.
Strong named assemblies that are NOT in the GAC but in you bin directory, can not by default be called from a partial trusted assembly
So in this case i have my project dll, spring, nhibernate and log4net in the bin directory, plus any dependant dlls. nhibernate and log4net are strong named, but i can only call log4net from my app, not nhibernate. Why is this? its because log4net has an assembly level attribute on it.
[assembly: System.Security.AllowPartiallyTrustedCallers()]
This attribute allows my partially trusted application to call into it without throwing an exception. Details can be found on msdn, its something to do with LinkDemand.
Now it gets tricky, that would mean all the dll's that i have in the bin directory need this attribute. How would i do this?, I could get all the sources for them and recompile, but what happens if i can't get the source, or i have a 3rd party app that is proprietary. I do the following instead:
1. get all the dll's and disassemble them
2. add the AllowPartiallyTrustedCallers attribute to them in the MSIL file
3. remove all signing code from the assembly
4. remove all public keys and hashes from the assembly
5. update any extern assembly declarations, by removing the public hash requirement
6. reassemble the dll's again.
What does this do? It removes all strong names from the assemblies and also updates the references to not require the strong named versions.
As we dont have the keys that sign the dll, we can't resign them, but we can remove the signing altogether.
We could resign them all with new keys that we created and update the references, but that sounds like a lot of work for no gain.
We are going to be running in partial trust mode so we just don't need strong named assemblies.
This process probably wont work in all circumstances mind you.
2006-08-28
NHibernateUtil.IsInitialized()
I thought there must be a way to check whether a collection had been loaded lazyily. First i thought about checking the type to see if it was the dynamic proxy. But then ran into this gem at the nhibernate reference guide:
http://www.hibernate.org/hib_docs/nhibernate/html/performance.html
I could just pass the collection to this method, and it would check if it had been initialised. Just waht i was after. The only other place i found a reference to this function then was at the forums:
http://forums.hibernate.org/viewtopic.php?p=2282177&sid=b5989f2c3f2387add4188a6e13802019
So why dao function ended up as, because i dont want the nhibernate logic permeating my service layer:
public bool HasBeenInitialised(ICollection collection) {
return NHibernateUtil.IsInitialized(collection);
}
2006-08-27
bindingRedirect
Could not load file or assembly 'dommons, Version=0.0.33.0, Culture=neutral, PublicKeyToken=873d6a369a01a6bd' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Now im fine with the error, its a shared strong named assembly, that NOT in the GAC. So how do i fix it. It didn't take long to find the solution was to add a bindingRedirect. I was going to map the 0.0.33.0 version to the lastest 0.0.36.0 one. Easier said than done i'm afraid.
Here is a link explaining the redirect:
http://www.diranieh.com/NETAssemblies/Assemblies.htm
All i would have to do would be to put this in my web.config:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="dommons"
publicKeyToken="873d6a369a01a6bd" culture="neutral" />
<bindingRedirect oldVersion="0.0.33.0" newVersion="0.0.36.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
Though this did not fix the problem. A lot of material seems to be geared towards the assemblies being in the GAC or running as a client application. Not my case of build versions mismateching. To a newer version as well.
So i then spent the next half a day figuring out what was going on.
First checking i was doing it correctly:
http://blogs.msdn.com/suzcook/archive/2004/05/14/132022.aspx
http://plans.thefrankes.com/tutorials/Assemblies/
http://blogs.msdn.com/junfeng/archive/2004/11/16/258081.aspx
I was sure i had the syntax right, time to start using the assembly loading debugger, a tool called fuslogvw. In the start menu, open up the .net framework command prompt and type that. Also make sure you restart IIS to register it, otherwise nothing happens. Here are some more links for debugging:
http://www.grimes.demon.co.uk/workshops/fusWSFive.htm
http://blogs.msdn.com/suzcook/archive/2003/05/29/57120.aspx
http://www.grimes.demon.co.uk/workshops/fusWSFive.htm
So what was my problem, it seems that the redirect was not working. This happens first in the process (msdn). But why was it failing.
The error from fusion log viewer was this:
*** Assembly Binder Log Entry (27/08/2006 @ 3:29:10 PM) ***
The operation failed.
Bind result: hr = 0x80131040. No description available.
Assembly manager loaded from: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll
Running under executable c:\windows\system32\inetsrv\w3wp.exe
--- A detailed error log follows.
=== Pre-bind state information ===
LOG: User = NT AUTHORITY\NETWORK SERVICE
LOG: DisplayName = dommons, Version=0.0.33.0, Culture=neutral, PublicKeyToken=873d6a369a01a6bd
(Fully-specified)
LOG: Appbase = file:///D:/projects/svn/project/trunk/project-web/
LOG: Initial PrivatePath = D:\projects\svn\project\trunk\project-web\bin
LOG: Dynamic Base = C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\project\91bd8e69
LOG: Cache Base = C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\project\91bd8e69
LOG: AppName = fec991e1
Calling assembly : repository, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\projects\svn\project\trunk\project-web\web.config
LOG: Using host configuration file: file:////?\c:\windows\microsoft.net\framework\v2.0.50727\aspnet.config
LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: dommons, Version=0.0.33.0, Culture=neutral, PublicKeyToken=873d6a369a01a6bd
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files
/project/91bd8e69/fec991e1/dommons.DLL.
LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files
/project/91bd8e69/fec991e1/dommons/dommons.DLL.
LOG: Attempting download of new URL file:///D:/projects/svn/project/trunk/project-web/bin/dommons.DLL.
LOG: Assembly download was successful. Attempting setup of file: D:\projects\svn\project\trunk\project-web\
bin\dommons.dll
LOG: Entering download cache setup phase.
LOG: Assembly Name is: dommons, Version=0.0.36.0, Culture=neutral, PublicKeyToken=873d6a369a01a6bd
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: The assembly reference did not match the assembly definition found.
ERR: Setup failed with hr = 0x80131040.
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.
Note the two red lines. The redirect was not working, and as the 33 version could not be found, the application start failed. In frustration i tried a suggestion to put the redirect in the machine.config file, and what do you know, the whole thing started to work. Now at least i know why it isn't working it might be a little easier to figure out the cause. I think i read a permission on a security namespace item may need to be set.
2006-08-25
Collection was modified; enumeration operation may not execute.
Extension Methods
The could be a way to use numerous different methods with the same name, but in different namespaces, but i haven't fully thought about that yet, and propably wont until 3.0 has gone into release.
Here are some links, though they are kind of old:
http://blah.winsmarts.com/2006/05/18/demystifying-c-30--part-3-extension-methods.aspx
http://mtaulty.com/communityserver/blogs/mike_taultys_blog/archive/2006/03/20/5798.aspx
http://www.cincomsmalltalk.com/userblogs/malby/blogView?showComments=true&entry=3304188302
http://blogs.msdn.com/abhinaba/archive/2005/10/21/483337.aspx
2006-08-24
yield
public IEnumerator<Node> GetDepthFirstTraversalEnumerator() {
yield return this.value;
foreach(Node child in this.children) {
IEnumerator<Node> enum_ = kidchildGetDepthFirstTraversalEnumerator();
while(enum_.MoveNext()) {
yield return enum_.Current;
}
}
}
and also found the map function from other laungauges:
public delegate object MapFunction(object o);
public static IEnumerable Map(MapFunction mapFunction, IEnumerable enumerable) {
foreach(object o in enumerable) {
yield return mapFunction(o);
}
}
public static IEnumerable PositiveIntegers() {
int a = 1;
while(true) {
yield return a;
a = a + 1;
}
}
public static IEnumerable SubList(int start, int end, IEnumerable enumerable) {
int count = 0;
foreach(object o in enumerable) {
count++;
if(count < start) {
continue;
} else if(count <= end) {
yield return o;
} else {
yield break;
}
}
}
IEnumerable set = I.SubList(5, 15, I.PositiveNumbers());
foreach(int value in Map(delegate(object o) { return ((int)o) * 2; }, )) {
//do something
}
heres the link to a Fibonacci generator
http://www.cerkit.com/cerkitBlog/2004/06/30/Using+The+Yield++Statement+In+Whidbey+C.aspx
a lazy paged collection:
http://haacked.com/archive/2006/08/14/FunIteratingPagedCollectionsWithGenericsAndIterators.aspx
and a textreader:
http://blogs.msdn.com/jmstall/archive/2005/08/08/textreader_yield.aspx
2006-08-23
WeakReference
object cached = new TimeConsumingToConstructObject();
WeakReference wr = new WeakReference(cached);
cached = null;
if(wr.IsAlive) {
cached = wr.Target;
} else {
cached = new TimeConsumingToConstructObject();
}
To Ruby or not to Ruby
http://discuss.joelonsoftware.com/default.asp?joel.3.309321.3
http://www.pankaj-k.net/archives/2005/11/ruby_or_java_a.html
I mean its sounds good to write less code, and have db mappping handled for you, but at what cost. I have spent years writting jscript asp with variable types, but the amount of errors that you miss without compile time and type checking support is painful. I prefer to let Visual Studio do the meanal tasks like remembering method names and type checking.
I think i saw somewhere that threading and internationalisation were issues, so it doesn't sound like an enterprise framework.
2006-08-21
COLLATE and Coalesce
The other function Coalesce is a C# 2.0 item that does a thing similar to T-SQL's isnull()'s function. So:
string x = null;
string y = null;
string z = "123";
string value = x ?? y ?? z;
(value == "123") == true
So instead of using the :? statement checking nulls, it makes it alot cleaner.
2006-08-19
Javascript Includes not Included
Finally i stumbled accross a similar problem here. But then i tried it in firefox, and i got no errors. Doh, this was that IE bug where the cache gets filled an nothing seems to work anymore. I know that happens with view source, but it must also happen with this. As soon as i cleared the temporary internet files, everything worked again. Lucky with subversion i can just revert, not too much damage done.
Static Code Analysis
The trouble with fxcop is that it only checks the compiled source, it doesn't check the actuall source code. I need a tool to intergrate with cruise control to check coding standards. The is a tool called PREfast in team studio, but i think it only does c/c++ for device drivers. And from the look of this article, thats all that microsoft offers. There is a java open source project called checkstyle that looks promising, but i will have to see that it doesn't throw huge amounts of errors for c#. I am surprised there is not a port yet. The last tool that i had a look at is SSW Code Auditor but it seems there server is having troubles at the moment and i can't download the trial. But it says it overs a large amount of source code checking, from cs, to html, to templates and sql.
2006-08-16
A MulitView with dynamic Views inside an UpdatePanel Exception
ActiveViewIndex is being set to '0'. It must be smaller than the current number of View controls '0'. For dynamically added views, make sure they are added before or in Page_PreInit event.
Parameter name: value
I have an multiview in an updatepanel which has the individual view dynamically generated in OnLoad. So how was i supposed to register them in PreInit if the multiview hadn't even be initialised. Then i stumbled on a solution.
I added some empty dummy views in the ascx file. Then i just cleared them before loading my own dynamic ones. I only added about 10 as i dont think ill ever need more than that, but if i do ill just add some more.
<atlas:UpdatePanel ID="MultiView1UpdatePanel" Mode="Conditional" runat="server">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View0" runat="server">
Empty
</asp:View>
<asp:View ID="View1" runat="server">
Empty
</asp:View>
<asp:View ID="View2" runat="server">
Empty
</asp:View>
<asp:View ID="View3" runat="server">
Empty
</asp:View>
<asp:View ID="View4" runat="server">
Empty
</asp:View>
<asp:View ID="View5" runat="server">
Empty
</asp:View>
<asp:View ID="View6" runat="server">
Empty
</asp:View>
<%-- add more if needed --%>
</asp:MultiView>
</ContentTemplate>
<Triggers>
<atlas:ControlEventTrigger ControlID="Menu1" EventName="MenuItemClick" />
</Triggers>
</atlas:UpdatePanel>
2006-08-10
WebServiceClientFactory
When you define the context object:
<object id="authServerStub"
type="Spring.Web.Services.WebServiceClientFactory, Spring.Services">
<property name="ServiceUrl" value="http://localhost:81/auth/MembershipWS.asmx?wsdl"/>;
<property name="ServiceInterface"
value="security.web.ISpringMembershipProviderAuthServer, dsecurity"/>
</object>
public interface ISpringMembershipProviderAuthServer {
bool ValidateUser(string name, string password);
}
normally in c# you dont have to make the names match, only the types, but in this instance i expect that the client proxy generator uses the interface to pass arguements to the server. If you have them named different then you seems to only get null's on the server end.
Spring.Net WebApplicationContext
First i narrowed the problem to when spring started, which was when the application initialised a custom membership provider. I could also get to the webservice okay via the browser, so it must have been a context issue. I dropped the dependancy injection and created the webservice client in code and things worked fine. Next i ditched the AOP advice around the service.
Finally i removed a piece of code i had custom loading the webcontext and replaced it with:
IApplicationContext ctx = WebApplicationContext.Current;
2006-08-09
Authenticate on LoginControl
Then i released that i had put this:
protected void Page_Load(object sender, EventArgs e) {
Login1.Authenticate += new AuthenticateEventHandler(Login1_Authenticate);
Login1.LoggingIn += new LoginCancelEventHandler(Login1_LoggingIn);
Login1.LoggedIn += new EventHandler(Login1_LoggedIn);
Login1.LoginError += new EventHandler(Login1_LoginError);
}
Security.dll
I have a dll called security and this apparently conflicts with a system dll of the same name.
What do i do, i rename the output of the dll to descurity.dll, clear out the bin directory, restart vstudio and no more problems. Unfortunately i now have to change the names of all the type declarations in web.config and spring files.
forums.microsoft.com
forums.asp.net
2006-08-08
Sandcastle CTP
Whats this, someone has already done it at http://blog.jkowalski.net/?p=52. Thanks Jaroslaw.
CodeFileBaseClass to the rescue of Page Inheritance
Trouble was that all the control definitions in the base class didn't get wired up. You know how it goes with the protected variables. So i spent a whilte trying public, didn't work. Reading blogs suggested using master pages.. Then Scott Allen on Rick Strahl's blog came to the rescue with the CodeFileBaseClass attribute on the page directive.
Nice. Rick's blog
Heres an example: jotek's sample
2006-03-19
2006-03-07
String Function
Anyway i was looking for String.Format
builderau
And also i found a string truncate function:
4guysfromrolla
Its always nice.
Update: found these examples too:
http://blog.stevex.net/index.php/string-formatting-in-csharp/
2006-03-06
.Net 2.0 Code Profilers
Free:
CLR Profiler
nprof
Cost:
ANTS Profiler
aqtime
jetbrains
and last but not least, the most expensive version of VS2005
vsts
I will try the CLR Profiler first and if the results are no good/hard to decipher, which I except, I will download the trial of ANTS, as that seems to be the recommended one.
2006-03-05
ASP.NET 2.0 EventValidation
The state information is invalid for this page and might be corrupted.
After doing a lot of reading about it, this problem is caused by the event validation feature of ASP.NET 2.0. This is where the items in the datagrid are added to an event validation thingy, so that incorrect values can not be used to postback. Now i can solve it two ways, either by disabling eventvalidation it in web.config:
forums.asp.net
channel9
forums.asp.net
Or by registering each of the new items that i add to the datagrid for the callback so that event validation works correct:
alexthissen.nl
I will see how easy it is added the validation, and hope that magicajax will correctly handle the updates. Otherwise i will just turn off the security feature as suggested here:
forums.asp.net
2006-03-04
ASP.NET 2.0 AJAX Frameworks
http://ajaxpatterns.org/DotNet_Ajax_Frameworks
Comparisons:
http://www.daniel-zeiss.de/AJAXComparison/Results.htm
Atlas Tutorial:
http://weblogs.asp.net/scottgu/archive/2005/12/26/433997.aspx
MagicAjax:
http://www.magicajax.net/
Decisions, decisions, which framework will i choose...
This is an awesome looking control so i hope whatever i choose i can build professional controls like this:
http://www.componentart.com/demos/grid/features/ajax_grid/WebForm1.aspx
2006-03-03
Format Source Code in Blog
MSDN VirtualPathProvider
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
<customErrors mode="Off"/>
<trace enabled="true" requestLimit="100" pageOutput="true" traceMode="SortByTime" localOnly="false"/>
<httpHandlers>
<add verb="*" path="*.vrf" type="System.Web.StaticFileHandler" />
</httpHandlers>
</system.web>
</configuration>
And still cannot access by "~/", must access by "~/default.aspx".
VirtualPathProvider IIS vs ASP.NET Development Server
The solution for IIS, to this problem is within one of Mark DÂUrso's presentations, http://blogs.msdn.com/mdurso/ [VSLive]. It involves adding a Wildcard Application Map in IIS's snapin (application configuration->mappings). With this mapping in place though, the ability to have default documents in a folder is lost. When normally requesting an aspx page, the ISAPI extension takes control from IIS. When you request a file that does not have an ISAPI mapping, IIS just servers the file itself. With the wildcard, all files are palmed off to the ASP.NET application extension. Don't know how this affects load/caching, having all files go though ASP.NET.
Heres what msdn says about wildcard application mappings in IIS 6.0:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx
Some info on httphandlers when wildcard application mappings are used:
http://support.microsoft.com/?kbid=909641
Static mappings for content served by ASP.NET compared to IIS
http://www.agileprogrammer.com/dotnetguy/archive/2003/05/04/4550.aspx
ASP.NET 2.0 VirtualPathProvider
One method of achieving this would be to use ASP.NET 2.0's VirtualPathProvider. Apparently you should be able to set up certain path's that map to what you want, rather than the filesystem. This could be a database, xml file or in this instance, an assembly.
If I wanted to create an assembly for a client script application, for example a html content editor, that consisted of style sheets, images and script files, the idea would be to map the path, ~/scripts/htmleditor, to a custom VirtualPathProvider. This provider would then read the file from the assembly and return it to the client.
Here are a few links to how to implement:
http://blogs.msdn.com/davidebb/archive/2005/11/27/497339.aspx
http://dotnetjunkies.com/WebLog/teund/archive/2005/02/15/54446.aspx