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

Sunday, August 23, 2009

How to search all tables in a SQL Server Database for a specific value

check this site: http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm

Here is the complete stored procedure code:
 CREATE PROC SearchAllTables (  @SearchStr nvarchar(100) ) AS BEGIN  
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN SET @ColumnName = ''
SET @TableName = ( SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY( OBJECT_ID( QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped' ) = 0 )
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName = (
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName )
IF @ColumnName IS NOT NULL BEGIN INSERT INTO #Results
EXEC ( 'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' + ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2 )
END END END SELECT ColumnName, ColumnValue FROM #Results
END


Share/Save/Bookmark

Thursday, July 23, 2009

Download file HttpHandler


public class getfile : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
try
{
int fileId;
int.TryParse(context.Request.QueryString[Timeline.Constants.QUERYSTRING_FILEID], out fileId);
MyFileClass file = new MyFileClass(fileId); //retrieve file info

context.Response.Clear();
context.Response.ContentType = "application/octet-stream";

byte[] fileSize = File.ReadAllBytes(file.PhysicalPath);
context.Response.AddHeader("Content-Length", fileSize.Length.ToString());
fileSize = null;
context.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}", file.Filename));
context.Response.WriteFile(file.PhysicalPath);
context.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
context.Response.Write(ex.Message);
}

context.Response.End();
}

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


Share/Save/Bookmark

Sunday, June 14, 2009

How to get the type of a System.__ComObject in COM Interop

string typename = Microsoft.VisualBasic.Information.TypeName(yourobject);

note: remeber to add the Microsoft.VisualBasic in your reference

Share/Save/Bookmark

Wednesday, June 3, 2009

How to retrieve Membership's PasswordAnswer

in .net's membership framework, as long as the provider's password format is set to "Encrypted" or "Clear" then developers will be able to retrieve and decode the password. that's ok. but, interestingly, membership does not provide a method to retrieve the "Password Answer" (the answer to the security question when resetting a user's password). one thing to note is that, the PasswordAnswer is encoded using the same algorithm used for the password encryption, thus, if we can decrypt the password then we could probably decrypt the PassswordAnswer using the same function that is being used to decrypt the password(i hope i still make sense). with this, a visit to your friendly reflector will show you MembershipProvider's DecryptPassword and UnEncodePassword methods. This will be all you'll be needing to be able to create your own method of retrieving the PasswordAnswer. The trick is to create a class that derives from the MembershipProvider class to be able to use the DecryptPassword(protected) and check out the implementation of the UnEncodePassword to be able to decode the byte[] returned by DecryptPassword. below is a sample implementation:




public class FalseMembershipProvider : MembershipProvider
{
#region Required Override Properties/Methods
...implement required properties/methods here
#endregion

///
/// Retrieves the Password Answer - wfp june 04 2009
///
///
///
public string GetPasswordAnswer(Guid providerUserKey)
{
Microsoft.Practices.EnterpriseLibrary.Data.Database db = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase();
using (System.Data.Common.DbCommand cmd = db.GetSqlStringCommand("SELECT PasswordAnswer FROM aspnet_Membership WHERE UserID=@UserID"))
{
db.AddInParameter(cmd, "@UserId", DbType.Guid, providerUserKey);

object answer = db.ExecuteScalar(cmd);
if (answer != null)
return ProviderDecryptor(answer.ToString());
else
return null;
}
db = null;
}

///
/// Generic Decryptor function. Can be used to decrypt Password and Password Answer.
/// Only works if passwordFormat is set to "Encrypted" - wfp june 04 2009
///
///
///
internal string ProviderDecryptor(string encryptedText)
{
string decrypted = null;

if (!string.IsNullOrEmpty(encryptedText))
{
byte[] encodedbytes = Convert.FromBase64String(encryptedText);
byte[] decryptedbytes = base.DecryptPassword(encodedbytes);

if (decryptedbytes != null)
decrypted = System.Text.Encoding.Unicode.GetString(decryptedbytes, 16, decryptedbytes.Length - 16);
}

return decrypted;
}
}



Share/Save/Bookmark