2011年4月8日星期五

virtual path to absolute path

Converts a virtual path to an application absolute path.
VirtualPathUtility.ToAbsolute("~/media/images/" + panel.Id)

use MapPath to resolve virtual paths and physical paths.
HttpContext.Current.Server.MapPath(@"xml/content/" + lXmlFile);
HttpContext.Current.Request.MapPath(@"xml/content/" + lXmlFile);

2011年3月23日星期三

Call web service in jquery

[WebMethod(true)]
public void UpdateTestTime(int timeLeft)
{
CLBWTTestContainer wtc = Session[CLBWTConstants.SESSION_VAR_TESTCONTAINER] as CLBWTTestContainer;
if (wtc != null)
{
wtc.TimeLeft = timeLeft;
log.Debug("timeleft=" + wtc.TimeLeft);
}
}

asp:ScriptManager ID="siteScriptManager" runat="server" EnablePartialRendering="true">







/asp:ScriptManager>

span id="timerLabel" class="timer_label">/span>

div id="expiredDialog" title="<%= GetGlobalResourceObject("CommonTerms", "Message")%>">


div class="buttons_cntr_right">


/div>
/div>

script type="text/javascript">
$(document).ready(function() {
$("#").countdown({ until: +<%=timeLeft%>, compact: true, format: 'MS', onTick: updateTestTime, onExpiry: expiredHandler,
layout: '{mnn}{sep}{snn}'});

// Dialog
$('#expiredDialog').dialog({
autoOpen: false,
modal: true,
close: function(event, ui) {
location.href = "/Secure/Testing.aspx";
}
});


});

function updateTestTime(periods) {
//last 60 seconds
if (periods[4] == 0 && periods[5] == 0 && periods[6] <= 59 )
{
$('#timerLabel').addClass("timer_label_last60");
}
//every 5 seconds call to server to update server time
if (periods[6] % 5 == 0) {
var timeLeftInSeconds = (periods[5] * 60) + periods[6];
CLBOA.Web.TestEngine.Services.WSTestEngine.UpdateTestTime(timeLeftInSeconds);
}
}

function expiredHandler() {
$('#expiredDialog').dialog('open');
}

/script>

Attributes

[DataObjectMethod(DataObjectMethodType.Update, false)]
[DataObjectMethod(DataObjectMethodType.Delete, false)]
[DataObjectMethod(DataObjectMethodType.Insert, false)]

FTP code

public bool HasFile(string sourceFileName)
{
bool ret = false;
try
{
Uri target = new Uri(CLBBLHelpers.AppendPathNames(Server, sourceFileName));
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = new NetworkCredential(Username, Password);
WebResponse response = request.GetResponse();
ret = true;
}
catch (WebException e)
{
Uri target = new Uri(CLBBLHelpers.AppendPathNames(Server, sourceFileName));
log.Warn("Error checking if ftp server has a file: username=" + Username + ";password=" + Password + ";source file=" + target.ToString(), e);
}
return ret;
}



public bool UploadFile(string targetFile, string sourceFile)
{
bool ret = false;
try
{
log.Debug("source file=" + sourceFile);
// Get the object used to communicate with the server.
Uri target = new Uri(CLBBLHelpers.AppendPathNames(Server, targetFile));
log.Debug("target file=" + target.ToString());
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Username, Password);

FileStream fs = File.OpenRead(sourceFile);
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, fileContents.Length);
fs.Close();
Stream rs = request.GetRequestStream();
rs.Write(fileContents, 0, fileContents.Length);
rs.Close();
FtpWebResponse resp = (FtpWebResponse)request.GetResponse();
log.Info("File upload complete, status " + resp.StatusDescription);
ret = true;
}
catch (WebException e)
{
Uri target = new Uri(CLBBLHelpers.AppendPathNames(Server, targetFile));
log.Error("Error uploading file: username=" + Username + "; password=" + Password + "; target file=" + target.ToString(), e);
}
return ret;
}

2011年3月21日星期一

Set No Cache

Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();

Event and Delegate

public delegate void SubmitAnswerHandler(object sender);
public event SubmitAnswerHandler Submited;

...

if (Submited != null)
Submited(this);

...



clbwtAbortReason.Submited += new CLBOA.Web.TestEngine.controls.CLBWTucAbortReasonPopup.SubmitAnswerHandler(clbwtAbortReason_Submited);

change something in runtime

1. Load control in runtime
ucReport = (CLBUCUserSurveyReport)Page.LoadControl("~/Reporting/Controls/CLBUCUserSurveyReport.ascx");
phReport.Controls.Add(ucReport);

2. Set CSS in runtime
if (Message != null)
{
Message.CssClass = css;
Message.Text = msg;
}

3. _pTreeView.Attributes.Add("onclick", "OnTreeClick(event)");

4. Show or hide something in page
<%
if (CLBOA.Web.Admin.CLBWAUtils.HasAccess((int)CLBOA.Web.Admin.CLBWAAccessibleType.BANKS))
{
%>

5. link href="<%= CLBOA.Web.Admin.CLBWAUtils.GetAppPath(this.Page) + "/js/jquery-tooltip/jquery.tooltip.css"%>" rel="stylesheet" type="text/css" />

public static string GetAppPath(System.Web.UI.Page curPage)
{
string apppath = curPage.Request.ApplicationPath;
return apppath == "/" ? "" : apppath;
}

6. HttpContext.Current.Request.Url.Host

7. IList al = _aService.GetAccessiblesForParentList((string.IsNullOrEmpty(pNode.Value) ? new Nullable() : int.Parse(pNode.Value)), ApplicationName);

8.
public static void OpenNewPageWindow(System.Web.UI.Page curPage, string strPage, int width, int height)
{
//Open a new window and load this page can now access the stored DataSet.
string sScript = " ";
ScriptManager.RegisterStartupScript(curPage, curPage.GetType(), "new_window_script", sScript, false);
}

public static void OpenNewPageWindow(System.Web.UI.Page curPage, string strPage)
{
OpenNewPageWindow(curPage, strPage, 600, 800);
}

9.
CLBOA.Utils.initButtonHovers = function() {
//hover states on the static widgets
$(".fg-button, .fg-button-w-icon").hover(
function() { $(this).addClass('ui-state-hover'); },
function() { $(this).removeClass('ui-state-hover'); }
);
}

protected override void OnLoad(EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "initButtonHovers", "CLBOA.Utils.initButtonHovers();", true);
base.OnLoad(e);
}

10.
a. A user control has a iFrame, in its iFrame, it loads MediaContainer to play video.
mediaFrame.Attributes["src"] = "/MediaContainer.aspx?mediasource=" + mediaLink + "&mediaframeid=" + mediaFrame.ClientID;

b. This is MediaContainer page
asp:ScriptManager ID="ScriptManager1" runat="server">
/asp:ScriptManager>
script type="text/javascript">
function setParentWindowSize(frameid, width, height) {
parentFrame = window.top.document.getElementById(frameid);
if (parentFrame) {
parentFrame.height = height;
parentFrame.width = width;
}
}
/script>
asp:MediaPlayer ID="MediaPlayer1" runat="server" AutoPlay="true" Windowless="true"
/asp:MediaPlayer>

c. This is MediaContainer code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int defaultMediaWidth = 500;
string mediaSource = Request.QueryString["mediasource"];
int mediaHeight = string.IsNullOrEmpty(Request.QueryString["mediaheight"]) ? 0 : int.Parse(Request.QueryString["mediaheight"]);
int mediaWidth = string.IsNullOrEmpty(Request.QueryString["mediawidth"]) ? 0 : int.Parse(Request.QueryString["mediawidth"]);
string mediaFrameId = Request.QueryString["mediaframeid"];
if (mediaSource != null)
{
log.Debug("mediaSource=" + mediaSource);
MediaPlayer1.MediaSource = mediaSource;
MediaPlayer1.Width = mediaWidth > 0 ? mediaWidth : defaultMediaWidth;
MediaPlayer1.Height = mediaHeight > 0 ? mediaHeight : (int)(0.75 * defaultMediaWidth);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "setParentWindowSize", "setParentWindowSize('" + mediaFrameId + "','" + MediaPlayer1.Width + "','" + MediaPlayer1.Height + "');", true);
}
}
}

11.


protected void clbwtConfirm_Confirmed(object sender)
{
clbwtAbortReason.ShowQuestion();
}

In AbortReason page
PLLCustom:CLBInlineScript ID="test" runat="server">
script type="text/javascript">

CLBOA.Utils.ProcessDialog<%=this.ClientID%> = function() {
var dlg = $("#dialog_container<%=this.ClientID%>").dialog({ modal: true });
dlg.parent().appendTo(jQuery("form:first"));
}

/script>


div id="dialog_container<%=this.ClientID%>" title="<%= QuestionMessageHeader %>"
style="display: none">
...
/div>

In AbortReason code behind:

public void ShowQuestion()
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "CLBOA.Utils.ProcessDialog", "CLBOA.Utils.ProcessDialog" + this.ClientID + "();", true);
}

12. Use Control.RenderControl(HtmlTextWriter) Method to create page content based on user contorl template:
//Loading usercontrol template...
uscSlider = (ASP.slider)Page.LoadControl(@"~/controls/templates/slider.ascx");
//Filling usercontrol property...
uscSlider.Slider = (SliderVO)HttpContext.Current.Items["PCF.Slider"];
lXhtml = new StringBuilder();
aTextWriter = new StringWriter();
aHtmlTextWriter = new HtmlTextWriter(aTextWriter);
uscRotator.RenderControl(aHtmlTextWriter);
lXhtml.Append(aTextWriter.ToString());
ltrContentHomepage.Text = lXhtml.ToString();

In page:
asp:Literal ID="ltrContentHomepage" runat="server" EnableViewState="false">

javascript jQuery code

1. _pTreeView.Attributes.Add("onclick", "OnTreeClick(event)");

2.
CLBOA.Utils.processClientConfirmation = function(confirmText, postbackLinkRef) {
if (typeof (CLBOA.Utils.getCustomClientConfirmation) == 'function') {
CLBOA.Utils.getCustomClientConfirmation(confirmText, postbackLinkRef);
}
else {
return confirm(confirmText);
}
return false;
}


CLBOA.Utils.getCustomClientConfirmation = function(confirmText, postbackValue) {
if ($('#dialog').length > 0) {

$('#dialog').dialog('option', 'title', 'Confirmation');
$('#dialog').text(confirmText);
$('#dialog').dialog('option', 'buttons', { "OK": function() { $(this).dialog("close"); eval(postbackValue); }, "Cancel": function() { $(this).dialog("close"); } });
$('#dialog').dialog("open");
}
else {
alert("Require object with id 'dialog'");
}
}



// find the row's delete button
LinkButton deleteButton = CLBPCHelpers.FindCommandButton(e.Row, "delete");
if (deleteButton != null)
{
// add the confirm call with our text
deleteButton.OnClientClick = "return CLBOA.Utils.processClientConfirmation(\"" + this.ConfirmDeleteText + "\",\"" + Page.ClientScript.GetPostBackEventReference(deleteButton, String.Empty) + "\")";

}

GetPostBackEventReference(Control, String)
Returns a string that can be used in a client event to cause postback to the server. The reference string is defined by the specified control that handles the postback and a string argument of additional event information.

///
/// Loop through each of the grid row cells to find the appropriate command button
///

///
/// ie. "delete", "select", etc...
///
public static LinkButton FindCommandButton(GridViewRow row, string commandString)
{
// default to null
LinkButton button = null;

if (!string.IsNullOrEmpty(commandString))
{
// get the first cell
foreach (TableCell commandCell in row.Cells)
{
button = FindThatCommandButton(commandCell, commandString) as LinkButton;
if (button != null)
break;
}
}
return button;
}

private static Control FindThatCommandButton(Control currentControl, string commandString)
{
Control button = null;
button = (from LinkButton b in currentControl.Controls.OfType(LinkButton>()
where b.CommandName.ToLower() == commandString.ToLower()
select b).FirstOrDefault();
if (button == null && currentControl.Controls.Count > 0)
{
foreach (Control c in currentControl.Controls)
{
//call recursive
button = FindThatCommandButton(c, commandString);
if (button != null)
break;
}
}
return button;
}


3.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using System.IO;

namespace CLBOA.PLL.Custom
{
///
/// To solve issue with inline javascripts that are used with the UpdatePanel.
/// Contents created/injected by the updatepanel (ie. Ajax contents) cannot access the javascripts
/// that is embedded in the page unless they are wrapped by this control.
///

public class CLBInlineScript : Control
{
protected override void Render(HtmlTextWriter writer)
{
ScriptManager sm = ScriptManager.GetCurrent(Page);
if (sm.IsInAsyncPostBack)
{
StringBuilder sb = new StringBuilder();
base.Render(new HtmlTextWriter(new StringWriter(sb)));
string script = sb.ToString();
ScriptManager.RegisterStartupScript(this, typeof(CLBInlineScript), UniqueID, script, false);
}
else
{
base.Render(writer);
}
}
}
}

%@ Register assembly="CLBOA.PLL.Custom" namespace="CLBOA.PLL.Custom" tagprefix="PLLCustom" %>

PLLCustom:CLBInlineScript ID="inlineScript" runat="server">
script type="text/javascript">
$(document).ready(function() {
$("#<%= pnlPrivileges.ClientID %>").panel({ collapsible: false });
});
/script>
/PLLCustom:CLBInlineScript>

4.
ajaxTK:ToolkitScriptManager ID="tksm" runat="server" OnAsyncPostBackError="tksm_AsyncPostBackError" >
Scripts>
asp:ScriptReference Path="~/js/jquery/1.4.2/jquery-1.4.2.min.js" />
asp:ScriptReference Path="~/js/jquery.cookie.js" />
/Scripts>
/ajaxTK:ToolkitScriptManager>

5.
使用ScriptManager.RegisterStartupScript方法可注册一个每次发生异步回发时都将包括的启动脚本块。 若要为 UpdatePanel 控件内的某个控件注册一个脚本块,以便仅在更新 UpdatePanel 控件时才注册该脚本块,请使用该方法的 RegisterStartupScript(Control, Type, String, String, Boolean) 重载。

如果要注册与部分页面更新无关的启动脚本,并且只想在初始页面呈现期间注册一次该脚本,请使用 ClientScriptManager 类的 RegisterStartupScript 方法。 可以从页面的 ClientScript 属性获取对 ClientScriptManager 对象的引用。

if (!ClientScript.IsClientScriptBlockRegistered("exampleScript"))
ClientScript.RegisterStartupScript(this.GetType(), "exampleScript","

");


6.
Script to hide status bar messages in IE
onmouseover="window.status=''; return true;" OnClientClick="location.href='/Login.aspx'"

7.
//right click disabled
$(document).bind("contextmenu",function(e){
return false;
});

$(document).bind("keydown", function(e) {
//backspace
if (e.keyCode == 8) return false;
});

8.

In basepage, define ExecuteClientScript method:
public void ExecuteClientScript(StringBuilder scriptJs)
{
ClientScript.RegisterStartupScript(typeof(string), "script", scriptJs.ToString(), true);
}


From code behind:
ExecuteClientScript(new StringBuilder(" CloseMapOverlay(); "));

In page:
script type="text/javascript">
function CloseMapOverlay()
{
parent.$.fancybox.close();
}
/script>

9. From javacript, run sever side event handler:
$("li.dropdown ul li a").live("click", function ()
{
$('#hdnProvince').val($(this).attr("id"));
$('#btnSaveCookie').click(); //here call server side event handler
return false;
});

This is the button that has onclick event



10. Call webservice from javascript

Method RegisterFirstAccess is defined in Default.aspx.cs.

[WebMethod()]
public static void RegisterFirstAccess()
{
//Registering the first access to call the map overlay
HttpContext.Current.Session.Add("FirstAccess", "false");
}

From jquery:

if (IsFirstAccess == 'true') {

//registering the first access with user session...
$.ajax({
type: "POST",
url: "Default.aspx/RegisterFirstAccess",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

2011年1月21日星期五

Sort gridview that bind to a generic List in code behind

protected void clbgvTestForms_Sorting(object sender, GridViewSortEventArgs e)
{
IList tl = null;
if (IsPilot)
tl = TService.GetPilotTestList();
else
tl = TService.GetOperationalTestList();

if (tl != null)
{
var param = Expression.Parameter(typeof(tblTest), e.SortExpression);
var sortExpression = Expression.Lambda < Func < tblTest, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);

// If we're toggling sort on the same column, we simply toggle the direction. Otherwise, ASC it is.
// e.SortDirection is useless and unreliable (only works with SQL data source).
if (_sortBy == e.SortExpression)
_sortDirection = _sortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
else
_sortDirection = SortDirection.Ascending;

_sortBy = e.SortExpression;

if (_sortDirection == SortDirection.Ascending)
{
clbgvTestForms.DataSource = tl.AsQueryable().OrderBy(sortExpression);
}
else
{
clbgvTestForms.DataSource = tl.AsQueryable().OrderByDescending(sortExpression);
}
clbgvTestForms.DataBind();
}

}

_sortBy and _sortDirection are parameters which value is saved in viewstate.