Monday, June 15, 2009

CodeFile and Codebehind


I have the site that builds and runs perfectly on my development machine. It was created in Visual Studio 2008 and then ported to Visual Studio 2010, .NET 4.0. However, when I deploy it to the IIS, I got the very strange error message: Could not find Default.aspx.


Then I started investigation and found that the original error message was Parser Error Message: The file 'Default.aspx.cs' does not exist. The resolution for the problem is very simpple: just change the CodeFile to Codebehind in Default.aspx and republish the site.

Monday, September 18, 2006

How to display an image without creating a file? ( ASP.NET , C# )


PageWithImage.aspx.cs :
   public class PageWithImage : Page
{
private void Page_Load(object sender, EventArgs e)
{
using(Bitmap bmp = new Bitmap( blankW, blankH ))
using(Graphics g = Graphics.FromImage( bmp ))
{
g.FillRectangle( ... );
g.DrawString( ... );
g.DrawLine( ... );

Response.ContentType = "image/gif";
bmp.Save( Response.OutputStream, ImageFormat.Gif );
}

}
...
}

LandVP LLC

Thursday, September 14, 2006

A couple of tips about IDisposable (C# .NET)

There are tips that connected to using the disposable pattern and finalization code. Probably it should be included in our code standard document or people should pay attention to it.

Managed types must occasionally encapsulate control over resources that are not managed by the CLR. In such cases, the smallest possible class, or “wrapper”, should be used to encapsulate these resources. Ideally, this thin wrapper should contain just allocation along with provisions for basic access to and freeing of the resources. This small class should provide a destructor (~T()) and implement explicit Dispose method to enable users to free resources owned by an instance deterministically.

Implicit cleanup should always be provided by protecting resources with a SafeHandle. Implementing finalizers by hand is seldom necessary because of this type in the .NET Framework 2.0.

In every case where a type owns resources or it owns types which themselves own resources you should give users the ability to explicitly release them. Developers will then have the oprion to initiate the release of resources once the object is no longer n use. Explicit control should always be provided with a Dispose method based on the IDisposable interface.

Sealed classes that own unmanaged resources without wrappers:

  • Implement a finalizer (~T());
  • Implement IDisposable with a simple method Dispose();

Sealed classes that own wrapped resources:

  • Implement IDisposable with a simple method Dispose();

Not sealed classes that own unmanaged resources without wrappers have to implement complete Disposable pattern (i.e. implement a finalizer ~T(), implement IDisposable interface (Dispose() method, it has to be final (not virtual) method), implement protected virtual void Dispose(bool) method).

Not sealed classes that own wrapped resources don’t have to implement finalizers (just implement IDisposable interface with final Dispose() method) and implement protected virtual void Dispose(bool) method for cleaning the resources.

Do fully implement the dispose pattern on classes with disposable subtypes, even if the base type does not own resources. This will enable programmers coding against the base class to dispose of further derived instances properly.

Do not re-implement IDisposable interface, override void Dispose(), or override Finalize if a base class in your class hierarchy has already defined them according to this pattern. Just override virtual void Dispose(bool) function.

Do not create any other variations of the Dispose methods other than the two specified here: void Dispose() and virtual void Dispose(bool disposing). Dispose should be considered a reserved word in our code standard and used only in context of this pattern to avoid misunderstanding.

Do implement IDisposable pattern on every type that have finalizers (~T()). This gives users of your type a possibility to explicitly clean up resources.

Do allow your Dispose method to be called more than once. It should not generate an exception.

Set to null large managed object fields in your Dispose method.

LandVP LLC

Wednesday, September 13, 2006

IDisposable and finalization code in C# .NET

There is a plenty of errors with finalization and Disposable pattern in code that new C# developers write, that’s why I decided to write about.

When we need to implement a finalizer (destructor)?

The finalization code is incredibly useful when we need to release unmanaged resources. But the problem is that we have no guarantee when the finalization code is called. And because it is not public method the user could not call it explicitly. That is the reason why we need to implement the Disposable pattern. Classes, that don’t need to release unmanaged resources, should not implement a finalizer and IDisposable.

What is the Disposable pattern and when we need to use it?

We need to implement the Disposable pattern only in case when we need to add a finalization code.

The sample of implementation of the Disposable pattern:


class SomeClass : IDisposable
{
// Track whether Dispose has been called.
bool _disposed = false;
object _syncObject = new object();

///
/// When garbage collected, this Finalize method, which
/// will close the unmanaged resource’s handle, is called.
///

~SomeClass()
{
Dispose(false);
}

///
/// Implement IDisposable.
/// Do not make this method virtual.
/// A derived class should not be able to override this method.
///

public void Dispose()
{
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
Dispose(true);
}

///
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
///

protected virtual void Dispose(bool disposing)
{
lock(_syncObject)
{
if (_disposed)
return;
if (disposing)
{
// The object is being explicitly disposed of/closed, not
// finalized. It is therefore safe for code in this if
// statement to access fields that reference other
// objects because the Finalize method of these other objects
// hasn’t yet been called.
}

_disposed = true;
}
}
}



How to use the objects that implements IDisposable interface:


When you create this kind of object you need to call IDisposable.Dispose() explicitly or implicitly (using statement).

The example of explicit using Dispose:


SomeClass someClassObject = new SomeClass();
// do something with someClassObject
someClassObject.Dispose();

SomeClass yetAnotherObject = new SomeClass();
try
{
// do something with yetAnotherObject
}
finally
{
yetAnotherObject.Dispose();
}


The Dispose should be called to release resources.

The example of implicit using Dispose:

using(SomeClass someClassObject = new SomeClass())
{
// do something with someClassObject
}


In this case Dispose() is called by using statement when we go out of using block.

LandVP LLC

Monday, August 07, 2006

How to send a mail from the ASP.NET web form.



In .NET 2.0 we have SmtpClient class that allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
Namespace: System.Net.Mail

Example
protected void BtnSubmit_Click(object sender, EventArgs e)
{
if(!validateFields())
return;


SmtpClient smtpClient = new SmtpClient(host, port);
smtpClient.Credentials = new NetworkCredential(user, password);

MailAddress from = new MailAddress(EmailBox.Text, NameBox.Text);
MailAddress to = new MailAddress(to_mail);

MailMessage message = new MailMessage(from, to);
message.Subject = string.Format(subject_template, NameBox.Text, PhoneBox.Text);
message.Body = QuestionBox.Text;
try
{
smtpClient.Send(message);
Response.Redirect(redirect_success,true);
}
catch(Exception ex)
{
ErrorMessage = ex.Message;
Response.Redirect(redirect_error, true);
}
}

LandVP LLC

Wednesday, December 07, 2005

Programmatic Channel Registration

A remoting channel is any component that implements the IChannel interface. Both the client and the host application need to register which channels they wish to use, using the static method RegisterChannel of the ChannelServices class.

Host channels registration


The host must register at least one channel if it wants to export objects.

// Register TCP channel
IChannel channel = new TcpChannel(8005);
ChannelServices.RegisterChannel(channel);

// Register HTTP channel
IChannel channel = new HttpChannel(8006);
ChannelServices.RegisterChannel(channel);


LandVP LLC