RSS

Monthly Archives: April 2012

How to: Create a Windows Communication Foundation Client


See follow link:

How to: Create a Windows Communication Foundation Client

Note: SvcUtil.exe can be found at C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin.

 
Leave a comment

Posted by on 24/04/2012 in WCF

 

Lập trình generic (template) với C#


Bài viết sưu tầm tại: http://my.opera.com/minhbt/blog/show.dml/3010009
Trong C# hỗ trợ lập trình generic khá mạnh, nếu bạn biết sử dụng lập trình generic thì bạn tiết kiệm được khá khá thời gian lập trình, và tính tái sử dụng code rất cao, vẫn đảm bảo tính trong sáng khi code mà performance của chương trình hầu như ko giảm. Trong C#, bạn có thể lập trình Generic với Class, Struct, Function.
1. Lập trình Generic với Class.
Chắc bạn đã quá quen thuộc với khai báo
List<string> nameList = new List<string>();
Đây là khai báo sử dụng một danh sách các string, trong đó lớp List<T> là một lớp được lập trình dạng generic, bạn có thể dễ dàng khai báo một danh sách các đối tượng thuộc kiểu bất kì. Rõ ràng tính tái sử dụng lớp List<T> cao hơn rất nhiều lớp List ko có generic.
Áp dụng phương pháp cách định nghĩa lớp này, chúng ta có thể tạo những lớp generic khác nhau. Tớ ví dụ ở đây lớp Couple<T, E> được sử dụng rất nhiều khi tớ viết code.

    public class Couple<T, E>
    {
        public T elementA;
        public E elementB;
        public Couple(T inA, E inB)
        {
            elementA = inA;
            elementB = inB;
        }
    }

Lớp này được dùng khi bạn muốn có một đối tượng tạm thời chỉ gồm hai phần tử, bình thường bạn phải định nghĩa một class mới để phù hợp với kiểu của 2 phần tử nói trên, nhưng với Couple<T, E> bạn ko cần thiết phải làm điều đó.
Ví dụ bạn muốn một đối tượng gồm 2 phần tử string và một số integer, bạn khai báo như sau :

Couple<string, int> couple = new Couple<string, int>(”Age”, 29);

Khi đó couple.elementA sẽ có kiểu string nhận giá trị “Age” và couple.elementB sẽ có kiểu int nhận giá trị 29.
Cũng với lớp này, bạn có thể tạo một lớp danh sách các bộ đôi string và int như sau :


List<Couple<string, int>> listCouple = new List<Couple<string, int>> ();

Và khi đó List[5].elementA sẽ có kiểu string, trả về giá trị string của Couple có index 5 trong List nói trên.
Hoặc khi hàm bạn viết cần phải trả về 2 đối tượng, thì việc sử dụng Couple<T, E> cũng là một cách tốt, trong sáng và vẫn rất OPP:D.
Chú ý, bạn có thể bổ sung thêm Property cho lớp Couple<T, E> nếu thấy cần thiết (khi lập trình aspx chẳng hạn), thêm như bình thường.

    public class Couple<T, E>
    {
        public T elementA;
        public E elementB;
        public Couple(T inA, E inB)
        {
            elementA = inA;
            elementB = inB;
        }
        public T ElementA
        {
            get{return elementA;}
            set{elementA = value;}
        }
    }

Tương tự như vậy, bạn có thể khai báo thêm các lớp Generic Triple<T, E, F> (bộ ba) và Quad<T, E, F, V>

    public class Triple<T, E, F>
    {
        public T elementA;
        public E elementB;
        public F elementC;
        public Triple(T inA, E inB, F inC)
        {
            elementA = inA;
            elementB = inB;
            elementC = inC;
        }
    }

    public class Quad<T, E, F, G>
    {
        public T elementA;
        public E elementB;
        public F elementC;
        public G elementD;
        public Quad(T inA, E inB, F inC, G inD)
        {
            elementA = inA;
            elementB = inB;
            elementC = inC;
            elementD = inD;
        }
    }

Bạn có thể tận dụng 3 lớp nói trên trong các dự án C# của bạn, sẽ tiết kiệm nhiều thời gian đấy. Chú ý phải định nghĩa thêm nhé, đây không phải là lớp sẵn có của .Net.

2. Lập trình Generic với Struct.
Nhìn chung, ko có ji khác biệt trong cách lập trình Generic Struct và Generic Class, ví dụ sau là Struct
Couple<T, E>:

    public struct Couple<T, E>
    {
        public T elementA;
        public E elementB;
        public Couple(T inA, E inB)
        {
            elementA = inA;
            elementB = inB;
        }
        public T ElementA
        {
            get{return elementA;}
            set{elementA = value;}
        }
    }

Nói chung, nếu ko phải quá bận tâm vào performance, thì hầu như ta có thể dùng Class thay vì dùng Struct trong lập trình C#. Tớ sẽ phân biệt sự khác nhau, và ưu nhược điểm của việc sử dụng Struct trong C# trong một bài viết khác.

3. Lập trình Generic Function.
C# cũng cho phép lập trình Generic với hàm, sau đây là một ví dụ :

    public string toString<T>(List<Couple<string, T>> list)
    {
        string result = "";
        foreach (Couple<string, T> pair in list){
            string tmp = pair.elementA + " : " + pair.elementB.ToString();
            result += tmp + '\n';
        }
        return result;
    }

Đây là ví dụ một hàm trả về một string tương ứng với nội dung của một danh sách bộ đôi của một String và một loại object nào đó (string, int, …) sẽ được thay thể trong mỗi trường hợp call cụ thể. Có lẽ đây ko phải là ví dụ hay cho Generic Function. Nhưng nhờ lập trình Generic Function, tớ đã có thể viết hàm BinarySearch rất tổng quát, có thể được tái sử dụng trong rất nhiều dự án khác, tiết kiệm rất nhiều thời gian. Tớ sẽ giới thiệu hàm này trong bài nói về Sắp xếp và Tìm kiếm sau.

Bài viết này có tham khảo tại: bnok.vn

 
Leave a comment

Posted by on 24/04/2012 in DotNet

 

WCF service failed to start: AddressAccessDeniedException


One of the major changes in Windows Vista / Windows 7 security is that most people are no longer going to be running with Administrator privileges by default like they were doing on earlier platforms. This impacts your ability to run HTTP web services because listening at a particular HTTP address is a restricted operation. By default, every HTTP path is reserved for use by the system administrator. Your services will fail to start with an AddressAccessDeniedException if you aren’t running the service from an elevated account. On Windows Vista/Windows 7, httpcfg.exe is no longer included and instead there’s a new command set available through netsh.exe.

I’m going to walk through delegating part of the HTTP namespace to get a web service working that wants to listen at http://localhost:8000/. Since I’m not running as the Administrator when debugging in Visual Studio, the service fails to start when I run it.

HTTP could not register URL http://+:8000/. Your process does not have access rights to
this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

The plus sign in the URL just means that there’s a wildcard being applied to the hostname. I’ll have another article that talks about wildcards in more detail. To fix this problem, I first need to start a command prompt using “Run as administrator” so that I have elevated privileges. Then, I can use netsh.exe to give some of the Administrator’s HTTP namespace to my user account. You can look at the existing HTTP namespace delegations by using “netsh http show urlacl“. There should be several namespaces set up by default, including the default one that WCF uses for temporary addresses as an example.

Reserved URL : http://+:80/Temporary_Listen_Addresses/
User: \Everyone
Listen: Yes
Delegate: No
SDDL: D:(A;;GX;;;WD)

Now, I open command prompt as administrator privileges and use follow command:
netsh http add urlacl url=http://+:8000/ user=MYMACHINE\UserName
to assign some of the HTTP namespace to my user account. You can get the syntax for all of these commands by running “netsh http” without any arguments. Note that I’ve matched the URL in this command to the URL that appeared in the error message. The wildcarding is important for getting the right reservation and you’ll continue to be denied access if your reservation covers less than your service’s attempted registration. Going back to Visual Studio, my service now starts up and runs as expected.

 
Leave a comment

Posted by on 23/04/2012 in WCF

 

Parser Error: Direct Dependencies and The Limit Has Been Exceeded


Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: The page ‘/sites/blah/_catalogs/masterpage/blah.master’ allows a limit of 11 direct dependencies, and that limit has been exceeded.

During deploying user control on the master page, in one of our project I used to get the above error. Generally such kind of exception is thrown will rendering a page. The reason behind this is the number of controls allowed on the page to render exceeds the limit specified in the web.config file

The solution of this problem can be fixed in two different ways.
Solution 1: Modify the control dependencies in the web.config file.
Solution 2: Optimize the usage of controls on the master page; this can be done either by deleting the duplicates, or integrating 2 or more control in one control.
The solution 2 is a complex one, where as the solution 1 is a simple modification as show below

Search for the following tag in the web config file and chage the DirectFileDependecies

<- SafeMode MaxControls=”200″ CallStack=”true” DirectFileDependencies=”20″ TotalFileDependencies=”50″ AllowPageLevelTrace=”false”>
By default the DirectFileDependecies will be set to 10, you can change to any limit u require.

 
Leave a comment

Posted by on 12/04/2012 in SharePoint

 

How to Restore SQL Server Suspect Database


Introduction

If your project’s database is in suspect mode, then no transaction will take place until and unless you repair your database. That causes a show stopper for your up and running application. Here, you will find a way to get out of this.
Background

Your Database is in Suspect Mode. I guess, you haven’t experienced this problem till now. But, if it comes to you and if the database is LIVE, then it’s time to read this article to get out of this tension.
Using the Code

If you find your database in Suspect mode, then please keep your nerve strong. Just proceed step by step what I am written below. I think you will get out of this trouble. SQL Server 2005 introduced a new DB Status called Emergency. This mode can change the DB from Suspect mode to Emergency mode, so that you can retrieve the data in read only mode. The steps are… After executing the script given below, you will get back your database in operational mode. Actually I have tried with two of my existing live systems and found no data loss.

Note: Obviously there are two more options available. Run REPAIR_ALLOW_DATA_LOSS to ensure the database is returned to a structurally and transitionally consistent state. Here are a few things to bear in mind about emergency mode repair: it’s a one-way operation. Anything it does cannot be rolled back or undone. If this worries you (if someone ever got into that state, then surely don’t have the healthy concern about data that they should have in the first place) then make a copy of the damaged database before you run emergency mode repair.
As it’s a one-way operation, you cannot wrap it in an explicit user-transaction.
It’s the only repair option available in emergency mode – if you try to use REPAIR_REBUILD, then it won’t work.
Collapse | Copy Code

EXEC sp_resetstatus 'yourDBname';
ALTER DATABASE yourDBname SET EMERGENCY
DBCC checkdb('yourDBname')
ALTER DATABASE yourDBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB ('yourDBname', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE yourDBname SET MULTI_USER

Source: http://www.codeproject.com/Articles/20333/How-to-Restore-SQL-Server-2005-Suspect-Database

 
Leave a comment

Posted by on 12/04/2012 in SQL Server