Wednesday, October 31, 2007

Changing AppSettings in .NET

Using appsettings("key")=value . Will change the settings in memory and not in web.config

To change it in both, use this method:

VB:

Private Sub ChangeAppSettings(ByVal key As String, ByVal NewValue As String)
Dim cfg As Configuration
cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")

Dim setting As KeyValueConfigurationElement = _
CType(cfg.AppSettings.Settings(key), KeyValueConfigurationElement)

If Not setting Is Nothing Then
setting.Value = NewValue
cfg.Save()
End If
End Sub

C#:

private void ChangeAppSettings(string key, string NewValue)
{
Configuration cfg;
cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

KeyValueConfigurationElement setting = (KeyValueConfigurationElement)cfg.AppSettings.Settings(key);

if ((setting != null)) {
setting.Value = NewValue;
cfg.Save();
}
}

Disabling ASP.NET Caching

Most web applications with authentication disable caching so after you logout, you can't click the back button to try and view pages that you shouldn't be accessing.

In ASP.NET, you can use the following code to disable caching
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()

There are some other snippets you could try out too. Here's one:

Response.ClearHeaders();
Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1
Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1
Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1

Another one to add directly to the HTML code on your page (this one has been known to not work on Firefox):

meta equiv="CACHE-CONTROL" content="NO-CACHE"

You'll probably want to test the code with all of your target web browsers.

Sunday, October 28, 2007

.NET to Java

The JaCIL compiler can convert .NET assemblies (binaries) to Java byte code. The output is a Java Archive (JAR). You can find more here:
http://www.cs.rit.edu/~atg2335/project/quickstart.php

Saturday, October 27, 2007

Mini-blog comment replies

A lot of people these days write short tit-bits on social networking sites instead of paragraphs and journals of hand-written notes. I think it's an evolution of the Orkut scrapbook and the Facebook wall - you would now post messages to your own scrapbook/wall and people following your mini-blog get notified, often via a free SMS text message.

When you let visitors add comments to your posts, you would reply back to their comment and there's no way for them to know that you've replied to their comment. Blogger.com addresses that by emailing you all comments after yours (or at least that's what I think it does) if you check a little box when posting a comment.

Some systems are smarter and maintain a tree-like structure to keep track of which post is a reply to which other post, but then it all depends on how the designers intended it to be. Being an architect myself, I have to make trade-offs between cost and functionality and, in the end, the more you spend, the better stuff you can come up with.

Friday, October 26, 2007

Java Application as a Windows Service

I was looking up some way to turn a Java application into a Windows service.

In Linux/Unix, it's much simpler since all you need to do is specify a command with all arguments, which in our case is the JVM executable java.exe with the class or Java archive name as a parameter.

In Windows, we would use a product like the Java Service Wrapper or the Java Service Launcher to launch the application whenever Windows starts up, without requiring the user to log in.
I haven't tried either of those products yet since I'm not currently into Java development, but when I do I'll post more about them here.

Monday, October 22, 2007

.NET Remoting over TCP

Remoting in .NET is quite similar to RMI in Java. To begin with, we need an object that has the methods we would be executing on the server-side. This object inherits from MarshalByRefObject. This indicates that the client does not get a copy of the object but rather a reference to the remote object. We then have a hosting process and a client process.

In our example, the hosting process creates a new instance of the TcpChannel class (pass the TCP port number to the constructor of TcpChannel for the server hosting process) and registers the object using ChannelServices.RegisterChannel. Then, the class we are hosting has to be registered using the RemotingConfiguration.RegisterWellKnownServiceType method - it takes the type of our class as the first parameter, the registration name as the second parameter and the object mode (singleton & single call modes) as the third parameter. When creating a console application, we would usually add a Console.ReadLine statement at the end of the application to prevent it from exiting.

The client application would create and register an instance of TcpChannel. Then, obtain an instance of the class hosted on the server using Activator.GetObject - with the type of the class as the first parameter and the URL (Example: tcp://localhost:8080/my_service) as the second parameter. You can now call methods on the object as you would for a normal object.

Sunday, October 21, 2007

Type Forwarding

Type Forwarding enables client applications to refer to a library at compile time for a type that is later moved to another library.

Example:
using System.Runtime.CompilerServices;
[assembly:TypeForwardedTo(typeof(DestinationLib.TheType))]

The IFormattable interface

Implementing the IFormattable interface let's you do much more with the ToString() method if you're developing text-based applications or are trying to create strings out of object fields.

To implement the IFormattable interface, you have to create a ToString method that accepts a format string and an IFormatProvider object. The IFormatProvider object isn't relevant but the format string can be used, such as to return only one field of an object. Here's a sample implementation:

class TimeInterval : IFormattable {

...

public override string ToString() {
return ToString(null, null);
}

public string ToString (string format, IFormatProvider formatProvider) {

if (format == null) {
return this.Hour.ToString() + ":" + this.Minute.ToString();
} else if (format == "h") {
return this.Hour.ToString();
} else if (format == "m") {
return this.Minute.ToString();
} else throw new Exception("Invalid format specified");
}
}

To use the new method, you could provide a format string to either string.Format or Console.WriteLine. Example:
TimeInterval timeInterval = new TimeInterval();
Console.WriteLine("{0:h} hours and {0:m} minutes", timeInterval);
Console.WriteLine("{0,2:h}:{0,2:m}", timeInterval); //the ",2" specifies the minimum number of characters in the resulting string - if positive, the output is left-padded, otherwise it is right-padded

Saturday, October 20, 2007

Common Interfaces

The following are some common interfaces implemented by user-defined types:

IComparable: This is required for sorting.

IDisposable: This is used for manually disposing an object

IConvertible: This provides conversion to a base type

ICloneable: This is to provide a copy for an object

IEquatable: This is used when comparison of objects using "==" is required

IFormattable: This is used to convert an object into a formatted string (rather than use the base ToString method)

Group chat coming soon in GoogleTalk

Google has a GoogleTalk gadget web client accessible from it's website at http://www.google.com/talk . It features Group chat but the downside is that it doesn't receive offline messages. As a friend from the old country would say, you've got to pick what suits the moment.

If it's any indicate of what's to come, we should see Group Chat in the GoogleTalk client sometime soon.

RSS vs Atom

RSS and Atom are both used to publish news feeds (summarized content used by readers to track content changes). Both are quite popular, although RSS has received more attention than Atom. RSS is a specification by the Harvard University, whereas Atom is an RFC by the IETF and IESG.

I read a pretty interesting comparison of the two at:
http://www.intertwingly.net/wiki/pie/Rss20AndAtom10Compared

Friday, October 19, 2007

VB 7 vs VB 8: Operator Overloading

When designing .NET as a programming platform, the designers could either leave out operator overloading, as Java does, or they could continue the tradition started off by C and continued by C++ to provide greater control to the programmer. They chose to let the programmer decide which path to take and so added the feature into the framework, but for some reason didn't provide a way to use it through Visual Basic .NET 2003 (VB 7).

In .NET 1.1, VB 7 did not include the concept of operator overloading. You could neither define nor use overloaded operators and the workaround was to create methods, such as a .Add(object) method. C#, however, did include operator overloading even on .NET 1.1.

.NET 2.0 introduced the Operator keyword in Visual Basic, a feature in VB 8, which reduces the amount of code and provides added convenience for the developers.

.NET Value Types

Value types in .NET

The following are the built-in value types in .NET. Value types are stored on the stack and can be accessed more efficiently than reference types.

Type: SByte
Alias(es): sbyte
Size (in bytes): 1
Range: -128 to 127

Type: Byte
Alias(es): byte
Size (in bytes): 1
Range: 0 to 255

Type: Int16
Alias(es): Short, short
Size (in bytes): 2
Range: -32768 to 32767

Type: Int32
Alias(es): Integer, int
Size (in bytes): 4
Range: -2147483648 to 2147483647

Type: UInt32
Alias(es): UInteger, uint
Size (in bytes): 4
Range: 0 to 4294967295

Type: Int64
Alias(es): Long, long
Size (in bytes): 8
Range: -9223372036854775808 to 9223372036854775807

Type: Single
Alias(es): float
Size (in bytes): 4
Range: -3.402823E+38 to 3.402823E+38

Type: Double
Alias(es): double
Size (in bytes): 8
Range: -1.79769313486232E+308 to 1.79769313486232E+308

Type: Decimal
Alias(es): decimal
Size (in bytes): 16
Range: -79228162514264337593543950335 to 79228162514264337593543950335

Type: Char
Alias(es): char
Size (in bytes): 2
Range:

Type: Boolean
Alias(es): bool
Size (in bytes): ?
Range: true, false

Type: IntPtr
Alias(es):
Size (in bytes): Platform-specific
Range:

Type: DateTime
Alias(es): Date, date
Size (in bytes): 8
Range: 1/1/0001 12:00:00 AM to 12/31/9999 11:59:59 PM


Operations with Int32, UInt32 and Double types are optimized by the runtime or the hardware.

Browsing the Linux source code

The Linux source code is a pain to go through. There's so much in there that you need to get someone to tell you where to look if you're ever planning to change anything. There are things to make your life easier, though. The LXR C source code to HTML converter adds cross-references and hyperlinks so you can find your way around just any piece of C source code. The folks at Promethos were nice enough to run the LXR on the Linux source code and the resulting HTML is available at: http://www.promethos.org/lxr/http/source

Unlike in real life, most of the good things in the computing world are free!

The Bionic Woman

Today is my weekend. I've been catching up with the Bionic Woman TV series and it's pretty neat. I've seen most of the episodes of the 1976 series and all the aired episodes of this year's series. I even saw the pre-air version of the first episode - they edited out a whole character! She wasn't all that pretty so who cares? :-P

The 1976 series starts off with Jamie Summers coming out of surgery to fix some of the bugs from her bionic replacement operation (in the 1976 series, Jamie Summers has a parachute-related accident). She returns home to Ojai and becomes a school teacher at an air force base and takes up some missions. Except for the 1st and 2nd episodes, all the others are pretty much disconnected.

In the 2007 series, Jamie Summers is carrying and shortly after meeting up with Will, her boyfriend to tell him about her pregnancy, she has a vehicle accident caused by Sara, the first bionic woman, suffers injuries and the only way to save her is through bionic replacement. Sara meets up with her a couple of times and in the 3rd episode she tells Jamie she is dying and needs her help... Sara took up bionic replacement before the technology was perfected and wants Jamie to go back with her to try some of the 'upgrades' as a fix.

Update: I watched episode 4 today and apparently Jamie has her clock ticking just like Sara does. The project sponsor does promise to work on a cure at the end of the episode.

Symantec blocks email

Symantec Client Firewall prevents me from sending out email from an email client that uses GMail as a server. I ran a system restore and got back all the factory-installed software and the Symantec suite happens to be one of them.

I haven't uninstalled it yet. I'm just sending my email through GMail's web interface for now, but something has got to change soon - either Symantec gives me an update or I move to something else.

Thursday, October 18, 2007

Project Planner on Windows

If you want to create a Gantt chart and manage a To Do list of tasks on a project, you don't have to spend a couple of hundred dollars to buy MS Project. You can settle for Planner, an open-source project management utility included with most Linux distributions. A windows version is available at: http://winplanner.sourceforge.net/ for free download.