2009/10/09

C# - Sys.webforms.pagerequestmanagerparsererrorexception: the message received from the server could not be parsed

Error: Sys.webforms.pagerequestmanagerparsererrorexception: the message received from the server could not be parsed

Problem: if you are using updatepanel (ajax) then you have to follow the list below:

(To start with, don't do anything from the preceding list! Here's a matching list of how to avoid a given error (when possible):

  1. Calls to Response.Write():
    Place an or similar control on your page and set its Text property. The added benefit is that your pages will be valid HTML. When using Response.Write() you typically end up with pages that contain invalid markup.
  2. Response filters:
    The fix might just be to not use the filter. They're not used very often anyway. If possible, filter things at the control level and not at the response level.
  3. HttpModules:
    Same as response filters.
  4. Server trace is enabled:
    Use some other form of tracing, such as writing to a log file, the Windows event log, or a custom mechanism.
  5. Calls to Server.Transfer():
    I'm not really sure why people use Server.Transfer() at all. Perhaps it's a legacy thing from Classic ASP. I'd suggest using Response.Redirect() with query string parameters or cross-page posting.

Another way to avoid the parse error is to do a regular postback instead of an asynchronous postback. For example, if you have a button that absolutely must do a Server.Transfer(), make it do regular postbacks. There are a number of ways of doing this:

  1. The easiest is to simply place the button outside of any UpdatePanels. Unfortunately the layout of your page might not allow for this.
  2. Add a PostBackTrigger to your UpdatePanel that points at the button. This works great if the button is declared statically through markup on the page.
  3. Call ScriptManager.RegisterPostBackControl() and pass in the button in question. This is the best solution for controls that are added dynamically, such as those inside a repeating template.

Enjoy!

2009/10/07

SQL- Split string function

Create this function:
CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
returns @Results TABLE (Items nvarchar(4000))
as
begin
declare @index int
declare @slice nvarchar(4000)

select @index = 1
if @String is null return

while @index != 0

begin
select @index = charindex(@Delimiter,@String)
if @index !=0
select @slice = left(@String,@index - 1)
else
select @slice = @String

insert into @Results(Items) values(@slice)
select @String = right(@String,len(@String) - @index)
if len(@String) = 0 break
end return
end


you can try the line below:

select * from dbo.split('a,b,c,d,e,f,g,h,i,j,k,l', ',')

SQL- clone table instantly (SQL)

Sometimes we want to clone a table. How to do it quick? Look at the code below:

select t.* into [#temp]
from TABLENAME t
where 1 = 0

The above code will create a temp table [#temp] with the same properties of table TABLENAME. Some of you might get confused why there is a line "where 1 = 0" what is that means? Actually this means that we do not want to clone the data, we just want to clone the table. So in here 1 = 0 will always false and so there will be no data insert into the temp table.

Enjoy

2009/10/06

C# - Load Attachment

Sometimes when you load your file, the filename might include some special character. Look at the code below:

HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=" + HttpUtility.UrlEncode(filenameArry[0], System.Text.Encoding.UTF8)));

When the system try to load the file with special character in the filename (like &, ;, etc) then there will be problem while reading it. You have to append the following to avoid the problem:

HttpUtility.UrlEncode(filename)

HttpUtility.Encode can solve the problem.

Enjoy.

2009/09/14

SQL - check if primary key exists in a table

IF EXITS (SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_NAME = '..... your table name ....'
AND TABLE_SCHEMA ='dbo' )
BEGIN

---- Your code here

SQL - create stored procedure if not exists

IF NOT EXISTS(Select * from sysobjects where name = 'usp_UserSproc')
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE usp_UserSproc
(
@ID int = NULL --nullable input
)
AS
BEGIN
-- BLAH BLAH BLAH
END';
END

2009/08/25

MSSQL- use runas to login to sql server with windows authentication

For some situation, you will need to use remote computer to connect to different server and login the sql server by windows authentication. But good news, you can use the following technique so that you can just login to the specific sql server from local machine.

- Open cmd
- Type:
runas /user: domain\loginname "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\SqlWb.exe"

or create a short cut with the following path:
C:\WINNT\system32\runas.exe /user:domain\login "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\SqlWb.exe"

So you save your time by without having to connect to your remote computer ;)

Reporting Services- Thousand separator

With decimal:
Format(First(Fields!IRTotal.Value, "TDec"), "#,###0.00")

Without decimal:
Format(First(Fields!IRTotal.Value, "TDec"), "#,###0")

2009/08/21

Reporting Services- Error [BC30494]

I am working on Report and I got this error:

error [BC30494] Line is too long.

Problem\Solution: If your table is too big will causes this error. There is a simple solution: rename all your text boxes to a short name, for example: textbox1234 - > t1234

If the above solution doesn't help, try to split the table into two.

Enjoy

2009/08/07

SQL- Stored procedure: list out all columns of a table

Sometimes, you need to create a temp table or whatever, you need to list out all the columns. If just only 2 or 3 columns sure that won't bother you, but if the table has 100 columns, its gonna kill you if you have to type everyone of it. So, here is the stored procedure for you. It will list out all columns of a table in one line and separate the columns with comma.


Usage: exec SP_ColName 'TABLENAME'

===
IF EXISTS (SELECT * FROM [sysobjects] WHERE [id] = OBJECT_ID(N'[dbo].[SP_ColName]'))
DROP PROCEDURE [SP_ColName]
GO
-- Usage: SP_ColName
-- It prints out the column names of the given table in one line delimited by ', '
CREATE PROCEDURE [SP_ColName] @TableName sysname
AS
BEGIN
DECLARE @ColumnList nvarchar(max)
DECLARE @ColumnName nvarchar(max)
SET @ColumnList = ''
DECLARE cur CURSOR FOR
SELECT [name] FROM [syscolumns] WHERE [id] = OBJECT_ID(@TableName) ORDER BY [colid]
OPEN cur
DECLARE @OutStr varchar(max)
SELECT @OutStr = ''
PRINT UPPER(@TableName)
FETCH NEXT FROM cur INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @OutStr = @OutStr + @ColumnName + ', '
FETCH NEXT FROM cur INTO @ColumnName
END
IF LEN(@OutStr) >= 2 PRINT LEFT(@OutStr,LEN(@OutStr)-2)
CLOSE cur
DEALLOCATE cur
END
GO

C# Is null or string is empty

I just found that there is a "new" thing to check the string is null or empty (asp.net 2.0)

old way:
if (var == string.Empty && var == null)

new way:
if (String.IsNullOrEmpty(var))

It looks cool right? Enjoy!

2009/08/04

C#- Using Nullable Types

Nullable types can represent all the values of an underlying type, and an additional null value. Nullable types are declared in one of two ways:

System.Nullable variable

-or-C

T? variable

T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.

For an example of when you might use a nullable type, consider how an ordinary Boolean variable can have two values: true and false. There is no value that signifies "undefined". In many programming applications, most notably database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.

This disparity can create extra programming work, with additional variables used to store state information, the use of special values, and so on. The nullable type modifier enables C# to create value-type variables that indicate an undefined value.

Any value type may be used as the basis for a nullable type. For example:

C#
int? i = 10;
double? d1 = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] arr = new int?[10];

SQL- List out all the columns in a table

Assume that you wish to check for rows in a table where all values are NULL. There are many columns in the table and you want to avoid hand coding them. Instead, you can create a script to do the work for you:

Select column_name + ' IS NULL AND'
FROM INFORMATION_SCHEMA.columns
where table_name = 'whatever'

Enjoy! this query is very useful ;)

2009/06/12

Remove Document Map (Report Service)

Recently I am working on MSSQL Reporting Services... when I print my report in excel file, I found something very annoying... a worksheet called "Document Map" automatically generated into the report... damn it... how to remove it!!???

Solution:
Open notepad and drag in your report.rdl file and then look up

2009/05/27

C#- Convert string to int with thousand separator

string sText = "111,111,111";
int i;
i = Int32.Parse(sText, NumberStyles.AllowThousands);

C#- Thousand separator

To add thousand separator to your number, you could do this:

Convert.ToDecimal(yourNumber.Text.ToString()).ToString("N2")
or
Convert.ToDecimal(yourNumber.Text.ToString()).ToString("N4")

where N2 = 2 decimal place and N4 = 4 decimal place.

if you don't want any decimal place you can try this:
Convert.ToInt32(yourNumber.Text.ToString()).ToString("N0")

Get windows login name?

To get windows login name, you can type this in dos prompt:
echo %username%

To get windows login name in sql, you can type this:
exec master..xp_cmdshell 'echo %USERNAME%'

2009/05/22

ASP.NET AJAX 1.0

ASP.NET AJAX is a set of technologies to add AJAX (Asynchronous JavaScript And XML) support to ASP.NET. It consists of a client-side script framework, server controls, and more.

Link: http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en

2009/05/21

Error connecting to undo manager of source file

Problem:
When you compile you see this error msg: "Error connecting to undo manager of source file ..."

Solution:
1) Right click the designer file and select delete.
2) Right click the aspx file and select Convert to Web Application.

Yay!

2009/05/20

DataGrid.DataSource return null?

There will be a time that you want to get the bound datagrid's datasource to work on it. For example: you want to have a button that can add in new row dynamically to the bound datagrid. But when you try to do this: DataTable dt = (DataTable)dg.DataSource, you will then realize that dt returns null.

Solution:
Actually .NET 2.0 would not save the datasource when the datagrid is bound. What you can do is to save the datasource into a view state variable. For example:

When you bind a datagrid, you also need to set viewstate varible to the same source:

dg.DataSource = ds;
ViewState["temp"] = ds;
dg.DataBind();

So, when you want to retrieve the datasource, you can do this:
DataTable dt = (DataTable)ViewState["temp"];

If you want to add a new row, you can do this:
DataTable dt = (DataTable)ViewState["temp"];
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
ViewState["temp"] = dt;
dg.DataSource = dt;
dg.DataBind();

Good Luck!

2009/05/16

C#- Validate before post back?

Recently I am working on SIMS (Safety Information Management System) and encountered a problem. The problem might make me sounds like a newbie but, yes, I am :).

So the problem is:
I have a textbox only accept numbers with no decimal and no letters, and I also set this textbox to auto postback so once the user enter a number and it will calculate the number with a formula.

Solution:
I have a validator with the needed regular expression pointed to that text box, all you have to do is click on the textbox and switch to html view and add in this: CausesValidation = "true", it will then check the textbox value and it must be true before doing the autopostback. Work like a charm ;)