Sunday, July 11, 2010

fix to login control's behavior on rewrited urls

protected void Application_EndRequest(object sender, EventArgs e)
{
if (Response.StatusCode == 302 && !string.IsNullOrEmpty(Response.RedirectLocation)) //if valid url and with redirect location
{
const string LOGINPAGE = "login.aspx";
string targetLocation = Response.RedirectLocation.ToLower();

//check if user is trying to login from a rewrited page
if ((Request.HttpMethod == Classes.Constants.HTTP_POST) && Request.RawUrl != Request.Url.PathAndQuery)
{
if (targetLocation.Contains(LOGINPAGE)
&& targetLocation.Contains(Classes.Constants.QS_RETURNURL.ToLower()))

//modify redirectlocation's return url with the rewrited url
Response.RedirectLocation = string.Format("{0}?{1}={2}",
VirtualPathUtility.ToAbsolute(Classes.Constants.PAGE_LOGIN),
Classes.Constants.QS_RETURNURL,
Server.UrlEncode(Request.RawUrl) //the rewrited url
);
}
}
}


Share/Save/Bookmark

Monday, January 25, 2010

How to remove the default inline styles of an ASP.Net Calendar control

namespace CustomCalendar
{
///
/// Created by Wilmer F. Pascual
///
public class RafnexCalendar:System.Web.UI.WebControls.Calendar
{
protected override void OnDayRender(System.Web.UI.WebControls.TableCell cell, System.Web.UI.WebControls.CalendarDay day)
{
cell.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.NotSet; //wfp - remove rendering of default inline attribute align='center' (for clean rendering of html)
base.OnDayRender(cell, day);
}

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
//base.Render(writer);
base.Render(new RafnexCalendarTextWriter(writer));
}
}

///
/// Created by Wilmer F. Pascual
///
public class RafnexCalendarTextWriter : System.Web.UI.HtmlTextWriter
{
public RafnexCalendarTextWriter(System.Web.UI.HtmlTextWriter writer)
: base(writer)
{
this.InnerWriter = writer.InnerWriter;
}

public RafnexCalendarTextWriter(System.IO.TextWriter writer)
: base(writer)
{
this.InnerWriter = writer;
}

protected override void AddStyleAttribute(string name, string value, System.Web.UI.HtmlTextWriterStyle key)
{
//remove rendering of inline styles - wfp
//base.AddStyleAttribute(name, value, key);
}


}
}


Share/Save/Bookmark

Thursday, January 21, 2010

Handle empty Repeater data

<asp:Repeater ID="repDeactivatedList" runat="server"
onitemcommand="repDeactivatedList_ItemCommand">
<HeaderTemplate>
<table class="commonTable">
<tr>
<th>...</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td>...</td>
</tr>
</ItemTemplate>

<FooterTemplate>
<tr runat="server" visible='<%# repDeactivatedList.Items.Count == 0 %>'>
<td colspan="5"><asp:Literal ID="Literal1" runat="server" Text="No results"></asp:Literal></td>
</tr>

</table>
</FooterTemplate>
</asp:Repeater>


Share/Save/Bookmark

Tuesday, December 1, 2009

Class for Sending email using Email templates (asynchronously)

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Net.Mail;

namespace Classes.Miscellaneous
{
///
/// Created by Wilmer F. Pascual
///

public class Email
{
#region Properties
public string Subject { get; set; }
public string From { get; set; }
public string To { get; set; }
public string CC { get; set; }
public bool IsBodyHtml { get; set; }
public System.Collections.Generic.Dictionary BodyParameters { get; set; }
public string ErrorMessage { get; private set; }

const string PARAMETER_FORMAT = "<%{0}%>";
const string XML_Default_Sender_Email = "Default_Sender_Email";
const string XML_SMTP_Server = "SMTP_Server";
const string XML_SMTP_Port = "SMTP_Port";
const string XML_SMTP_User = "SMTP_User";
const string XML_SMTP_Password = "SMTP_Password";
const string ERROR_TEMPLATENOTEXIST = "Template does not exists.";
#endregion

public Email(){}

#region Methods
///
/// Adds a parameter name and value to the BodyParameters collection
///

///
///
public void AddBodyParameter(string parameterName, string parameterValue)
{
if (this.BodyParameters == null)
this.BodyParameters = new System.Collections.Generic.Dictionary();

this.BodyParameters.Add(string.Format(PARAMETER_FORMAT, parameterName), parameterValue);
}

///
/// Send email using the specified Email template
///

/// Path to the email template file
///
public bool Send(string templateFilename)
{
if (!System.IO.File.Exists(templateFilename))
{
throw new ArgumentException(ERROR_TEMPLATENOTEXIST, templateFilename);
}

MailDefinition md = new MailDefinition();
md.BodyFileName = templateFilename;
md.Subject = this.Subject;
if (string.IsNullOrEmpty(this.From))
md.From = Setting.GetSetting(XML_Default_Sender_Email).Value;
else
md.From = this.From;
md.CC = this.CC;
md.IsBodyHtml = this.IsBodyHtml;

System.Net.Mail.MailMessage mailMessage;

Control dummyControl = new Control();//the Control owner parameter is required so i just created a dummy - wfp
mailMessage = md.CreateMailMessage(this.To, this.BodyParameters, dummyControl); //pass the parameter-value collection; the CreateMailMessage will automatically replace the parameters with the value we specify - wfp

string serverSetting = Setting.GetSetting(XML_SMTP_Server).Value;
string portSetting = Setting.GetSetting(XML_SMTP_Port).Value;
string userSetting = Setting.GetSetting(XML_SMTP_User).Value;
string passwordSetting = Setting.GetSetting(XML_SMTP_Password).Value;

SmtpClient smtp = new SmtpClient(serverSetting, Convert.ToInt32(portSetting));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential(userSetting, passwordSetting);
smtp.UseDefaultCredentials = false;
smtp.Credentials = cred;

try
{
//smtp.Send(mailMessage); send email synchronously -- wfp

//send email asynchronously -- wfp
SendEmailDelegate dc = new SendEmailDelegate(smtp.Send);
AsyncCallback cb = new AsyncCallback(this.SendEmailCallback);
IAsyncResult ar = dc.BeginInvoke(mailMessage, cb, null);
//

return true;
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
return false;
}
}

#region For Asynchronous Email sending
//delegate for asynchronous sending of email -- wfp
public delegate void SendEmailDelegate(System.Net.Mail.MailMessage mailMessage);

//callback method
public void SendEmailCallback(IAsyncResult ar)
{
SendEmailDelegate del = (SendEmailDelegate)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
try
{
//bool result;
//result = del.EndInvoke(ar);
del.EndInvoke(ar);
//System.Diagnostics.Debug.WriteLine("\nSuccess on Send Email CallBack");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("\nError on Send Email CallBack: " + ex.Message);
}
}
#endregion
#endregion
}
}

Share/Save/Bookmark

Thursday, October 22, 2009

Calling PageMethod using jQuery

a simple example:



html code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function CallPageMethod()
{
var msg = '<%= this.Message %>';

$.ajax({
type: "POST",
url: 'default.aspx/MyPageMethod',
contentType: "application/json; charset=utf-8",
data: "{msg:'" + msg +"'}",
dataType: "json",
success: function(result){alert(result.d);},
error: function(result){alert(result.d);}
});

}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Call Page Method" OnClientClick="CallPageMethod(); return false;" />
<asp:Button ID="Button2" runat="server" Text="Postback" onclick="Button2_Click" />
</form>
</body>
</html>


code-behind:



protected string Message;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Message = "hellooo";
}
}

[System.Web.Services.WebMethod]
public static string MyPageMethod(string msg)
{
return msg;
}

protected void Button2_Click(object sender, EventArgs e)
{

}



Share/Save/Bookmark

Tuesday, October 6, 2009

Httphandler to retrive data and return it in JSON format

using System.Web.Script.Serialization;

///
/// Created by Wilmer F. Pascual
///
public class getdata : IHttpHandler
{
const string JSON_ARRAY = "[{0}]";
const string JSON_RECORD = "{{0}}";
const string JSON_KEYVALUE = "\"{0}\":\"{1}}\"";
const string COMMA = ",";

///
/// Retrieve Subcategories for the specified Category
///
///
void GetSubCategories(HttpContext context)
{
int parentCategoryId = int.Parse(context.Request.QueryString[Classes.Constants.QS_CATID]);
IEnumerable subCats = Classes.SubCategory.GetAll(parentCategoryId);
JavaScriptSerializer jSer = new JavaScriptSerializer();
string jsonData = jSer.Serialize(subCats);

context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(jsonData);
context.Response.End();
}

public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString[Classes.Constants.QS_CATID] != null)
{
GetSubCategories(context);
}
}

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



....
the data return can then be used by jquery (ex. used in cascading dropdown list Category -> Subcategories)

$(document).ready(function()
{
$("#").change(function()
{
$("#").html("");
$("#").attr("disabled", "disabled");
$("#").append($("").val('').html('loading...'));
var catId = $("#").attr("value");
if(isNaN(catId)) return;
$.getJSON('http://?catid=' + catId, function(sucats)
{
$("#").html("");
$.each(sucats, function() {
$("#").append($("").val(this['CategoryId']).html(this['CategoryName']));
});
});
$("#").attr("disabled", "");
})
});


Share/Save/Bookmark

Monday, September 7, 2009

Extending Gridview to implement partial paging



///
/// Extended Gridview that supports Custom Paging w/o using ObjectDataSource
/// - wfp May 30, 2008
///

public class CustomGridView : GridView
{
public CustomGridView() : base() { }

[Browsable(true), Category("RafnexProperties")]
[Description("Set the virtual item count for this gridview")]
[DefaultValue (-1)]
public int VirtualCount
{
get { return ViewState["virtualcount"]==null? -1 : (int)ViewState["virtualcount"]; }
set { ViewState["virtualcount"] = value; }
}

private int CurrentPageIndex
{
get
{
return ViewState["cur_pIndex"] == null ? 0 : (int)ViewState["cur_pIndex"];
}
set
{
ViewState["cur_pIndex"] = value;
}
}

public override object DataSource
{
get
{
return base.DataSource;
}
set
{
base.DataSource = value;
//save current page index, this.PageIndex value will be reset along the way(i dont know which event =P ) so we need to save it to be able to use it on InitializePager - wfp
this.CurrentPageIndex = this.PageIndex;
}
}

protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
{
if (this.AllowPaging)
{
pagedDataSource.AllowCustomPaging = true;
if (this.VirtualCount > -1) pagedDataSource.VirtualCount = this.VirtualCount;
pagedDataSource.CurrentPageIndex = this.CurrentPageIndex;
}

base.InitializePager(row, columnSpan, pagedDataSource);
}
}



Share/Save/Bookmark