Microsoft Study Bible

November 27, 2009

How to achieve Ajax in Asp.net 2.0?

 
ASP.NET 2.0 Client side Callbacks Framework
ASP.NET 2.0 has been released for a long time .The 2.0 framework has a great number of new features, one of which is Client side Callback. It can retrieve page values and populate them to an already-generated page with out reconstructing page. This makes it possible to use on a page with out going through the entire post back cycle; that means you can update your pages without completely redrawing the page. Client side Callback allows us to call the server-side methods without postback, which is consistent with the features of AJAX. However, AJAX can custom the method called that Callback of .NET 2.0 can not .The prerequisite to use Client Side Callback is to achieve System.Web.UI.IcallbackEventHandler interfaces, which contain two methods.
//call this method when the client callback
public void RaiseCallbackEvent(String eventArgument)
//After implementation of RaiseCallbackEvent , Call this method whose return value

// is sent back to the client side. 
  public string GetCallbackResult()

  
for example:
  .cs:
  String cbReference = Page.ClientScript.GetCallbackEventReference(
  this,”arg”, “ReceiveServerData”, “context”);
  String callbackScript;
  callbackScript = “function CallServer(arg, context)” + “{ ” + cbReference + “} ;”;
  Page.ClientScript.RegisterClientScriptBlock(
  this.GetType(),”CallServer”, callbackScript, true);
  javascript:

AJAX Introduction

AJAX is not a new programming language, but a new technique for creating better, faster, and more interactive web applications. With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. The AJAX technique makes Internet applications smaller, faster and more user-friendly.
AJAX mechanism
When we used XmlHttp to achieve no-fresh page, we used XmlHttp to request a hidden page and Asp/Asp.Net of HttpHandler’own. Although in Ajax, we also request a hidden page ,the difference of the page of HttpHandler is achieved by ourselves.
Build your own AJAX:
1. Firstly we need to achieve a HttpHandler to respond the client’s request:
If we want to achieve self-define HttpHandler we should achieve IHttpHandler interfaces ,which contain a property and a method :
bool IHttpHandler.IsReusable
  void IHttpHandler.ProcessRequest(HttpContext context)
  Example:
  bool IHttpHandler.IsReusable
  {
  get { return true; }
  }
  void IHttpHandler.ProcessRequest(HttpContext context)
  {
  context.Response.Clear(); // To obtain the method called
  string methodName = context.Request.QueryString["me"];
  //To obtain the assembly information
  //Czhenq.AJAX.Class1.Dencode is self-defining string coding
string AssemblyName = Czhenq.AJAX.Class1.Dencode(context.Request.QueryString["as"]);
  //acquire the parameters of the method
  string Arguments = context.Request.QueryString["ar"]; //start to call the method
  Type type = Type.GetType(AssemblyName);
  MethodInfo method = type.GetMethod(methodName,
  BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
  if (method != null)
  {
  //The parameters are separated by “,”
  string[] args = Arguments.Split(”,”.ToCharArray());
  ParameterInfo[] paras = method.GetParameters();
  object[] argument = new object[paras.Length];
  for (int i = 0; i < argument.Length; i++)
  {
  if (i < args.Length) {
  //As the parameters passed from XmlHttp are all string type, all of them are must converted .
//Here just convert the parameters into Int32
  argument[i] = Convert.ToInt32(args[i]);
  }
  }
  object value = method.Invoke(Activator.CreateInstance(type, true), argument);
  if (value != null) context.Response.Write(value.ToString());
  else context.Response.Write(”error”);
  }
  //end of process
  context.Response.End();

2. Client side Javascript code:
function CallMethod(AssemblyName,MethodName,Argus)
  {
  var args = “”;
  for(var i=0;i)
  args += Argus[i] + “,”;
  if(args.length>0) args = args.substr(0,args.length-1);
  var xmlhttp = new ActiveXObject(’Microsoft.XMLHTTP’);
  url = “AJAX/AJAX.czhenq?as=” + AssemblyName + “&me=” + MethodName +”&ar=”+ args;
  xmlhttp.open(”POST”,url,false);
  xmlhttp.send();
  alert(xmlhttp.responseText);
  }

3.We have achieved a simple AJAX framework. Now we need to write a piece of code to test it.
Use your own AJAX
1. New a website, and use your written HttpHandler, and register your HttpHandler on Web.config to explain that those requests will use your written Handler. The following description is all of request ending up with “czq” will use “Czhenq.HttpHandlerFactory” to deal with them.
</type=”Czhenq.HttpHandlerFactory, Czhenq.AJAX”/>

2. Add a web page and copy the script to the page and add a method you want to call .
private string Add(int i, int j)
  { return TextBox1.Text;  }
3. Place a HieddenField control on the page which is named AssemblyName.And add the following code in the Page_Load.
string assemblyName = Czhenq.AJAX.Class1.Encode(
  typeof(_Default).AssemblyQualifiedName);
  AssemblyName.Value = assemblyName;

4. Add the following script on the page
 var assemblyName = document.getElementById(”AssemblyName”);
  var argus = new Array();
  argus.push(”100″);
  argus.push(”200″);
  CallMethod(assemblyName,”Add”,argus)

Summarization
AJAX is not a new technology, which is just combination of some technology existed. In my opinion, AJAX is to encapsulate XmlHttp called by JavaScript, which just change the ways to write the code.

Encode and Decode:
public static string Encode(string value)
  {
  byte[] bytes = ASCIIEncoding.ASCII.GetBytes(value);
  return Convert.ToBase64String(bytes);
  }
  public static string Dencode(string value)
  {
  byte[] bytes = Convert.FromBase64String(value);
  return ASCIIEncoding.ASCII.GetString(bytes);
  }

November 26, 2009

Microsoft open source the .Net Micro Framework

At PDC in Los Angeles, Microsoft announced that we are open sourcing the product and making it available under the Apache 2.0 license open source community which is already being used by the community within the embedded space. They also will create a community to help shape the future of the products.

However, the programmers in the embedded space could not too be happy. Because the complete code have not been provided .For example, can not be freed the TCP/IP protocol stack and Cryptography library of the third part EBSNET. In May, Microsoft announced that they would embrace open-source to make some of platforms as the projects supported by the society.

More detailed information, you can see

Microsoft to Open Source the .NET Micro Framework.

November 25, 2009

SQL Server Compact on Windows 7 x 64-bit

Today, when I use Visual Studio 2008 to develop a simple SQL Server Compact 3.1 application on Windows x64 platform, throws the following exception:

Message: “An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0×8007000B)”

StockTrace:

  StockTrace

  System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0×8007000B)

  at System.Data.SqlServerCe.NativeMethods.CreateErrorInstance(IntPtr& pError)

  at System.Data.SqlServerCe.SqlCeCommand..ctor()

at WindowsApplication1.NorthwindDataSetTableAdapters.EmployeesTableAdapter.InitAdapter() in D:\Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\NorthwindDataSet.Designer.cs:line 6400

at WindowsApplication1.NorthwindDataSetTableAdapters.EmployeesTableAdapter.get_Adapter() in D:\Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\NorthwindDataSet.Designer.cs:line 6324

at WindowsApplication1.NorthwindDataSetTableAdapters.EmployeesTableAdapter.Fill(EmployeesDataTable dataTable) in D:\Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\NorthwindDataSet.Designer.cs:line 6607

at WindowsApplication1.Form1.Form1_Load(Object sender, EventArgs e) in D:\Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\Form1.cs:line 29 

at System.Windows.Forms.Form.OnLoad(EventArgs e)

at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)

at System.Windows.Forms.Control.CreateControl()

at System.Windows.Forms.Control.WmShowWindow(Message& m)

at System.Windows.Forms.Control.WndProc(Message& m)

at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Think it carefully .SQL Server Compact 3.5 SP1 just can support Win7 x 64 platform, SQL Server Compact 3.1 and 3.5 should run only through WOW64 mode .WOW64 is an Emulation Layer which allow 32-bit applications run on 64-bit platform. This seems that the 32-bit applications run on the 32-bit platform.

That problem is familiar on the internet .Generally speaking ,the answer is to install 64-edition SQL Server Compact 3.5 SP1.However ,what I need to resolve is SQL Server Compact 3.1 .What should we do ?

It is very simple. “Any CPU” is the default target platform Visual Studio 2005/2008 creates the project on. we just change it to be “x86”.So,the complied program will run through WOW64 mode.

November 19, 2009

Encapsulate if/else, switch/case and While

This article will discuss how to use extension method to encapsulate if/else,swith/case and while. Through these extensions the written code will seldom use curly brackets. What about this extension, maybe you have better advice .Please let me know.
Proclamation: This article just wanted to express a thought. And the code provided only an example, which can be tested successfully ,but imperfect.
Firstly, let us see if/else, and switch/case, both of which in the code are used as branched structure. Here, we encapsulate them into an “If “extension:

public static T If<T>(this T t, Predicate<T> predicate, Action<T> action) where T: class

        {

            if(t == null) throw new ArgumentNullException();

            if (predicate(t)) action(t);

            return t;

        }

See the following code to call, which will generate a people instance:

public static void Test1()

        {

           //General Code

            People people1 = new People { Name = “ldp615″, IsHungry = true, IsThirsty = true, IsTired = true };

            if (people1.IsHungry) people1.Eat();

            if (people1.IsThirsty) people1.Drink();

            if (people1.IsTired) people1.Rest();

            people1.Work();

            //Use extension method

            People people2 = new People { Name = “ldp615″, IsHungry = true, IsThirsty = true, IsTired = true }

                .If(p => p.IsHungry, p => p.Eat())

                .If(p => p.IsThirsty, p => p.Drink())

                .If(p => p.IsTired, p => p.Rest());

            people2.Work();

        }

We used Lambda expression in the If extension code .If the preceding “p=>p” can be moved ,it will be better.
The Class People is as follows:

public static void Test1()

        {

            //General code

            People people1 = new People { Name = “ldp615″, IsHungry = true, IsThirsty = true, IsTired = true };

           if (people1.IsHungry) people1.Eat();

            if (people1.IsThirsty) people1.Drink();

            if (people1.IsTired) people1.Rest();

            people1.Work();

            // /Use extension method

            People people2 = new People { Name = “ldp615″, IsHungry = true, IsThirsty = true, IsTired = true }

                .If(p => p.IsHungry, p => p.Eat())

                .If(p => p.IsThirsty, p => p.Drink())

                .If(p => p.IsTired, p => p.Rest());

            people2.Work();

        }

For the reference type, we can use Action, and also use chain programming mode to string several If. However, for a value type, we can use Func to return a new value every time.

public static T If<T>(this T t, Predicate<T> predicate, Func<T, T> func) where T : struct

        {

            return predicate(t) ? func(t) : t;

        }

It is necessary to modify the code called.

public static void Test2()

        {

            // /Use extension method

            int int0 = -121;

            int int1 = int0.If(i => i < 0, i => -i)

                .If(i => i > 100, i => i - 100)

                .If(i => i % 2 == 1, i => i - 1);

            // General code

            int int3 = -121;

            if (int3 < 0) int3 = -int3;

            if (int3 > 100) int3 -= 100;

            if (int3 % 2 == 1) int3–;

        }

The extension of the reference type and value type have been completed .Now ,we can use string to test it :

public static void Test3()

        {

            //Transform the mailbox into a home page .

            string email = “ldp615@163.com”;

            string page = email.If(s => s.Contains(“@”), s => s.Substring(0, s.IndexOf(“@”)))

                .If(s =>! s.StartsWith(“www.”), s => s = “www.” + s)

                .If(s =>! s.EndsWith(“.com”), s => s += “.com”);

        }

But the compilation can not be passed, and prompt an error.
This error looks strange .We have written two extensions, one is for value type, other is for reference type. But the Class string can not be passed here.
However, we can write specifically an extension for string to resolve this problem. The code is as follows:

public static string If(this string s, Predicate<string> predicate, Func<string, string> func)

        {

            return predicate(s) ? func(s) : s;

        }

From the above code, we find that there is a priority in the extension method: on the same class, we can do the extension for several times. When there is the same extension, equivalent parameters (the same number and sequence), and the priority of the non generic extension is higher than generic extension.
Let us see a swith code, which is very long-winded. In order to elicit extension, we had to write the following code:

public static void Test4()
        {

            string englishName = “apple”;

            string Name = string.Empty;

            switch (englishName)

            {

                case “apple”:

                    Name = “Apple”;

                    return;

                case “orange”:

                    Name = “Orange”;

                    return;

                case “banana”:

                    Name = “Banana”;

                    return;

                case “pear”:

                    Name = “Pear”;

                    break;

                default:

                    Name = “unknown”;

                    break;

            }

            Console.WriteLine(chineseName);

        }

We use extension method to complete this way:

public static  TOutput Switch<TOutput, TInput>(this TInput input, IEnumerable<TInput> inputSource, IEnumerable<TOutput> outputSource, TOutput defaultOutput)

        {

            IEnumerator<TInput> inputIterator = inputSource.GetEnumerator();

            IEnumerator<TOutput> outputIterator = outputSource.GetEnumerator();

            TOutput result = defaultOutput;

            while (inputIterator.MoveNext())

            {

                if (outputIterator.MoveNext())

                {

                    if (input.Equals(inputIterator.Current))

                    {

                        result = outputIterator.Current;

                        break;

                    }

               }

                else break;

            }

            return result;

        }

The Test5 is used to call:

public static void Test5()

        {

            string englishName = “apple”;

            string Name = englishName.Switch(

                new string[] { “apple”, “orange”, “banana”, “pear” },

                new string[] { “Apple”, “Orange”, “Banana”, “Pear” },

                “unknown”

                );

            Console.WriteLine(Name);

        }

It was simple and clear.
Finally, we’ll encapsulate the extension on while.

public static void While<T>(this T t,  Predicate<T> predicate, Action<T> action) where T: class
        {

            while (predicate(t)) action(t);

        }

Calling code:

public static void Test6()

        {

            People people = new People { Name = “Wretch” };

            people.While(

                p => p.WorkCount < 7,

                p => p.Work()

                    );

            people.Rest();

        }

In this while extension, we only perform an Action, which is not good to improve:

public static void While<T>(this T t, Predicate<T> predicate, params Action<T>[] actions) where T : class

        {

            while (predicate(t))

            {

                foreach (var action in actions)

                    action(t);

            }

        }

Call again; we can perform multiple operations in the loop:

public static void Test7()

        {

            People people = new People { Name = “Wretch” };

            people.While(

                p => p.WorkCount < 7,

                p => p.Work(),

                p => p.Eat(),

                p => p.Drink(),

                p => p.Rest()

                    );

            people.Rest();

        }

Of course ,the previous If extension also can be like this .But here we just write one :

public static T If<T>(this T t, Predicate<T> predicate, params Action<T>[] actions) where T : class

        {

            if (t == null) throw new ArgumentNullException();

            if (predicate(t))

            {

                foreach (var action in actions)

                    action(t);

            }

            return t;

        }

If you don’t want to use params, you need to display a statement about a set of Action.

November 18, 2009

Windows Mobile Development in VS 2010

Firstly, let us talk about what we can get benefit when we develop WM application by VS 2010.Of course, we had to talk about the Windows 7’s official sale and Visual Studio 2010 on-line, both of which belong to a series of products released by Microsoft. These new products will have high levels of integration and closer mutual support. For a developer, Development of uniform standards will bring not only convenience, but also high efficiency.
Take “Hello World” as an example. We just need to change PSTE of the application under Win32 edition as LPSTR, the program can be compiled and on.
Code:

#include <windows.h>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,

                   LPTSTR lpCmdLine, int nShowCmd)

{

     MessageBox(NULL, TEXT(“Hello, Windows Mobile!”), TEXT(“HelloMsg”), 0);

     return 0;

}

From this, we can find that Windows Mobile development is the same as the general Windows program development. We can get a handle on it without hard learning process. And we can use our familiar language.
With intelligence handset more and more popular and coupled with the arrival of 3G area, the demand to write the mobile applications will increase much.
Now, let us see a code in windows mobile by using c# to achieve cmnet link:

public bool Connectcmnetmethod(Guid destGuid, bool exclusive, bool mode)

        {

            {

                connInfo.cbSize = (uint)Marshal.SizeOf(connInfo);

                connInfo.dwParams = 0×1;//CONNMGR_PARAM_GUIDDESTNET;

                connInfo.dwPriority = 0×08000;

                connInfo.dwFlags = 0×1 | 0×2 | 0×4 | 0×8;//0;

                connInfo.bExclusive = 0;// exclusive;

                connInfo.bDisabled = 0;// false;

                connInfo.guidDestNet = destGuid;

                connInfo.hWnd = this.Handle;

                if (mode == true)

                {

                    result = ConnMgrEstablishConnectionSync(ref connInfo, ref hConnection, 10000, out dwStatus);

                    if (result != 0) MessageBox.Show(result.ToString(“X”), dwStatus.ToString(“X”));

                    return result == 0;

                }

                return false;

            }

        }

        public struct CONNMGR_CONNECTIONINFO

        {

            public uint cbSize;

            public uint dwParams;

            public uint dwFlags;

            public uint dwPriority;

            public int bExclusive;

            public int bDisabled;

            public Guid guidDestNet;

            public IntPtr hWnd;

            public uint uMsg;

            public uint lParam;

            public uint ulMaxCost;

            public uint ulMinRcvBw;

            public uint ulMaxConnLatency;

        }

        [DllImport("cellcore.dll", EntryPoint = "ConnMgrEstablishConnectionSync", SetLastError = true)]

        internal static extern int ConnMgrEstablishConnectionSync(ref CONNMGR_CONNECTIONINFO pConnInfo, ref IntPtr phConnection, int dwTimeout, out int dwStatus);

        [DllImport("cellcore.dll", EntryPoint = "ConnMgrEstablishConnection", SetLastError = true)]

        internal static extern int ConnMgrEstablishConnection(ref CONNMGR_CONNECTIONINFO pConnInfo, ref IntPtr phConnection);

        [DllImport("cellcore.dll", EntryPoint = "ConnMgrReleaseConnection", SetLastError = true)]

        internal static extern int ConnMgrReleaseConnection(IntPtr hConnection, int lCache);

        [DllImport("coredll.dll")]

        private static extern int CloseHandle(IntPtr hObject);

        [DllImport("Coredll.dll", EntryPoint = "GetLastError", SetLastError = true)]

        internal static extern int GetLastError();

private void menuItem1_Click(object sender, EventArgs e)

        {

            MessageBox.Show(Connect(new Guid(“7022E968-5A97-4051-BC1C-C578E2FBA5D9″), false, true).ToString());

        }

Under Visual Studio 2010, it is very easy to write the simple, stable, efficient procedure. However, there are some problems .For example, the mobile have great resource consumption, and need to install the mobile version of the Framework program. The market share of the windows mobile is low, and there won’t be much demand to write the program in the short time.

November 16, 2009

Return absolute path of ReturnUrl during Authentication

In Asp.net mvc, we just need to mark a [authorization] on the “Action” or “Controller” required to be authenticated during authentication. When the users did not login in ,it will return the result “ActionResult is HttpUnauthorizedResult”.

public class HttpUnauthorizedResult : ActionResult {
    
public override void
ExecuteResult(ControllerContext context) {
            
if (context == null
) {
                
throw new ArgumentNullException(“context”
);
            }
            
// 401 is the HTTP status code for unauthorized access - setting this
            // will cause the active authentication module to execute its default
            // unauthorized handler
            context.HttpContext.Response.StatusCode = 401
;
        }
    }

From the source code of HttpUnauthorizedResult ,we can get to know that it is very easy or simple to execute HttpUnauthorizedResult .We just set the current HttpContext.Response of the status code as “401”,which will activate authentication module to execute unauthorized handler by default .In other words , It will jump to the logging page ,but the address of the default ReturnURL parameter is relative ,which obviously can’t meet my needs when implementing SSO under different domains .
The resolution is to inherit the feature AuthorizeAttribute and rewrite the OnAuthorization method.

 

 public class ClientAuthorizeAttribute : AuthorizeAttribute
    {
        
public override void
OnAuthorization(AuthorizationContext filterContext)
        {
            
base
.OnAuthorization(filterContext);
            
if (filterContext.Result is
HttpUnauthorizedResult)
            {
                filterContext.Result =
new
RedirectResult(
                    
string
.Concat(FormsAuthentication.LoginUrl,
                                
“?ReturnUrl=”
,
                                 filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsoluteUri)));
            }
          
        }
    }

 It is just ok when we used the method we just mark the self-defining ClientAuthorizeAttribute on “Action” or “Controller” which are required to be authenticated .For example:

[HandleError]
    [ClientAuthorize(Roles =
"Admin"
)]
    
public class
AdminController : Controller
    {
        
//
        // GET: /Admin/

        
public ActionResult Index()
        {
            
return
View();
        }
    }

November 13, 2009

Achieve interaction between Silverlight and database

For security reasons, Silverlight often was not allowed to access the database directly. But there are many ways to make Silverlight access the database indirectly. Today, we’ll talk about three ways of them: 1.RESTful API, 2.use JavaScript to access the database under Silverlight. 3. Use .NET Web service template –Silverlight—enabled. This article will introduce the latter two ways.
1.Use JavaScript to achieve the interaction between Silverlight and Database.
Under the Silverlight event handler, we can make it by adding the following simple JavaScript code, callWebService of which is JavaScript function.

protected void btnSubmit(object sender,EventArgs e)
{
System.Windows.Browser.HtmlPage.Window.Invoke(”callWebService”,
null
);
}

We can get some information on the call of JavaScript.
By ScriptServiceAttribute we can add the following codes:

[ScriptService]
public class UserValidationService: System.Web.Services.WebService
{
    [WebMethod]
    public bool ValidateUserName(string strInput)
    {
        
return !GetUserByUserName(strInput);
//If user exists return false indicates the name is no longer availabe.

    }
    private bool GetUserByUserName(string strUserName)
    {
         bool blnIsUserExists = false;        
        
//Call database API to see if the username is availabe, set blnIsUserExists to true if exists.
         return
blnIsUserExists;
    }
}

 

Then, add ScriptMananger Control through the page.

<asp:ScriptManager runat=”server” ID=”scriptManagerId”>
                
<Services>
                    
<asp:ServiceReference  Path=”UserValidationService.asmx” />
                
</Services>
</asp:ScriptManager>

 call Webservice as the same as calling the local function of JavaScript

<script type=”text/javascript”>
function
validateUserName()
{
  
var

userName = document.getElementById(”txtUserName”).value;
UserValidationService.ValidateUserName(userName,showValidateResult,validateUserNameError);
}
function validateUserNameError(result)
{
    
//Do nothing if any error, ideally, we should log this error to database.

}
function showValidateResult(result)
{
//Since it is only a boolean value, no need to get result.d, if result contains .net object,
// use result.length and result.d to retrieve the object.
    if
(!result)
    {    
        
//Not available
    }else

    {
        
//Username is still available
    }
}
</script>

 

 2.Use Silverlight-enabled Webservice to achieve the interaction between Silverlight and database.

Firstly, Create a Silverlight-enabled Webservice through the template, and then add the database and other server-related into the service .The next step is to add and reference this service into the Silverlight application. Finally use the following code to call webservice in Silverlight application.

using

MySilver.MyService;
……
…..
private void btnSend_Click(object sender, RoutedEventArgs e)
{
        
if
(!String.IsNullOrEmpty(txtMessage.Text.Trim()))
         {
               lstHisotryMessage.Items.Add(
“Gene: “
+ txtMessage.Text.Trim());
               GeneMessage message =
new
GeneMessage();
               message.Body = txtMessage.Text.Trim();
               MyServiceclient =
new
MyService();
             client.SendMessageCompleted +=
new
EventHandler<SendMessageCompletedEventArgs>(client_SendMessageCompleted);
               client.SendMessageAsync(message);
         }
        
else

         {
               MessageBox.Show(
“You cannot send empty message!”

);
         }
}
protected void client_SendMessageCompleted(object sender, SendMessageCompletedEventArgs e)
{
         txtMessage.Text = e.Result.MessageID.ToString();
}

 

 

 

 

 

 

November 12, 2009

The improvement of VS 2010 and .NET 4.0 code Intellisense

The improvement of VS 2010 and .NET 4.0 code Intellisense
Today ,we will talk about the a small but really nice improvement to VS 2010 code intelligent hints with VS 2010 that better filter type and complete the member code ,which will make you more easily find and use APIs when writing code.
Code Intellisense with VS 2008
To show how improve code Intelisense of VS 2010, let us look at a example in VS 2008 where we want to write some code to enable an editing scenario with a GridView control. Maybe we start to type”GridView1.Edit”to bring up intellisense to see what Edit members there are in this control. It will bring up the intellisense drop-down box which move the current location into the members whose initial letters are “Edit”:

11

It was OK if we would like to use the initial letters of the method/property/event that are “Edit”. However, if the initial letters of the “Edit ” members we are looking for are other words such as “RowEditing” event or “SetEditRow()” helper method, this will can not be helpful for us .We have to either manually scroll up and down looking for the other edit members, or pull up the object browser or help system to find them.
Code Intellisense with VS 2010
Now,let us try out the above example in Visual Studio 2010。When we start to type “GridView1.Edit”, we’ll find that the EditIndex property is still highlighted by default. But the intellisense list has also been filtered so that it enables you to quickly locate all other members that have the word “Edit” anywhere in them:

21
This allows us to quickly see all of the edit related methods/properties/events and more quickly find what we are looking for.
Searching for Keywords
This new intellisense filtering feature of VS 2010 is useful for searching for any member – regardless of what word it starts with.  For example, if we want to enable paging on a datagrid and can’t remember how to-do it, we could just type “GridView1.Paging” and it would automatically filter out everything but members that have the word paging.  Notice below how no members on the GridView class actually start with the word “Paging” – but I am still finding the two members that do have paging in them later in their names.

31

Searching for Types
This new intellisense filtering capability of VS 2010 is also useful for quickly finding classes and types. For example, when we type “List” to declare a variable, the editor will provide automatic filtering to show all types that have the word “List” somewhere in them (including IList<> and SortedList<> – which do not start with List):
41

This makes it much easier to find type names you can’t entirely remember – without having to resort to searching through the object browser and/or using help documentation.
Pascal Case Intellisense
The .NET Framework naming guidelines specify that type and member names should be “Pascal Cased” by default.  This means that each word in a type or member should start with a capitalized letter (for example: PageIndexChanged). 
VS 2010’s intellisense filtering support now enables you to take advantage of this to quickly find and filter methods based on their pascal naming pattern.  For example, if we typed “GridView1.PIC” VS 2010 would filter to show us the members that have PIC in their name, as well as those members which have a pascal cased name where the word segments start with that letter sequence:

51

Notice above how PIC caused both “PageIndexChanged” and “PageIndexChanging” to show up.  This saves us a few keystrokes when resolving either member or type names.
Summary
I think you’ll find that the new intellisense filtering approach in VS 2010 makes it easier to quickly find and use classes and members when writing code.  You can take advantage of it with both VB and C#.
Hope this helps
This is from http://weblogs.asp.net/scottgu/archive/2009/10/22/vs-2010-code-intellisense-improvements-vs-2010-and-net-4-0-series.aspx

November 10, 2009

C#.NET String encryption and decryption process

Yesterday My friend the headquarter do Security Review over my sites .When he saw many of the connection strings were not be encrypted, he blamed me .So ,today ,I shared the string encryption and decryption process used with us to help those who need it .The encryption is to use 3DES and the key is to use MD5 HashThe strength should meet the common require. Besides, the code is few and very useful.

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace NOP.Security
{
    public class Encrypt
    {
        public static string DecryptString(string strText, string key)
        {
            byte[] buffer = new MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(key));
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
            provider.Key = buffer;
            provider.Mode = CipherMode.ECB;
            byte[] inputBuffer = Convert.FromBase64String(strText);
            return Encoding.ASCII.GetString(provider.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length));
        }

        public static string DecryptUTF8String(string strText, string key)
        {
            byte[] buffer = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(key));
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
            provider.Key = buffer;
            provider.Mode = CipherMode.ECB;
            byte[] inputBuffer = Convert.FromBase64String(strText);
            return Encoding.UTF8.GetString(provider.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length));
        }

        public static string EncryptString(string strText, string key)
        {
            byte[] buffer = new MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(key));
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
            provider.Key = buffer;
            provider.Mode = CipherMode.ECB;
            byte[] bytes = Encoding.ASCII.GetBytes(strText);
            string str = Convert.ToBase64String(provider.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length));
            provider = null;
            return str;
        }

        public static string EncryptUTF8String(string strText, string key)
        {
            byte[] buffer = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(key));
            TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
            provider.Key = buffer;
            provider.Mode = CipherMode.ECB;
            byte[] bytes = Encoding.UTF8.GetBytes(strText);
            string str = Convert.ToBase64String(provider.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length));
            provider = null;
            return str;
        }
    }
}

This is from http://space.itpub.net/12639172/viewspace-617465

November 9, 2009

Analysis of Dump Device in SQL Server

Today we will talk about how to add dump device where the SQL Server backup database. Dump device is visible in SEM, and the information on the device can be stored in sysdevice table of the key databases .The member servers Sysadmin and diskadmin can allow this device to be added and undone. The following script will display how to add this device .And then the Sysdvices table will get the information from the device and undo the dump device.

 EXEC sp_addumpdevice ‘DISK’, ‘pubs_dump’, ‘c:pubs_dump.bak’
  GO
  BACKUP DATABASE pubs TO pubs_dump WITH NOINIT, STATS = 10
  GO
  SELECT name logical_name, phyname physical_name, *
  FROM master..sysdevices WHERE name = ‘pubs_dump’
  GO
  EXEC sp_dropdevice pubs_dump, DELFILE
  GO

You can directly backup the database without using dump device .The following command will help you make it.

BACKUP DATABASE pubs TO DISK=‘c:pubs_filedump.bak’
  WITH NOINIT, STATS = 10

  GO

SEM is invisible in the backups of Database .So, you can add the dump device to point this file .When the dump device is added, you can use SEM to provide visible files for the dump device. Although the content in the storage files can not be seen when the dump device was added, the SEM can see them.

SELECT name logical_name, phyname physical_name, *
  FROM master..sysdevices WHERE name like ‘%pubs%’

  GO

  EXEC sp_addumpdevice ‘DISK’, ‘pubs_diskdump’, ‘c:pubs_filedump.bak’

  GO

  SELECT name logical_name, phyname physical_name, *

  FROM master..sysdevices WHERE name like ‘%pubs%’

  GO

 

 

If we want to undo this device and files, you can use the command sp_dropdevice to logic device name .If you want to delete the file the dump device pointed, you can add the Delete statement .The following script will undo the device created previously.

Older Posts »

Powered by WordPress

Close
E-mail It