Showing posts with label ASPX. Show all posts
Showing posts with label ASPX. Show all posts

Sunday, February 22, 2009

Useful Image WaterMark Extension Method

Today i'll give you a useful Extension Method in order to Add some Text to Image that can be used in HttpHandler to display copyrighted images from Database for a Photo Store for example.

WaterMarkImageHandler.ashx

Here is the Extension Code

public static Bitmap WaterMarkImage(this Bitmap bmp, String Text)
{
Image img = new Bitmap(bmp, new Size(bmp.Width, bmp.Height));
Bitmap tmp = new Bitmap(img);
using (Graphics graphic = Graphics.FromImage(tmp))
{
SolidBrush brush = new SolidBrush(Color.FromArgb(120, 255, 255, 255));
Font font = new Font("Arial", 18, FontStyle.Bold);
graphic.DrawString(Text, font, brush, new PointF(10, 30));
}
return tmp;
}
Here is a Sample of Usage
public class WaterMarkImageHandler : 
IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Image img = Bitmap.FromFile(context.Server.MapPath("~/03SC008.JPG"));
Bitmap bmp = new Bitmap(img);
bmp = bmp.WaterMarkImage("SB2 DEVELOPPERS BLOG TEST");
bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}

public bool IsReusable
{
get
{
return true;
}
}
}

Download Solution - WaterMarkImageHandler.zip

Source : http://blog.sb2.fr/post/2008/11/29/Useful-Image-WaterMark-Extension-Method.aspx

Cookies Extensions Methods

Tonight a simple way to manage Cookies on an ASP.NET Application with Strongly Typed Objects.

These Extensions might be improved but it's a beginning.

Here is the code

public static class CookieExtensions
{
public static void AddToCokie(this HttpCookie cok, String name, T val)
where T : struct
{
if (cok == null)
return;
if (!String.IsNullOrEmpty(cok.Values[name]))
cok.Values.Remove(name);
cok.Values.Add(name, val.ToString());
HttpContext.Current.Response.Cookies.Add(cok);
}
public static T GetCookieValue(this HttpCookie cok, String name)
where T : struct
{
if (cok == null)
return default(T);
if (String.IsNullOrEmpty(cok[name]))
return default(T);

return cok[name].ConvertTo();
}
public static T ConvertTo(this String input) where T : struct
{
T ret = default(T);

if (!string.IsNullOrEmpty(input))
{
ret = (T)Convert.ChangeType(input, typeof(T));
}

return ret;
}
}

And here is a sample of usage

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Int32 orderId = Request.Cookies["MyCookie"].GetCookieValue("OrderId");
Response.Write(orderId.ToString());
}
}

protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyCookie"].AddToCokie("OrderId", Int32.Parse(this.TextBox1.Text));
}
}
Source : http://blog.sb2.fr/post/2008/11/29/ASPNET-Cookies-Extensions-Methods.aspx

HowTo Get Current Online Users Count and Infos with ASP.NET

Today I'll talking about getting current online users count and informations about them using ASP.NET and HttpModule.

Here is our OnlineUserInfo class
public class OnlineUserInfo
{
public String UserAgent { get; set; }
public String SessionId { get; set; }
public String IPAddress { get; set; }
public String UrlReferrer { get; set; }
public DateTime SessionStarted { get; set; }
public IPrincipal CurrentUser { get; set; }

public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("UserAgent = {0} | ", UserAgent);
sb.AppendFormat("SessionId = {0} | ", SessionId);
sb.AppendFormat("IPAddress = {0} | ", IPAddress);
sb.AppendFormat("UrlReferrer = {0} | ", UrlReferrer);
sb.AppendFormat("SessionStarted = {0}", SessionStarted);
return sb.ToString();
}
}


Here is our OnlineUserHttpModule

public class OnlineUsersModule : IHttpModule
{
private static Int32 _sessionTimeOut = 20; // Set Default to 20 Minutes
private static List _onlineUsers = null;

public static List OnlineUsers
{
get
{
CleanExpiredSessions();
return _onlineUsers;
}
}

private static void CleanExpiredSessions()
{
_onlineUsers.RemoveAll(delegate(OnlineUserInfo user)
{
return user.SessionStarted.AddMinutes(_sessionTimeOut) < _onlineusers =" new">();

// Get the Current Session State Module
SessionStateModule module = context.Modules["Session"] as SessionStateModule;

module.Start += new EventHandler(Session_Start);
}

private void Session_Start(object sender, EventArgs e)
{
HttpRequest Request = HttpContext.Current.Request;
HttpApplicationState Application = HttpContext.Current.Application;
HttpSessionState Session = HttpContext.Current.Session;

// Get Session TimeOut
_sessionTimeOut = HttpContext.Current.Session.Timeout;

Application.Lock();

OnlineUserInfo user = new OnlineUserInfo();

user.SessionId = Session.SessionID;
user.SessionStarted = DateTime.Now;
user.UserAgent = !String.IsNullOrEmpty(Request.UserAgent)
? Request.UserAgent : String.Empty;
user.IPAddress = !String.IsNullOrEmpty(Request.UserHostAddress)
? Request.UserHostAddress : String.Empty;
if (Request.UrlReferrer != null)
{
user.UrlReferrer = !String.IsNullOrEmpty(Request.UrlReferrer.OriginalString)
? Request.UrlReferrer.OriginalString : String.Empty;
}
else
{
user.UrlReferrer = String.Empty;
}
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
user.CurrentUser = HttpContext.Current.User;
}

// Add the New User to Collection
_onlineUsers.Add(user);
Application.UnLock();
}

public void Dispose()
{
}

#endregion
}


Here is a sample of Getting Informations using this HttpModule.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(OnlineUsersModule.OnlineUsers.Count);

foreach (OnlineUserInfo user in OnlineUsersModule.OnlineUsers)
{
Response.Write(user.ToString());
}
}
}


Download Solution - OnlineUserInfos.zip

More

Clearing Extra White Lines from Pages HttpModule

Here is a pretty useful HttpModule in order to clear Extra White lines from ASP.NET Pages using an Response Filter.

Here is the HttpModule code
public class ClearWhiteLinesModule : IHttpModule
{
#region IHttpModule Members

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}

public void Dispose()
{
}

#endregion

private void BeginRequest(object sender, EventArgs e)
{
HttpApplication Application = sender as HttpApplication;
String OriginalString = Application.Request.Url.OriginalString;
if (OriginalString.ToUpperInvariant().Contains(".ASPX"))
{
Application.Response.Filter = new ClearWhiteLinesFilter(Application.Response.Filter);
}
}

private class ClearWhiteLinesFilter : Stream
{
#region Private Fields

private Stream _originalFilter;

#endregion

#region Constructors

public ClearWhiteLinesFilter(Stream originalFilter)
{
_originalFilter = originalFilter;
}

#endregion

#region Public Overrides Properites

public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override long Length { get { return 0; } }
public override long Position { get; set; }

#endregion

#region Public Overrides Methods

public override void Flush()
{
_originalFilter.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _originalFilter.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _originalFilter.Seek(offset, origin);
}
public override void SetLength(long value)
{
_originalFilter.SetLength(value);
}
public override void Close()
{
_originalFilter.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
Byte[] data = new Byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
String html = Encoding.Default.GetString(buffer);

// Remove Extra White Lines
html = html.Replace("\r\n\r\n", String.Empty);

Byte[] outdata = Encoding.Default.GetBytes(html);
_originalFilter.Write(outdata, 0, outdata.GetLength(0));
}

#endregion
}
}


ClearWhiteLinesModule.cs

More

Clearing Extra White Lines from Pages HttpModule

Here is a pretty useful HttpModule in order to clear Extra White lines from ASP.NET Pages using an Response Filter.

Here is the HttpModule code
public class ClearWhiteLinesModule : IHttpModule
{
#region IHttpModule Members

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}

public void Dispose()
{
}

#endregion

private void BeginRequest(object sender, EventArgs e)
{
HttpApplication Application = sender as HttpApplication;
String OriginalString = Application.Request.Url.OriginalString;
if (OriginalString.ToUpperInvariant().Contains(".ASPX"))
{
Application.Response.Filter = new ClearWhiteLinesFilter(Application.Response.Filter);
}
}

private class ClearWhiteLinesFilter : Stream
{
#region Private Fields

private Stream _originalFilter;

#endregion

#region Constructors

public ClearWhiteLinesFilter(Stream originalFilter)
{
_originalFilter = originalFilter;
}

#endregion

#region Public Overrides Properites

public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override long Length { get { return 0; } }
public override long Position { get; set; }

#endregion

#region Public Overrides Methods

public override void Flush()
{
_originalFilter.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _originalFilter.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _originalFilter.Seek(offset, origin);
}
public override void SetLength(long value)
{
_originalFilter.SetLength(value);
}
public override void Close()
{
_originalFilter.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
Byte[] data = new Byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
String html = Encoding.Default.GetString(buffer);

// Remove Extra White Lines
html = html.Replace("\r\n\r\n", String.Empty);

Byte[] outdata = Encoding.Default.GetBytes(html);
_originalFilter.Write(outdata, 0, outdata.GetLength(0));
}

#endregion
}
}


ClearWhiteLinesModule.cs

More

HowTo Redirect WebResource.axd Requests To Another Server

Today an other trick in order to Redirect WebResource.axd Requests to Another Web Application Server. In collaboration with my friend Sebastien. V we made this HttpModule.

Here is the code
public class WebResourceRedirectorModule : IHttpModule
{
#region IHttpModule Members

public void Dispose()
{
}

public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}

#endregion

private void BeginRequest(object sender, EventArgs e)
{
HttpRequest Request = HttpContext.Current.Request;
HttpResponse Response = HttpContext.Current.Response;
String Url = Request.Url.OriginalString;
String RemoteServer = "http://localhost:2847";

if (Url.Contains("WebResource.axd"))
{
Uri uri = new Uri(Url);
String RemoteUrl = RemoteServer + uri.PathAndQuery;
HttpWebRequest req = WebRequest.Create(RemoteUrl) as HttpWebRequest;
using (StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream()))
{
String data = sr.ReadToEnd();
Response.Write(data);
Response.End();
}
}
}
}


Download Solutionhttp://www.blogger.com/img/blank.gif - WebResourceRedirector.zip

more

FeedBurner Syndication Widget for BlogEngine.NET

Here is a simple FeedBurner Syndication Widget for BlogEngine.NET

Here is the "Very" Simple Code :)

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;

public partial class widgets_Syndication_widget : WidgetBase
{

public override string Name
{
get { return "Syndication"; }
}

public override bool IsEditable
{
get { return true; }
}

public override void LoadWidget()
{
StringDictionary settings = GetSettings();
String contents = String.Empty;
if (settings.ContainsKey("Contents"))
{
contents = settings["Contents"];
}
this.ltContents.Text = contents;
}
}

To Install it download and extract the file at the end of this post and copy the Syndication directory to ~/widgets of your BlogEngine.NET web site.

The Add it to your SideBar and Copy/Paste your FeedBurner Button Link as the Following Sample :

To Install it download and extract the file at the end of this post and copy the Syndication directory to ~/widgets of your BlogEngine.NET web site.

The Add it to your SideBar and Copy/Paste your FeedBurner Button Link as the Following Sample :

<br/>
<p style="text-align: center">
<a href="http://feeds.feedburner.com/sb2/JSrW">
<img style="border-style: initial; border-color: initial; border-width: 0px"
src="http://feeds.feedburner.com/[YOURFEED]?bg=FF66300&fg=444444&anim=1" alt="" width="88" height="26" />
a>
p>
Syndication.rar

more

Blocking not Robots.txt Compliant Crawlers

Today an article talking about blocking Crawlers which are not Robots.txt Compliant. Number of web sites grows exponentially day by day and crawlers too on the Internet ! But there is a lot of Web Crawlers that don't follow Robots.txt Disallow Rules or totally ignore it ...

Download Solution - RobotModule.zip

more

GridView Paged Edition WebControl for ASP.NET

In this article i'll talk about GridView in order to display Data in an ASP.NET Page. While working with a lot of Data, Data Paging must be very useful.

So here is the Standard ASP.NET GridView but in it's Paged Edition.

Download Solution - PagedDataWithGridView.zip

more

Simple TagCloud WebControl For ASP.NET

Simple TagCloud WebControl For ASP.NET

Download Solution - TagCloudNET.zip

RequireSSL Attribute For ASP.NET

Here is a quick Custom Attribute in order to Define if a Page must be in HTTP SSL Mode and switch it to SSL if not.

[AttributeUsage(AttributeTargets.Class)]
public class RequireSSLAttribute : Attribute
{
public static void Validate(IHttpHandler handler)
{
Type type = handler.GetType();
Object[] objs = type.GetCustomAttributes(typeof(RequireSSLAttribute), true);
if (objs != null && objs.Count() > 0)
{
SwitchToSsl();
}
}
private static void SwitchToSsl()
{
#if DEBUG
return;
#endif
String baseUrl = HttpContext.Current.Request.Url.OriginalString;
Uri uri = new Uri(baseUrl);
String url = baseUrl.Replace(uri.Scheme, Uri.UriSchemeHttps);
HttpContext.Current.Response.Redirect(url, true);
}
}

A Sample Page Implementation

In order to make it working, you just need to call RequireSSLAttribute Validate Method. On Page Constructor might be fine :)

[RequireSSL]
public partial class _Default : Page
{
public _Default()
{
RequireSSLAttribute.Validate(this);
}

protected void Page_Load(object sender, EventArgs e)
{
}
}
Source : http://blog.sb2.fr/post/2008/12/20/RequireSSL-Attribute-For-ASPNET.aspx

RequireSSL Attribute For ASP.NET

Here is a quick Custom Attribute in order to Define if a Page must be in HTTP SSL Mode and switch it to SSL if not.

[AttributeUsage(AttributeTargets.Class)]
public class RequireSSLAttribute : Attribute
{
public static void Validate(IHttpHandler handler)
{
Type type = handler.GetType();
Object[] objs = type.GetCustomAttributes(typeof(RequireSSLAttribute), true);
if (objs != null && objs.Count() > 0)
{
SwitchToSsl();
}
}
private static void SwitchToSsl()
{
#if DEBUG
return;
#endif
String baseUrl = HttpContext.Current.Request.Url.OriginalString;
Uri uri = new Uri(baseUrl);
String url = baseUrl.Replace(uri.Scheme, Uri.UriSchemeHttps);
HttpContext.Current.Response.Redirect(url, true);
}
}

A Sample Page Implementation

In order to make it working, you just need to call RequireSSLAttribute Validate Method. On Page Constructor might be fine :)

[RequireSSL]
public partial class _Default : Page
{
public _Default()
{
RequireSSLAttribute.Validate(this);
}

protected void Page_Load(object sender, EventArgs e)
{
}
}
Source : http://blog.sb2.fr/post/2008/12/20/RequireSSL-Attribute-For-ASPNET.aspx

Tricky Simple File Download Proxy Handler

Today I wanna play a bit with Streams and specially with Response.OutputStream. So I decided to make a Simple File Download Proxy Handler in order to Download Files through an HttpHandler which download Files from Remote Site.

It’s Tricky, and may not be very useful :)

Here is the Code

public class FileProxyHandlerBase : HttpHandlerBase
{
#region Private Properties

private String RemoteUrl { get; set; }
private Uri RemoteUri { get; set; }
private String FileName { get; set; }

#endregion

protected override void Process()
{
if (!String.IsNullOrEmpty(Request.QueryString["url"]))
{
RemoteUrl = Request.QueryString["url"];
}

Uri uri;
if (!Uri.TryCreate(RemoteUrl, UriKind.Absolute, out uri))
{
Response.Write("Unable to Process File");
Response.End();
return;
}
RemoteUri = uri;

if (RemoteUri.Scheme == Uri.UriSchemeFtp)
{
Response.Write("Unable to Process File");
Response.End();
return;
}

int index = RemoteUrl.LastIndexOf("/") + 1;
FileName = RemoteUrl.Substring(index, RemoteUrl.Length - index);

HttpWebRequest _webRequest = WebRequest.Create(RemoteUri) as HttpWebRequest;
Stream ResponseStream = _webRequest.GetResponse().GetResponseStream();

Response.ClearContent();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);

using (BinaryWriter bw = new BinaryWriter(Response.OutputStream))
{
byte[] buffer = new byte[1];
while (ResponseStream.Read(buffer, 0, 1) > 0)
{
bw.Write(buffer);
}
}
Response.End();
}
}

You should use it like that : http://mysite.com/MyHandler.ashx?url=http://www.myRemoteSite.com/MyFile.zip


Source : http://blog.sb2.fr/post/2008/12/21/Tricky-Simple-File-Download-Proxy-Handler.aspx

Handle External Links With Custom Http Handler

In this article I’ll talk about External Links Handling.

We often need to manage more external links particularly in the mail or newsletter. These links must remain Standing, even when changing architecture of the website.

That is why it is important to adopt an external links policy of in a unique manner.

For that we'll use a Http Handler which will allow us to intercept the requested URL and so redirect the user to the proper destination.

more

BlogEngine.NET Backup Manager

BlogEngine.NET Backup Manager

Google Analytics WebControl for ASP.NET

Tonight I’ll provide a Quick Useful WebControl in order to add Google Analytics Feature to your ASP.NET WebSite.

This WebControl allow you to choose between the 2 different Analytics Mode :

  • Analytics GA
  • Analytics Urchin

Here is the Code :

[DefaultProperty("Text")]
[ToolboxData("<{0}:GoogleAnalytics runat=server>")]
public class GoogleAnalytics : Control
{
#region Inner Enum

public enum AnalyticMode
{
Urchin,
GA
}

#endregion

#region Public Properties

public String UACode
{
get { return ViewState["UACode"] as String; }
set { ViewState["UACode"] = value; }
}
public AnalyticMode GMode
{
get { return (AnalyticMode)ViewState["Mode"]; }
set { ViewState["Mode"] = value; }
}

#endregion

#region Protected Overrides Methods

protected override void Render(HtmlTextWriter output)
{
switch (GMode)
{
case AnalyticMode.GA:
output.Write(GetGAString());
break;
case AnalyticMode.Urchin:
output.Write(GetUrchinString());
break;
default:
output.Write(GetGAString());
break;
}
}

#endregion

#region Private Methods

private String GetUrchinString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("");
sb.AppendLine("");
return sb.ToString();
}

private String GetGAString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("");
sb.AppendLine("");
return sb.ToString();
}

#endregion
}

Sample Usage :


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Sb2.Web.Tests._Default" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>title>
head>
<body>
<form id="form1" runat="server">
<div>
<Sb2:GoogleAnalytics ID="analytics" runat="server" GMode="GA" UACode="XXXXX" />
div>
form>
body>
html>


Source : http://blog.sb2.fr/post/2008/12/21/Google-Analytics-WebControl-for-ASPNET.aspx