Monday, July 19, 2010

How to resotre MS SQL backup and fixed user incorect associate to login

When you restore a DB to a new create Database or Users has changed after backup the database,  you may notice that user name in the restored database not correctly associate to user in logins.
the SQL Command as below will restore database name call myDb and fix the User user1 associate to user name in Logins.


-- Full backup database , WITH FORMAT says overwrite the bak file if it is already existed.
BACKUP DATABASE myDb
    TO DISK = 'd:\backup\myDb.bak'
    WITH FORMAT;
GO

-- Restore Sample 1
USE master
RESTORE DATABASE myDb
FROM DISK = 'd:\myDb.bak'
WITH REPLACE
GO


-- Restore Sample 2
-- 1. List File Set position in backup file
RESTORE HEADERONLY
FROM DISK = 'd:\myDb.bak'
GO
-- 2. List Logical Name from particular file set position in backup file
RESTORE FILELISTONLY
FROM DISK = 'd:\myDb.bak'
WITH FILE = 2
GO
-- 3. Restore data from particular file set position and move backup data to specify location
-- 'MyDB' and 'MyDB_log' is Logical name from step 2.
--  MyDB.mdf is data store, MyDB_log.ldf is DB log file
RESTORE DATABASE myDb
FROM DISK = 'd:\myDb.bak'
WITH MOVE 'MyDB' TO 'd:\DB\MyDB.mdf'
,MOVE 'MyDB_log' TO 'D:\DB\MyDB_log.ldf'
,FILE = 2, REPLACE


--
USE myDb

-- the following statement say if login 'test_user' not exist just create it with password.
IF NOT EXISTS(SELECT name FROM master.dbo.syslogins WHERE name = 'test_user')
BEGIN
    CREATE LOGIN test_user WITH PASSWORD = 'Password123', CHECK_POLICY = OFF
END
GO

-- Create new user for login
-- for sql server 2005/2008
USE myDb
CREATE USER user1 FOR LOGIN test_user WITH DEFAULT_SCHEMA = dbo

-- for SQL Server 2000
EXEC sp_adduser 'login1', 'user1'

-----------------------------------------------------------------
-- the Syntax of sp_adduser
sp_adduser [ @loginame = ] 'login' 
    [ , [ @name_in_db = ] 'user' ] 
    [ , [ @grpname = ] 'group' ]

-- Set default schema to user
USE myDb
ALTER USER user1 WITH DEFAULT_SCHEMA = dbo;

-- Add db_owner role to the user
EXEC sp_addrolemember 'db_owner', 'user1'


-- the 'update_one' is the parameter value of @action in sp_change_users_login
-- the 'test_user' is user name in myDb
-- the 'user1' is login name
-- the third parameter password no require if you specific the first param @action='update_one'
EXEC sp_change_users_login 'update_one', 'test_user', 'user1';

------------------------------------------------------------------- the Syntax of sp_change_users_login
sp_change_users_login [ @Action= ] 'action' 
    [ , [ @UserNamePattern= ] 'user' ] 
    [ , [ @LoginName= ] 'login' ] 
    [ , [ @Password= ] 'password' ]
[;]
 
 



-- If you got a error while restore db: Exclusive access could not be obtained because the database is in use.
-- find out which user connecting the db and kill the spid
-- Show all the users connection include spid.
EXEC sp_who
-- Kill the users who is connecting the db, 52 is spid.
KILL 52



-- Change DB Logic Name
-- display current using DB logic name
select * from sysfiles
-- change logic name
ALTER DATABASE MyDB
MODIFY FILE (NAME =  'MyDB_log' , NEWNAME = 'MyDB2_log');




See MSDN
 
  

Sunday, July 11, 2010

How To call a Web service in javascript

By Using jQuery

    var params = "{'id':'123','name':'josh'}";

    $(document).ready(function()
    {
        $.ajax({
            type: "POST",
            url: "/WebService/aspnet_service.asmx/getUserInfoFunc",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg)
            {
                alert(msg.d);
            }
            ,
            error: function(result)
            {
                alert(result.status + ":" + result.statusText);
            }
        });
    });

Microsoft Ajax

<script type="text/javascript" src="/script/MicrosoftAjax.js"></script>





<script type="text/javascript">

    function onclickBtn1()
    {
        var wRequest = new Sys.Net.WebRequest();
        wRequest.set_url("/test.aspx?id=3");
        wRequest.add_completed(
            function(executor, eventArgs)
            {
                alert(executor.get_responseData());
             });
        wRequest.invoke();
    }
</script>

How to request URL with login credential in C#

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Saturday, July 10, 2010

How To Create XML Object in C#




XmlDocument xDoc = new XmlDocument();
XmlElement root = null;
XmlElement node = null;
XmlAttribute att = null;

// Create XML declaration
XmlNode declaration = xDoc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
declaration.Value = "version=\"1.0\" encoding=\"utf-8\"";
xDoc.AppendChild(declaration);


// Create Child Element with two attributes id and name
node = xDoc.CreateElement("node");

att = xDoc.CreateAttribute("id");
att.Value = "100";
node.Attributes.Append(att);

att = xDoc.CreateAttribute("name");
att.Value = "data_100";
node.Attributes.Append(att);

// Create data content which encapesole in <![CDATA[[ ]]> section.
XmlCDataSection CData = xDoc.CreateCDataSection("This text contains some xml escape characters & < > ' \" which encapsolete in CDATA.");

node.AppendChild(CData);

// Create root Element
root = xDoc.CreateElement("root");


root.AppendChild(node);

xDoc.AppendChild(root);



// Get XML string from XmlDocument
string xmlStr = xDoc.outerXml;

the result of xmlStr will be like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node id="100" name="data_100" >
        <![CDATA [This text contains some xml escape characters & < > ' " which encapsolete in CDATA.]]>
    </node>
</root>

Thursday, July 8, 2010

XML Escape Sequences

XML Escape
"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

Wednesday, July 7, 2010

Regex Samples

// Filter images file name
var regExp = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF|.png|.PNG|.bmp|.BMP)$/;


// Check number format in integer and float, the symbol +, - or
// thousandsprate like(123,456,78.001) is no acceptable.
^((((\d+(\.)?)|(\d*\.\d+))(\d+)?))$


// Check XSS Meta-characters insid the input string. This 
// characters and string in the pattern is forbidden in input string.
[\r\n\\'"<>&\u0085]|(?i:\bjavascript|jscript)

Using command line for Windows Disk Defragmenter

Windows Disk Defragmenter
Copyright (c) 2003 Microsoft Corp. and Executive Software International, Inc.
Usage:
defrag <volume> [-a] [-f] [-v] [-?]
  volume  drive letter or mount point (d: or d:\vol\mountpoint)
  -a      Analyze only
  -f      Force defragmentation even if free space is low
  -v      Verbose output
  -?      Display this help text

for example if you want to defrag Dirve D: and analyze onlydefrag D: -a

result is show below:
Windows Disk Defragmenter
Copyright (c) 2003 Microsoft Corp. and Executive Software International, Inc.
Analysis Report
    51.16 GB Total,  14.92 GB (29%) Free,  5% Fragmented (10% file fragmentation)
You do not need to defragment this volume.

Friday, July 2, 2010

How To Handdle XSL output HTML charset

Some times we transfrom xsl to html will get a wrong html chartset.
In C# we usually using TextWriter or XmlTextWriter to output a stream from xsl transformation, but the default encoding of the TextWriter and XmlTextWriter have a potential pitfall makes you difficult to fine out the real reason cause the wrong html charset automatically reander by xsl transform.
By defaul TextWriter and XmlTextWriter using UTF-16 encoding, it cause XSL Trasformation automatically generate html charset to UTF-16, What if you already defined html chartset in your xsl you will find out there a duplicated content-type defined in your output html head like this:
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-16" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        .....
        .....
Solution:
      
      no more best guidance than a real sample code....
XmlDocument xDoc = new XmlDocument();
xDoc.Load(new Uri(Request.Url, xmlUrl).ToString());
XslCompiledTransform xTrans = new XslCompiledTransform();
xTrans.Load(new Uri(Request.Url, xslUrl).ToString());
StringBuilder sb = new StringBuilder();
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
{
    Encoding = Encoding.UTF8
    ,
    // if you don't want any xml declaration output such as <?xml ... ?>
    OmitXmlDeclaration = true    
};
          XmlWriter xWriter = XmlTextWriter.Create(sb, xmlWriterSettings);
          xTrans.Transform(xDoc, null, xWriter);
        
         // get result there
        System.Console.Write(sb.ToString());
       
        xWriter.Close();
        // if you want directly write to response
        XmlTextWriter xTxtWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
        xTxtWriter.Close();