Microsoft Study Bible

October 30, 2009

The fighting between Microsoft and Open source.

Filed under: Windows — Tags: , , — Jackson @ 5:01 am

For many years, the fighting between open Source Movement and Microsoft almost has been a religious war. The firepower of both parties .Microsoft boss Steve·Ballmer consider the open source movement as “a cancer”, while the founder Linus·Torvalds once hinted that he can destroy Microsoft as easy as blow off dust. Recently ,the founder of Lotus , Mozilla Foundation president Mitch Kapor think the war of Microsoft and Open source software has been ended ,because the resist of Microsoft and its followers is too weak to stand competition or attack.

Although Firefox has been considered as a great achievement, Kapor warned that in fact it was not the best example that show open-source movement have won .Instead ,he think this movement’s main achievement is unseen by people –those systems who support the network itself. He said that the history of Mozilla and Firefox is that it is never taken as “possible” example .and the success of Open-Source is it is back-end network, the invisible part that cannot be seen as users.

October 28, 2009

LINQ to SQL common BaseClass

LINQ is a series of new features provided by Visual Studio 2008, which will expand C# and Visual Basic and can provide powerful query capabilities. As part of LINQ, LINQ to SQL can provide a framework on which the relational data is used as object to run. In one way, it is equal to NHibernate and Castle provided by Microsoft. When we need to access the database, LINQ to SQL will become our first choice.

In LINQ to SQLall varies in relational database model are strongly typed ,which can provide verification and intelisense when they are being complied .And we can use Query expression including query syntax and method syntax, to access data from the database.

 

1. Achieve where method

 

 Howeverthe strongly-typed is not beneficial to do abstract operation on the data .So, the developer had to define some particular class for each entity object, which will cause to a lot of duplicate code .If we can achieve a common BaseClass and encapsulate Public Data operation such as Select ,Where ,Add ,Update and Delete ,it can be useful for us to develop the N-tier application development.

Fortunately, Generics Types can help us make it .The way is to call GetTable<T>() method of  DataContext .For example ,we can achieve where method by passing a Lambda expression to find the result we want to get.

 public IList<TEntity> Where(Func<TEntity, bool> predicate)
{
    InitDataContext();
    
return
m_context.GetTable<TEntity>().Where(predicate).ToList<TEntity>();
}

 

Andwe can even use Dynamic Query to expose some methods to receive conditional expression

public static class DynamicQueryable
{
    
public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object
[] values)
    {
        
return
(IQueryable<T>)Where((IQueryable)source, predicate, values);
    }
public static IQueryable Where(this IQueryable source, string predicate, params object
[] values)
    {
        
if (source == null) throw new ArgumentNullException(“source”
);
        
if (predicate == null) throw new ArgumentNullException(“predicate”
);
        LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType,
typeof(bool
), predicate, values);
        
return
source.Provider.CreateQuery(
            Expression.Call(
                
typeof(Queryable), “Where”
,              
                
new
Type[] { source.ElementType },
                source.Expression, Expression.Quote(lambda)));
    }
}
public IList<TEntity> Where(string predicate, params object
[] values)
{
    InitDataContext();
    
return
m_context.GetTable<TEntity>().Where(predicate, values).ToList<TEntity>();
}

 

Data Entity operation

Of course, for an AbstractBaseClass, there is no problem to query .Because there is no need to care the properties of the entity or the composition of the expression Lambda when we call these methods. (more…)

Linus Torvalds thumb up to Windows 7

Filed under: Windows — Tags: , , — Jackson @ 5:34 am

The release of Windows 7 throws a rock to the market of operating system, and makes a big splash. Especially, the rivals of the Microsoft have different attitudes to this. Apple once claimed that it is a good opportunity for apple to snatch pc users and would provide official support for windows 7 through Boot Camp software a few days ago.

Although the other important rival Linux have not declared his opinion to Windows 7, the father of Linux Linus Torvalds thumbed up to Windows 7.When Torvalds attend a seminar exhibition held in Japanese, right to the conference center ,the Microsoft was holding large-scale publicity conference .During meeting break, Torvalds was pulled across the street to “make fun of Microsoft”. Unexpectedly ,Linus Torvalds thumbed up ,which was taken photo of .This picture will go down in  history for ever .

423b4be4-33b5-48ad-b82a-e3c59cd1beb6

October 26, 2009

What does ASP.NET 3.5 Extensions bring to us?

Filed under: Developer tools and applications — Tags: , , , , — Jackson @ 9:32 pm

1. Overview

The release of the new technology .NET 3.5 and Visual Studio 2008 makes milestone contribution to the .NET strategy of Microsoft. In the Web development, it includes a powerful HTML Web designer which provides split-view editing, and the perfect CSS. Meanwhile, it makes its support to JavaScript better, including Intelligent hints and debug.

 

Microsoft issued the first preview version of ASP.NET 3.5 Extensions only 20 days after it released .NET 3.5. The final version is released in the first half of the year 2008, which contains more features of ASP.NET:

1. ASP.NET MVC Framework

2. Improvement of ASP.NET AJAX

3. ASP.NET Dynamic Data support 

4. ASP.NET Silverlight support

5. ADO.NET Data services

 

In this article, I will display some of the new features of ASP.NET 3.5 Extensions though several simple examples.

2. ASP.NET MVC framework

The concept of MVC has been raised for many years. It divides the application implementation into three parts: Model to maintain the data status, View to display the user interface, Controller to handle the user interaction, operate Model and select View to display the data. The first concern of ASP.NET MVC Framework is separation for testing more conveniently. Meanwhile, it uses aspx page, template page and user control as View and provides powerful URL Routing Engine. I will show these features by examples.

 

Step1: set up Model, use LINQ to SQL to establish a Product data model

 

 

 

Step2 set up View, display the detailed information of Pdoduct by using an aspx page which inherited from a Generic ViewPage

 

public partial class Product_Product : ViewPage<ProductInfo>
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
 

 

 

 

   show the data in aspx page, use <%=%> directly to label output 

<div>
<h2>ProductDetail:</h2>
ProductId

<%= ViewData.ProductId %><br /><br />
Name
<%= ViewData.Name %><br /><br />
Descn
<%= ViewData.Descn %>
</div>
 
 

 

 

Step3set up Controllerinherit from Controller base classand add Actionat the same time, use product view to realize the data function and input data object that needs to be displayed.

public class ProductController : Controller
{
[ControllerAction]
public void Index()
{
MSPetShopDataContext db = new MSPetShopDataContext();
ProductInfo productinfo = db.ProductInfos.Single(p => p.ProductId == “BD-03″);
RenderView(”Product”, productinfo);
}
}
 

 

 

 

Step4select Path for Configurationmake configurations Application_Start

 

void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(
new Route
{
Url = “[controller]/[action].mvc”,
Defaults = new { action = “Index”},
RouteHandler = typeof(MvcRouteHandler)
}
);
}
 
 

 

basicly, the proceedings are the four steps for setting up a application based on ASP.NET MVC Framework.

   


3. ASP.NET AJAX improvement
 
 

 

In the ASP.NET 3.5 Extensions, the most important improvement to ASP.NET AJAX is a better support to browser history that we can control the Back and Forward button more conveniently. It provides two ways for us to choose, using server-side control or Client-script. In the following, I will illustrate how to use server-side control to control the browser history.


       add ScriptManager Control
and set its EnableHistory attribute as truepermit the history management of browser and OnNavigate handled as OnNavigateHistory function for dealing with navigation event. At the same time, set the EnableStateHash attribute as false to make modifications easier to perform. In real situations, we can decide whether to perform the Hash encryption as required:

 

<asp:ScriptManager runat=”server” ID=”ScriptManager1″
OnNavigate=”OnNavigateHistory”
EnableHistory=”true”
EnableStateHash=”false” />

 

Create Browser history point at the time of clicking button with the way of AddHistoryPoint

 

 

public void ButtonClick(object sender, EventArgs e)
{
LabelHistoryData.Text = ((Button)sender).Text;
ScriptManager.GetCurrent(this).AddHistoryPoint(key, LabelHistoryData.Text);
} 

 

Navigation processing

public void OnNavigateHistory(object sender, HistoryEventArgs e)
{
LabelHistoryData.Text = Server.HtmlEncode(e.State[key]);
} 

 

For demonstrationthree button should be added on the page

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="Button3" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Panel runat="server" CssClass="box" ID="Content" Height="40px">
Date and Time:
<%= DateTime.Now.ToLongTimeString() %>
<br />
Page's refresh state:
<asp:Label runat="server" ID="LabelHistoryData" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<p />
<asp:Button runat="server" ID="Button1" Text="Key 1" OnClick="ButtonClick" />
<asp:Button runat="server" ID="Button2" Text="Key 2" OnClick="ButtonClick" />
<asp:Button runat="server" ID="Button3" Text="Key 3" OnClick="ButtonClick" /> 

 

  

In the preceding, I mainly use the server-side approach to realize the support to browser history in ASP.NET AJAX, you can also use client script to manage browser history.

 

 

 

 

 

 

October 21, 2009

A way to save and read ntext,image in ASP.net.

Filed under: Developer tools and applications — Tags: , , — Jackson @ 5:33 am

Today, I will introduce a way to use stored procedures to save and read the field ntext and image field. In ASP.net, how should we call the stored procedures?

Firstly, create the procedure:

CREATE   PROCEDURE   sp_textcopy   (

 @srvname   varchar   (30),

 @login   varchar   (30),

 @password   varchar   (30),

 @dbname   varchar   (30),

 @tbname   varchar   (30),

 @colname   varchar   (30),

 @filename   varchar   (30),

 @whereclause   varchar   (40),

 @direction   char(1))

 AS

 DECLARE   @exec_str   varchar   (255)

 SELECT   @exec_str   =

 ‘textcopy   /S      +   @srvname   +

    /U      +   @login   +

    /P      +   @password   +

    /D      +   @dbname   +

    /T      +   @tbname   +

    /C      +   @colname   +

    /W   “‘   +   @whereclause   +

 ‘”   /F      +   @filename   +

    /’   +   @direction

 EXEC   master..xp_cmdshell   @exec_str

 

2. And then, create the table and initialize the data.

create   table     tablename (NO   int,image columnname   image)

 go

 insert  tablename   values(1,0x)

 insert   tablename   values(2,0x)

 go

 

3. Read in the data.

sp_textcopy ‘yourservername’,’sa’,'yourpassword’,'libname’,'tablename’,'imagecolumnname’,'c:\image.bmp’,'where NO=1′,’I’ –Attention is NO=1sp_textcopy   ‘yourservername’,’sa’,'yourpassword’,'libname’,'tablename’,'imagecolumnname’,'c:\bb.doc’,'where    NO=2′,’I’   –Attention is   NO=2

 go

 

4. Read out the data into a file:

sp_textcopy ‘yourservername’,’sa’,'yourpassword’,'libname’,'tablename’,'imagecolumnname’,'c:\image.bmp’,'where NO=1′,’I’ –Attention is NO=1sp_textcopy   ‘yourservername’,’sa’,'yourpassword’,'libname’,'tablename’,'imagecolumnname’,'c:\bb.doc’,'where    NO=2′,’I’   –Attention is   NO=2

 go

 

October 20, 2009

How to operate UI layer control state In C#

Filed under: Developer tools and applications — Tags: , , , — Jackson @ 5:40 am

Suppose that there is a form F, which has a button BtnA and a Label control.

Requirements: click the button BtnA and display the status in Label according to the Start() method .

The resolution is to use the delegate or event .Let’s look at the following codes:

The form code:

private void BtnA_Click(object sender, EventArgs e)
  
{
   A ms = new A();

ms.SetInfo += new EventHandler(ms_SetInfoTwo);
   Thread m = new Thread(new
ThreadStart(ms.Start));
   m.Start();

}

private delegate void mySetInfo(string s);
   void SetInfoOne(string
s)
  
{
   if (this
.InvokeRequired)
  
{
   this.Invoke(new
mySetInfo(SetInfoOne), s);
   return
;
  
}
   this
.Label1.Text = s;
   }

// event

void ms_SetInfoTwo(object sender, EventArgs e)
  
{
   if (this
.InvokeRequired)
  
{
   this.Invoke(new
System.EventHandler(ms_SetInfoTwo), sender);
   return
;
  
}
   this.Label1.Text = (string
)sender;
   }

Class A:

public class A
   {

public event EventHandler SetInfo;

private void SetSourceInfo(object sender, EventArgs e)
  
{
   if (SetInfo!= null
) { SetInfo(sender, e); }
   }

public dSetSourceInfo tt;
   public delegate void dSetSourceInfo(string str);

private void SetSourceInfott(string str)
  
{
   if (tt != null
) { tt(str); }
  
}
   public
A() { }
  

   /**////

/// Start

public void Start()
   {

SetSourceInfo(“hahaha”,null);
   Thread.Sleep(1000
);
   SetSourceInfo(“hahaha1″,null
);
   Thread.Sleep(1000
);
   SetSourceInfo(“hahaha2″,null
);
  
}
   }

October 16, 2009

How to perform operation on library with managed code.

In the previous articles, we have discussed how to use Shell API to manipulate the library with unmanaged codes?

 So, what about the managed codes??

To display how to manipulate the library with the managed code, we create a console application written in Visual C#, and then add the reference of Microsoft.WindowsApiCodePack.dll and Microsoft.WindowsApiCodePack.shell.dll to the project. Now, we can use the object ShellLibrary .

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
// use the namespace the ShellLibrary located

using Microsoft.WindowsAPICodePack.Shell;
namespace
LibraryDemoCS
{
    
class
Program
    {
        
static void Main(string
[] args)
        {
            
// To definite the name the library and the path to save the folder
             string strLibName = “MyLib”
;
            
string strFolderPath = @”C:\”
;
            
// create library and add the folder.

             using (ShellLibrary library =new ShellLibrary( strLibName, true))
             {
                  library.Add(strFolderPath);
              }
              
// To load the library which already exists and perform the operation.

               using (ShellLibrary lib = ShellLibrary.Load(“MyLib”, false))
               {
                    
//To add new folder
                    lib.Add(@”D:\”
);// To set properties
                     lib.IsPinnedToNavigationPane =
true;
                    
string strDefSaveFolder = @”D:\”
;
                    
// To set the default folder to save the file.

                     lib.DefaultSaveFolder = strDefSaveFolder;
                    
// to traverse the folder in the library in the loop.

                    

                    // find and display the default folder.

                    foreach (ShellFolder folder in lib)
                    {
                        Console.WriteLine(
“\t\t{0} {1}”, folder.Name, strDefSaveFolder ==folder.ParsingName ? “DefSaveFolder” : “”
);
                      }
                  }
                  Console.Read();
               }
           }
}

In this code, we used the ShellLibrary object in Windows API Code Pack to manipulate the library such as: to create the library, to add the folder, and set the properties and traverse the folder that the library will manage, and so on. From the example, we can get to know that it is easier and more flexible to use managed code than unmanaged code.

How to manipulate the library with unmanaged codes?

We could use the library Shell API in Windows 7 and unmanaged codes to manage the libraries .When downloading the software, we often used the folder to classify kinds of resources. For example, among those software, the resource which were downloaded were organized in “All downloads” .In fact, those resources could be stored in different directories and partitions on your hard disk. To be more conveniently use Windows-Explorer to access all of those resources, there is need to create a “MyDownload” library, which is corresponding to the Classified Management way of the “All downloads” file, and manage all of resources downloaded in.

   To better display how to manipulate the library with Shell API, we create a simple console application with Visual C++. In the main function, we’ll create and do the operation of library.

 #include “stdafx.h”
// the introduction of header files

#include <shobjidl.h> // introduce Shell API
#include <objbase.h>
// define  IID_PPV_ARGS  macro
#include <Knownfolders.h> // introduce FOLDERID

int _tmain(int argc, _TCHAR* argv[])
{
    
// COM initialization
    CoInitialize(NULL);
    
// use Shell API to create a library

    IShellLibrary *pIShelLibrary;
    HRESULT hr = SHCreateLibrary(IID_PPV_ARGS(&pIShelLibrary));
    
if (SUCCEEDED(hr))
    {
        
// if the library are successfully created,add the paths of the different files to it.

        IShellItem *pIShellItem;
        SHAddFolderPathToLibrary(pIShelLibrary,
        L
“C:\\Users\\Public\\Pictures”);
        SHAddFolderPathToLibrary(pIShelLibrary,
        L
“C:\\Users\\Public\\Music”
);
        SHAddFolderPathToLibrary(pIShelLibrary,
        L
“D:\\Tools”
);
        SHAddFolderPathToLibrary(pIShelLibrary,
        L
“D:\\Video”
);
        
// store current library into the directories of the system library .
        // that is to say ,to add a new library
MyDownload

        hr = pIShelLibrary->SaveInKnownFolder(FOLDERID_Libraries ,
        L
“MyDownload”
,
        LSF_MAKEUNIQUENAME,
        &pIShellItem);
      
// release the object.
       pIShellItem->Release();
       pIShelLibrary->Release();
  }
    
// release COM

    ::CoUninitialize();
    
return 0;

 

In this code, at first, we introduce the header files that Shell API required .Then in the main function, because those APIs all are based on .COM, we should firstly do COM initialization .After initialization, we can do the operation of the libraries by Shell API. In the code example, we create a new library object with SHCreateLibrary function, and use SHAddFolderPathToLibrary function to add the paths on the hard disk into the library, that is, to use the library to manage the files under these paths. Afterwards, we stored this library created into FOLDERID_Libraries, that is, create a new library definition file under this directoryFinally, we need to release the object COM .After the above steps, we could see the library created in the file browser.

October 14, 2009

How to improving IIS 6.0 more secure?(part 2)

Filed under: Developer tools and applications, Windows — Tags: , , , — Jackson @ 4:43 am

6. Make Good Use of Web Service Extensions in IIS 6.0

 

Web Service Extensions in IIS 6.0 is a mighty ally in the fight for security. This feature prevents executable content from being delivered unless it is explicitly allowed by full path name. By default, IIS 6.0 will not deliver any executable content! This means that if you want to allow ASP to run you must configure Web Service Extensions to permit ASP.dll to execute. As a result, even if you granted a Web site the NTFS permission of Everyone—Full Control, and an attacker placed an executable in the Web site, they still could not run the executable from a URL. A 404—File not Found error would be returned. Figure 3 shows the default configuration that allows only static content to be delivered.

 

 fig03

Figure 3  IIS Manager

This feature can be disabled by electing to allow “All Unknown ISAPI” and “All Unknown CGI”. You may find yourself doing this when troubleshooting in order to remove potential problems. You will also find that developers who use IIS 6.0 will disable this feature as it can be quite annoying to have your most recent executables blocked every time you create a new one. This may be fine for your developers, but it is not fine on your production server.

 

 

7. Use Host Headers

 

This one surprises most administrators, but I recommend using host headers on your public-facing Web sites, even if you don’t need them. A host header is the HOST field that is part of the HTTP request sent from the client when contacting IIS. This field is required as part of the HTTP 1.1 specification. When you assign a host header to a site, the site must be accessed by the name entered in the host header field.

 

For example, if I assign contoso.com to a Web site’s host header field, then the user must type in http://contoso.com (which, of course, must resolve to the correct IP address) in order to connect to the server. If they type in http://www.contoso.com, the connection will fail. As a result, in the Advanced Configuration you should enter every name for which you have DNS configured to resolve to the IP address of the server.

 

I know you’re wondering why you should bother. The most aggressive and famous attacks in Internet history have all succeeded by finding servers to infect through some automated IP address scanning process. If you use host headers, your Web sites will not respond to an IP address. In other words, the Web site Contoso.com is always available when using Contoso.com or www.contoso.com, but if you use http://192.168.1.1 (the IP address of contoso.com) the connection is refused because the IP address does not match the host headers you entered for the site.

 

In this way, any future worms using an IP address scanning engine will miss you completely. This will not interfere with SSL as long as you have a unique IP address for each Web site.

 

 

8. Scrub Your Apps

 

I’d be remiss if I did not point out that the most likely point of attack on IIS these days is not the server itself, but the applications you host. After you’ve tightened up your server and you are successfully channeling all the untrusted traffic to port 80 on your Web server, you may still be hosting exploitable applications, in which case you’ve got a different kind of problem. This is not one that administrators can do much about. It would be a good idea, however, to check on your software design policy and be certain that it contains this directive: all user input is considered bad or malicious. This means that your applications must enforce validation of every entry in every form, every request to a service, and any other way the user has of entering content into the application. An attacker will try to enter all kinds of content into every field of an application to see what happens. A persistent hacker will not miss any of them, so you can’t either.

 

 

 

9. Keep Your Server Updated

 

Of course you must keep your server current with the latest updates for Windows Server 2003 as well as those for any other apps. The good news is that, as of this writing, IIS 6.0 has required zero critical security updates since it was released. This is an outstanding record that Microsoft is proud of and intends to continue. For more best practices, see “Checklist: Securing Your Web Server”.  

This article from:

http://blog.csdn.net/yjz0065/archive/2006/08/02/1011222.aspx

Best way to decompress .zip file in C#?

Filed under: Developer tools and applications — Tags: , , — Jackson @ 4:37 am

To decompress .zip file, there are many ways on the internet such as  using System.IO.Compression.GZipStream ,and J # library function ,etc. Finally ,many ways were tried out ,and it is best to use System.Shell.Folder.copyHere(oItem [, intOptions]) .
So, let’s look up the detailed information about this function.
1. firstly ,we should add the reference to  “Shell32.dll” in windows\system32.
2. add the method .
static void UnZip(string zipFile,string destFolder)
            {
                        Shell32.ShellClass sc = new Shell32.ShellClass();
                        Shell32.Folder SrcFolder = sc.NameSpace(zipFile);
                        Shell32.Folder DestFolder = sc.NameSpace(destFolder);
                        Shell32.FolderItems items = SrcFolder.Items();
                        DestFolder.CopyHere(items, 20);
            }
Notice :destFolder must be the folder existed as this method could not automatically create folder .

Older Posts »

Powered by WordPress

Close
E-mail It