Monday, December 7, 2009

ASP.NET - display records to grid view

Reference:

http://www.codersource.net/asp_net_grid_view_whidbey.aspx

Below is an example of using C#/ASP.NET to display content to a gridview (need to specify the object of "GridView1" in design view of ASP.NET first):

protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}

public void BindData()
{ // local variables
SqlConnection conn = null;
SqlCommand cmd = null;

try
{
conn = new SqlConnection("server=xxx;User ID=xxx;Password=xxx");
conn.Open();

cmd = new SqlCommand("select top(100) xxxx", conn);

SqlDataAdapter mySqlAdapter = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);

GridView1.DataSource = myDataSet;
GridView1.DataBind();

if (conn != null)
{
conn.Close(); conn = null;
}
}
catch (Exception ex)
{
if (conn != null)
{
conn.Close(); conn = null;

strLog = "[ (!!!Fail) Error=" + ex.Message + "]";
Response.Write(strLog);

}
}

Use code as below to add horizontal scrolling


// add code of GridView here


Use code as below to edit content of a row
1. Define functions


2. Function of Edit:

protected void GridView_MatchingServer_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView_MatchingServer.EditIndex = e.NewEditIndex;
BindData();
}

3. Function of Update
Add code as below to retrieve content of field being edited.

GridViewRow row = GridView_MatchingServer.Rows[e.RowIndex];
strMess1 = ((TextBox)(row.Cells[1].Controls[0])).Text; // RecID
strMess2 = ((TextBox)(row.Cells[3].Controls[0])).Text; // content of field

Where Cells[1] and Cells[3] represent the 1st and 3rd columns.

Sunday, December 6, 2009

ASP.NET - save content as ,excel file

Below is an example which indicates how to save content to excel file. It will pop-up a window to ask user to specify proper directory to store the file.

protected void Button1_Click(object sender, EventArgs e)
{
// make sure nothing is in response stream
Response.Clear();
Response.Charset = "";

// set MIME type to be Excel file.
Response.ContentType = "application/vnd.ms-excel";

// add a header to response to force download (specifying filename)
Response.AddHeader("Content-Disposition", "attachment; filename=\"MyFile.xls\"");

// Send the data. Tab delimited, with newlines.
Response.Write("Col1\tCol2\tCol3\tCol4\n");

Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");
Response.Write("Data 1\tData 2\tData 3\tData 4\n");

// Close response stream.
Response.End();
}

Thursday, December 3, 2009

SQL - Encryption / decryption

Today find a web page which provides example about usage of symmetric and asymmetric for SQL encryption:

http://www.mssqltips.com/tip.asp?tip=1886&home

Thursday, November 26, 2009

SQL - lock a record for update

Below is an example of how to lock a record for update operation

strCmd = "select serial_num from DBase..Table with (UPDLOCK) where mobile_num = '' order by serial_num asc";
cmd.CommandText = strCmd;
reader = cmd.ExecuteReader();

if (reader.Read() == true)
{
strResult = reader.GetString(0);
}
reader.Close();

// update content of the record
strCmd = "update DBase..Table set mobile_num='" + strMobile + "', create_timestamp='" + strPresTime + "', SID='" + strSID + "' where serial_num='" + strResult + "'";
cmd.CommandText = strCmd;
cmd.ExecuteNonQuery();

Friday, November 20, 2009

SQL - insert special character

Today I try to insert string with special characters in SQL dbase, below is a possible approach:

insert DBase..tableXXX (title) values (N'电影原生' + char(39) + N'东邪西毒' + char(39) )

It will result in something like: 电影原生'东邪西毒'

Wednesday, November 18, 2009

SharePiont and e-Learning

Find a web page which provide valid information about this.

http://elearningtech.blogspot.com/2008/12/using-sharepoint.html

SQL - collation error

Today I try to use Union to join query result of tables of different SQL server (use linked server) and get the following error message

Cannot resolve the collation conflict between "Chinese_PRC_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the UNION operation.

The solution wil be syntax similar as below

WHERE A.Column COLLATE SQL_Latin1_General_CP1_CI_AS = B.Column
(i.e. to override/convert A.column to proper collation)

SQL - linked server

Today try to use SQL2005 SSMS to create a linked server, below is an URL which provides valid information:

http://blog.miniasp.com/post/2008/07/How-to-setup-Linked-Server-in-SQL-Server-2005.aspx

Note:
1. Simply specify IP address in the field of "Server Name"
2. Select "SQL Server" as "Server Type"
3. Remember to enter login information in the page of "Security" setting.

Access linked server by command as below:

select * from [linked server].dbase.schema.table where ...

Tuesday, November 17, 2009

SQL - injection

Find the following information from Web Site related to SQL injection

 http://support.microsoft.com/kb/954476
 http://msdn.microsoft.com/en-us/library/ms161953(SQL.90).aspx

Monday, November 16, 2009

SQL - access rights

Below is an example of how to set access rights in SQL2005 server. A trigger is created in DBase B which will add/update record in a table of DBase A. Account "developer" has full control of DBase B but only allow to insert/update record in that particular table of DBase A.

Account "developer" is used to create a record in DBase B and the trigger will create related record in DBase A

Steps:
1) Create account "developer" and add it to DBase A. (without set role to db_owner, db_denyreader, db_denywriter, etc)

2) Login SSMS as SA, execute commands as below to grant "developer" to access particular table of DBaseA:

use [DBaseA]
GO
GRANT INSERT ON [dbo].[table_XXX] TO [developer]
GRANT UPDATE ON [dbo].[table_XXX] TO [developer]
GRANT SELECT ON [dbo].[table_XXX] TO [developer]
GO

3) Login SSMS as SA, check access rights by command as below:

USE DBaseA;
EXECUTE AS USER = 'developer';
SELECT *
FROM fn_my_permissions('dbo.table_XXX', 'Object')
ORDER BY subentity_name, permission_name ;
REVERT;
GO

4) Login SSMS as "developer", try to create a record in related table of DBaseB, the trigger will be activated to insert a record in "table_XXX" of DBaseA.

Remark:
**Commands in step-2 will be ignored (and become useless) by SQL Server if role of user is set to "db_denywriter" in step 1.

Reference:
http://www.mssqltips.com/tip.asp?tip=1440

SQL - trigger

[Sample of trigger for "inserted"]

Create trigger MMS_insert_dup on t_mms_mo_mms_send_history for insert
as
begin
declare @TxID bigint
declare @MMSTitle nvarchar(50)
select @TxID=TransactionID,
@MMSTitle = MMSTitle
from inserted
insert XXX..XXX(TransactionID, MMSTitle)
values (@TxID, @MMSTitle)
end


Sample of trigger for "updated" (There is no "Updated" table)
Create trigger MMS_update_dup on t_mms_mo_mms_send_history for update
as
begin
declare @TxID bigint
declare @MMSTitle nvarchar(50)
select @TxID=TransactionID,
@MMSTitle = MMSTitle
from inserted
update XXX..XXX
set
MMSTitle = @MMSTitle
where TransactionID = @TxID
end

Sunday, November 15, 2009

SQL - Shrink file

Below is an example of reduce size of log file:

USE AdventureWorks;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks
SET RECOVERY FULL;
GO

Friday, October 30, 2009

SQL - A simple example of using IN / NOT IN

Below is a simple example of using IN / NOT IN of SQL2005

select TID, MobileNum, create_timestamp, success from XXX..XXX where TID not like 'ZHA%' and mobilenum not in
( select mobile_num as mobilenum from XXX..XXXX
)
order by create_timestamp asc

Tuesday, October 27, 2009

C# - example of time string formatting

Below is two simple example of how to use C# to display date/time in different format:

[Present Time]
strNow = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

[TimeStamp of File]
FileInfo fi = new FileInfo(strPath);
fi.LastWriteTime.ToString("yyyyMMddHHmmss");

Friday, October 23, 2009

SQL 2005 - Usage of recursive query and Union

Below is an example which I implemented in this morning. Need to use the SQL to perform join among three tables

select c.CID, c.event, c.SID, c.TID, c.create_timestamp,

SUBSTRING(d.userid,1,4)+'XXXX'+SUBSTRING(d.userid,len(d.userid)-3,4) as mobile

from

(select a.CID, b.alias as event, a.SID, a.TID, a.create_timestamp

from XXXX..TxEvent as a join XXXX..campaigns as b

on a.success='0' and a.CID=b.campaignid) c

join XXX..MMS_Usage as d on c.SID=d.session_id and d.inbound='0'


union


select a.campaign_id as CID, b.alias as event, a.session_id as SID, a.TID, a.create_timestamp,

SUBSTRING(a.userid,1,4)+'XXXX'+SUBSTRING(a.userid,len(a.userid)-3,4) as mobile

from XXXX..Master_TxEvent as a join XXXX..campaigns as b

on a.state='0' and a.campaign_id=b.campaignid


Sunday, October 11, 2009

SQL - create user account

1. Execute commands as below to create login account
CREATE LOGIN deve1
WITH PASSWORD = 'deve1';
USE dbase_xxx;
CREATE USER deve1 FOR LOGIN deve1;
GO


2. Execute commands as below to assign user account to each database
use dbase_xxyy
exec sp_adduser deve1

3. Execute commands as below change grant / deny access rights to individual account
DENY UPDATE ON dbase_XXX..table_xxx to develop

Monday, September 28, 2009

ASP.NET Web Site Setup

Today I try to setup a ASP.NET web site which was developed by a previous colleagues. After I have finished to prepare all the things (Setup in IIS, registery modification, etc..) according to the description in the setup document, I try to access the site but it reports error message of "failure to load XXX.DLL"

I modify register to enable "Fusion!EnableLog" and make sure the DLL has been stored in both of "\bin" of the web site and subdirectory of "Temparoary ASP.NET Files" but the problem is still there.

Finally I modify "security setting" of "Temporary ASP.NET Files" and allow "Internet Access Account" to access the folder. The problem is solved after I have added the access the folder. BTW, not certain whether it will cause security loophole or not.



Thursday, September 24, 2009

Knowledge Management (R&D validation)

Today the company which I am working with talks about how to validate (or capitalize) the technical capability of the company. This cause me to remember what I have learned in the courses related to Knowledge Management in the past few years.

Based on what I learned, the following can be used to measure (capitalize) asset of a company:

1) Human Asset
This is related to how experience the staffs are, whether they are knowledgeable and stable or not.

2) IT Asset
This is related to IT infra-structrue of the company, how IT is used to improve efficiency of the company
(e.g. Bugs Tracking, Source Control, email system, IT for project management, etc)

3) Work procedure
This is related to whether there is proper procedure so that the staffs can re-utilize their knowledge to develop a new project (to keep the quality, to shorten the development period), to based on existing knowledge to create new knowledge, etc.

4) Social Asset
Related to relationship with existing and potential customer.

5) Patent
Number of patent the company have and how the patent can help the company to safeguide its business/product.

SQL2005 (Data Migration)

Today I try to setup a new SQL2005 server which will be used to replace the development server of SQL2008. Orginial I think I can simply detect the SQL2008 server and then use the "attach" method to utilize those database files from SQL2008 to SQL2005. However, the process fails due to reason of compatibility.

At the end I require to do the following for each database:

1) Generate script from the orginial SQL 2008 Server (include schema of Tables, SP, Views,etc)

2) Create database in the SQL2005 Server and then execute those scripts in Query Window of SSMS for those database

3) Use SSMS export function to copy records from SQL2008 to SQL2005.

However, while I try to do step 3 I get the below error message which cause me fail to do the data migration. Have try to change "regional setting" ot the two servers and also, change collation of the two SQL servers but still fail.

[...More than one code page (1252 and 936)...]

It is because the collation used in the orginial SQL2008 server is "SQL_Latin1_General_CP1_C1_AS" but the collation of the new SQL2005 server is "Chinese_PRC_C1_A1", the problem seems can't be solved by changing collation of those database of the SQL2008 server.

Finally I find that the solution is to change the collation of the new database of SQL2005 server to "SQL_Latin1_General_CP1_C1_AS" while the database is created.

Wednesday, September 23, 2009

Remove SQL2005 and Reporting Service

These few days I try to remove a previous installed SQL2005 (with reporting service) and then re-install a new instance of SQL2005 (with reporting service) again in the same server. Below are several items which needed to noted for proper installation:

1. Check "Services" by using features of "Administration", need to stop all services of "SQL XXX"

2. Use "Add/Remove" function to remove SQL2005 from the Server

3. Within IIS, delete those entries related to "Reporting Service" in the application pool

4. Check sub-directories of "C:\program Files\Microsft SQL Server", either rename or delete those directores related to "Reporting Service".

Can find more information from this URL: http://support.microsoft.com/kb/909967/en-us

T-SQL (string manipulation)

Below is example of using string manipulation function of T-SQL to mask off part of content of a string

SUBSTRING(ui.userid,1,4)+'XXXX'+SUBSTRING(ui.userid,len(ui.userid)-3,4) as userid

userid will become "123XXXX456"

Tuesday, September 22, 2009

SQL2005 setup

Today I try to install a new instance of SQL2005 server to a Windows2003 Server which is previous part of a cluster machine. (Previouly another instance of SQL2005 was installed to the server in a cluster configuration but no longer accessible).


It always display below error message which causes me failure to install a new instance:


SQL Server Setup was unable add user XXX/administrator to local group SQLServer2005SQLBrowserUser$YYY


Finally I find that the solution is to update login name of related SQL Services found in "Administration --> Services function" of Windows2003 Server. Right click the entry and change the login name from "XXX/administrator" to "YYY/administrator" where XXX is machine name of previous cluster machine and YYY is local machine name.

Wednesday, February 25, 2009

Refresh DropDownList in server by using ASP.NET

Today I study how to refresh content of a DropDownList (based on user selection of content of another DropDownList). It seems quite easy (no need to use AJAX nor UpdatePanel) and let's summarize procedure as below:

1. Define several DropDownList boxes in a web form, remember to define those control as server control (runat="server").

2. Set "AutoPostBack=true" of those DropDownList boxes.

3. Once content of the ListBox is changed, it will trigger functions of "Page_Load()" and "xxxList_SelectedIndexChanged()".

4. Remember to use "if (!Page.IsPostBack) { ... }" to protect the logic in Page_Load( ).

5. Add logic in "xxxList_SelectedIndexChanged" to refresh content of other DropDownList Box.

Tuesday, February 24, 2009

Usage of User Control for ASP.NET

Today I try something of creating an "User Control" for an ASP.NET based web site, and pass parameter to the control. Below is a summary

1. For an ASP.NET project, select to add “user control” as shown below


2. For the ASCX file, add resource to UI of the control as below


3. For the .CS file related to the user control add proper logic as shown below


4. Drag and drop the “User Control” to a web form which will use the control. Related code as below will be generated automatically
@ Register Src="ctrlCalendar.ascx" TagName="ctrlCalendar" TagPrefix="uc1"

<%@ Register Src="ctrlCalendar.ascx" TagName="ctrlCalendar" TagPrefix="uc1" %>5. Do the following if wants to pass parameter from a web form to the control:
..Add variable such as “public string ButName;” in the control
..Add command as below in the Page_Load of the web form:
CtrlCalendar1.ButName = "From";
CtrlCalendar2.ButName = "To";
..Add command as below in the Page_Load of the user control:
this.Button_1.Value = ButName;

Saturday, February 14, 2009

Sample to use CLR for SQL2005

Below is a summary of steps to create CRL for SQL2005
1. Create a project using Visual Studio 2005 (Create DLL with “User Defined Function” (DLL: SQL_SimpleCLR.dll))
2. Click to add “User-defined function”
3. Build and copy the DLL under “..\binn” of SQL Server
[Sample source code]
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString DispTime(SqlString HashString)
{
// Put your code here
string hashedPasswordString = null;
hashedPasswordString = "Hello";

//return new SqlString("Hello");
return new SqlString(hashedPasswordString);
}
};

4. Execute the following command to register addembly as shown in the following diagram

CREATE ASSEMBLY MyLib FROM
'd:\Microsoft SQL Server\MSSQL.1\MSSQL\binn\SQL_SimpleCLR.dll'
WITH PERMISSION_SET = SAFE

5. Execute the following command to create function associated with the API provided in the class of the assembly (DLL)
CREATE FUNCTION dbo.DispTime
(
@result nvarchar(4000) = ''
)
RETURNS nvarchar(4000)
EXTERNAL NAME [MyLib].[UserDefinedFunctions].[DispTime]


6. Execute the following command to test the function:
sp_configure 'clr enabled', 1
go
reconfigure
go

SELECT dbo.DispTime('mypassword')

Create accounts and assign rights to access SQL

Below is a summary of steps to create account and assign rights to access database (more than 1 database) of SQL Server 2005.

1. Execute commands as below to create login account
CREATE LOGIN deve1
WITH PASSWORD = 'deve1';
USE name_of_dbase1;
CREATE USER deve1 FOR LOGIN deve1;
GO

2. Execute commands as below to assign user account to each database
use name_of_dbase2
exec sp_adduser deve1

use name_of_dbase3

exec sp_adduser deve1

3. Right click name of database, select permission and click to select options as below:

Saturday, January 31, 2009

Knowledge Management

Regarding KM (Knowledge Management), there are three areas to be considered:

  • IT related (Infrsatructure and Tools): A study of how to use tools such as Portal, Search Engine, Collaboration tools, etc to retend and retrieve knowledge
  • Human Related (Personal Management, Human Capital)
  • Organization Related (Organization Learning)

It just like a 3-dimensional space that each area contains items to be studied.