Microsoft Study Bible

February 21, 2010

Does your training center need an online business expansion?

Filed under: Server technologies — Jackson @ 11:41 pm

Hello everyone, I am Megan from Getinmore. Remember my name for I am willing to help your training center to get more income.

What is Getinmore?

Getinmore is an online training service corporation which aims to enable you to start your training business online with 0 input.

What is our Service?

We have three major platforms: online trading platform, affiliate marketing platform, and remote education platform.

What does Online Trading Platform Contain?

Online Training Platform. In another word, it is our website. You are able to release and manage your online training courses information, check how many students are enrolled, how much do you earn, and how many customers are brought by the affiliate marketing, the evaluation from the students, apply to payment, etc. You may think you can also do this on your website. Indeed. This is just a first part of our service.

How does Affiliate Marketing Platform work?

Affiliate Marketing Platform brings your additional customers. You are able to check how many students are brought by it in your user center. And the students can also be your local students. After we have enough students, you submit the time to start the class. Then, you can use our Remote Educational Platform to deliver the course.

What is the Remote Educational Platform?

We use WebEx as your educational tool. If your trainers are not familiar with WebEx, we have technicians to train them. And before cooperation, you can have a test on the platform to see whether it work well with your class. And in every class, we will arrange a host to help your solve the problems with using WebEx.

After your trainers finish delivering the lecture, you can apply us to pay the fee to you. And we will transfer the money to your account in a month.

All the services enable to start your own online training center with 0 inputs. We will add customized services according to your advices.

Please tell me your advice about service for we sincerely welcome you to join us and sparing no efforts to improve our service to meet your requirements.

Please mail me @ sales@getinmore.com or call me @ +17033504321.

Advices and Cooperation intentions are mostly welcomed.

December 7, 2009

How to pass parameters between Asp.net pages

Filed under: Server technologies — Tags: , , , , — Jackson @ 5:28 am

 There are many methods to pass parameters between pages, including Get, Post, Session, and Application。However,there are some new and unique methods in Asp.Net.
The page B wants to take the value from Page A. (more…)

December 2, 2009

Error LNK2001 (C++)

Filed under: Server technologies — Tags: , , , , — Jackson @ 4:58 am

Would you have such an experience: you try to build program in C++ code. All of the code is simple and legal, however, when you compile link with your programs, the following link errors happen:

>error LNK2001: unresolved external symbol _purecall (more…)

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 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.

SQL Server 2008 :New location-aware data types

Introduction

It was very easy to store location data and just to store the latitude and longitude of the location, by using simple floating point fields. Of course, it was not enough, which can just only achieve simple applications. However, if you want to create more advanced applications or do location of data points by using geometric algorithms, you must write the code by yourself. For example, how would you go on and find all stored locations within a 10 mile radius of a given spot? In such a situation, wouldn’t it be nice if the database itself could handle some of the work for you? This is what the latest release of SQL Server aims to do. With SQL Server 2008, you will have new built-in support for location based data types and supporting geospatial features. Next you will learn how these new data types work.

 

Two types, two models

SQL Server 2008 supports two similar but still distinct data types called geometry and geography. If simplifying things a bit, both are able to store x and y values and support a set of operations to do calculations based on these values. However, what separates these types from each other is that geometry is based on calculations on a straight surface (the “flat Earth” model), but geography does calculations based on the fact that Earth is round.

This distinction is important to remember, as for example taking the shortest route can be fundamentally different depending on whether you calculate Earth to be flat or round. This can easily be seen in shortest routes in inter- continental flights (Figure 1). In fact, SQL Server can base its calculations on dozens of different roundness and coordinate calculations. Such support is needed because traditionally different countries have had slightly different ways of calculating the shape of Earth. These differences are minute, but nonetheless can affect your results if you are not careful.

1

Figure 1. Which route is actually the shortest one?

 

 

 

SQL Server uses a notion of Spatial Reference Identifiers (abbreviated as SRID) which you must use when using either of the data types. However, for the simpler geometry data type, the SRID value is ignored, and can be set to zero. For the geography type, you have to explicitly set the SRID value. SQL Server prefers to use a coordinate system called WGS 84 (World Geodetic System 1984), which is assigned to the SRID magic value 4326, which itself is just an arbitrary number. A list of all the supported SRIDs can be found from the sys.spatial_reference_systems view in the Master database (Figure 2).

2

Figure 2. SQL Server supports many different SRIDs.

 

 

 

Nowadays, the importance of different coordinates has diminished, as the WGS 84 system is used globally in the GPS system (Global Positioning System). Thus most online mapping sites are based on the same reference system.

Back to school with Euclidean geometry

If you were at all awake during your math classes at school, you will surely recall the Euclidean geometry and the simple Cartesian coordinate system (Figure 3). In this system, the center, or origo, is at the coordinates (0,0) and in the classic positioning, the x axis runs from left to right and y bottom to top. In this coordinate system, distances are calculated the same no matter which unit is used: inches, meters and miles all give the same numeric results.

 

 

 

3

Figure 3. The classic Cartesian coordinate system

 

 

 

The SQL Server’s geometry data type sits well within this model. SQL Server implements the type internally as a .NET type, and thus you can directly use the same type in your own applications. The type is defined in the assembly Microsoft.SqlServer.Types.dll, which by default resides in the folder C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies.

As you want to put these new types into real use, take a look at the sample application shown in Figure 4. This application contains simple functionality: at the top, it can store points in a database, and at the bottom, it can plot those points on a map. It can also check whether a point is inside a polygon.

4

 

 

 

Figure 4. The sample application.

Let’s take the topmost button, which can store a geometry point in a database. To form storage for the point(s) in SQL Server, you would first need a suitable table to store the values in. This can be done with a very simple CREATE TABLE statement:

  CREATE TABLE [dbo].[GeometryTest](
   [ID] [int] IDENTITY(1,1) NOT NULL,
   [Points] [geometry] NOT NULL,
   [Description] [nvarchar](50) NULL
  )

With this table in place, you could use the following C# code to store a value into the field: using

  Microsoft.SqlServer.Types;
  ...
  private void geometryAddPointButton_Click(
    object sender, EventArgs e)
  {
    int x = int.Parse(geometryXTextBox.Text);
    int y = int.Parse(geometryYTextBox.Text);
  
    SqlGeometry geom = SqlGeometry.Point(x, y, 0);
  
    // add to database
    string sql = "INSERT INTO [geometrytest] " +
      "([points], [description]) VALUES " +
      "(@points, @description)";
    StorePointIntoDatabase(geom, sql, "geometry",
      "My first geometry point");
  }

First, the code reads the x and y coordinates from the user interface, and then constructs a SqlGeometry instance from the point specified by the x and y values. The SqlGeometry type lives in the Microsoft.SqlServer.Types namespace, which is in turn implemented in a similarly named assembly. Note how a point object can be constructed using the static Point method of the class. As the final step, a simple SQL insert statement is constructed. The actual database access is done in the method StorePointIntoDatabase, which in turn is implemented like this:

  internal int StorePointIntoDatabase(
    object geoPoint, string sql,
    string udtTypeName, string description)
  {
    SqlConnection conn = GetConnection();
    try
    {
      SqlCommand cmd = new SqlCommand(
          sql, conn);
      SqlParameter param = cmd.Parameters.
          AddWithValue("@points", geoPoint);
      param.UdtTypeName = udtTypeName;
      cmd.Parameters.AddWithValue(
        "@description", description);
      conn.Open();
      int rows = cmd.ExecuteNonQuery();
      MessageBox.Show("Added " + rows +
        " row(s) to the database.");
      cmd.Dispose();
      return rows;
    }
    finally
    {
        conn.Dispose();
    }
  }

If you have worked with SQL Server previously, the above code should look very familiar. First, the code opens a connection to the SQL Server database (its specifics are not important here), and then constructs a SqlCommand object with the given INSERT statement.

Note how the parameter value is specified with the Parameters.AddWithValue call. In the case of most other parameter types, the AddWithValue call alone is enough on its own. However, as the new geospatial types are implemented as UDF types (.NET types), the UdtTypeName property of the parameter object must be set. For the geometry type, it is simply “geometry”, and likewise for the geography type, it is “geography”.

Now that you are aware of how spatial data can be added to SQL Server 2008 database tables, you need to learn how to read those values back from the tables. For instance, assume you have the database table GeometryTest which was defined previously. This table has an id value, and you might need to retrieve the point given an id value of 3. In code, you could implement a method similar to the following:

  internal SqlGeometry ReadPointFromDatabase(int id)
  {
    SqlConnection conn = GetConnection();
    try
    {
      string sql = "SELECT [points] " +
        "FROM [geometrytest] " +
        "WHERE ([id] = @id)";
      SqlCommand cmd = new SqlCommand(
        sql, conn);
      cmd.Parameters.AddWithValue("@id", id);
      conn.Open();
      object geometryPoint = cmd.ExecuteScalar();
      if ((geometryPoint != null) &&
          (geometryPoint is SqlGeometry)) {
        return (SqlGeometry)geometryPoint;
      }
      else return null;
    }
    finally
    {
        conn.Dispose();
    }
  }

Here, the implementation is very straightforward: you only need a SQL Server connection, a command object and a simple SELECT statement. Then, you simply set the parameter values and fetch the results.

Plotting points on a map

Now that you know how to read a point value pair back from the database, you can start doing something interesting with them. For instance, you might wish to point a geography latitude and longitude pair on a map. On the web, there are multiple mapping providers, for instance from Google, Microsoft and others.

If you take Microsoft’s solutions, then the Bing Maps offering is a possible choice. When Bing shows you maps, the images are created using URLs like the following: http://www.bing.com/maps/default.aspx?v=2&FORM=LMLTCC &cp=37.839179~-119.541904&style=r&lvl=8 Here, the query string parameter “cp” starts the latitude and longitude pair; in this case they would be 37.8 and -119.5, respectively. With this information in place, you could construct URLs with the following code:

  int id = int.Parse(pointIdTextBox.Text);
  SqlGeography geog = ReadPointFromDatabase(id);
  
  string bingMapsFormat =
      "http://www.bing.com/maps/default.aspx?" +
      "v=2&FORM=LMLTCC&cp={0}~{1}&style=r&lvl=8";
  string bingMapsUrl = string.Format(
      bingMapsFormat, geog.Lat, geog.Long);
  
  webBrowser1.Navigate(bingMapsUrl);
  MessageBox.Show("Point " + geog.Lat +
      ", " + geog.Long + " plotted!");

Here, the ReadPointFromDatabase method is able to retrieve a SqlGeography object from the database given an id value (this could be any other query suitable for the situation). Next, the code constructs the necessary URL value, and then uses a simple WinForms WebBrowser component to display the web page showing the map (see again Figure 4).

Of course, a more sophisticated implementation would use an actual map control, and add for example pushpin or other similar objects on top of the map. However, for many simple applications, it is more than enough to be able to center the map on a certain point.

Calculations with polygons as an example

So far, we’ve discussed the geometry and geography types, but have only focused on single points. However, although points in a two-dimensional space can be very useful, wouldn’t it be great if you could also store lines or even polygons inside a single data field in your SQL Server tables? The good news is that you can!

That said, take for example a look at the SqlGeometry type. By using the static Point method, you can store a single point inside the object. But the same class also contains methods to create lines and polygons with three or more points (Figure 5). Each SqlGeometry object (or a SqlGeography object for that matter) can thus store one or more points, and these multiple points can form any objects you wish to present with those points.

Figure 5. Methods of the SqlGeometry class

 

 

 

Figure 5. Methods of the SqlGeometry class

For instance, assume you would need to store straight lines. This requires two points, the start and end. You could easily use two different database fields for the start and end points, but SQL Server 2008 allows you to store the two points inside a single geometry data type. You might start to think why it is useful to be able to store one or more points in a single table column. The answer is for one part in storage efficiency, but also in calculations. Yes, SQL Server and the corresponding .NET object types allow you to do calculations!

For example, you might have multiple points stored in your database which form a polygon, for instance a square. Then, you might need to determine whether another single point is inside or outside that square. Of course, there are simple algorithms to do this, and you could implement them directly on C#. But you can also let SQL Server do this for you.

SQL Server also supports more advanced features than just simple “points exists” tests. For instance, you can calculate areas, find the center location of an object, detect whether a polygon is closed or not, or find the number of points in a polygon. This gives you a lot of possibilities, especially since you can do these test either in code using the SqlGeometry and SqlGeography objects, or as functions inside a stored procedure, for instance.

But let’s return to a simple square and the need to detect whether a point is inside that square or not. Take for instance a square defined with the Cartesian coordinates ((0,0), (0,10), (10,10), (10,0)). Then, you would need to determine whether the point (5,5) is inside this square (Figure 6). How would you implement this kind of test using the SqlGeometry .NET class?

6

 

 

 

Figure 6. Is the point within the square?

First, you need to define your square. Just like with strings in .NET, you can use a StringBuilder component to build your strings. Similarly, you use a SqlGeometryBuilder object to build geometry objects. Here is an example of using the class:

  SqlGeometryBuilder builder = new SqlGeometryBuilder();

  builder.SetSrid(0);

  builder.BeginGeometry(OpenGisGeometryType.Polygon);

  builder.BeginFigure(0, 0);

  builder.AddLine(0, 10);

  builder.AddLine(10, 10);

  builder.AddLine(10, 0);

  builder.AddLine(0,0);

  builder.EndFigure();

  builder.EndGeometry();

Here, the SqlGeometryBuilder (part of the same Microsoft.SqlServer.Types namespace as the other objects) is used to construct the square with four points. However, since you can store almost an unlimited number of points even in multiple distinct objects, you must specify whenever a figure starts, and when it ends. Before this, you need to specify the spatial reference id (SRID) and also the type of object you wish to create using the BeginGeometry method call. The SRID must be specified, although its value is ignored. Thus, a value of zero will do nicely.

Now that you have the square defined, you need to detect whether the point is inside the square. This can be done using the STContains method of the SqlGeometry object. But first, you need to get an instance of the geometry object from the builder. This can be done using the ConstructedGeometry property. Here is an example:

  SqlGeometry square = builder.ConstructedGeometry;

  SqlGeometry point = SqlGeometry.Point(5, 5, 0);

  SqlBoolean contains = square.STContains(point);

  if (contains.Value)

  {

    MessageBox.Show(”Contains point!”);

  }

As you can guess, the above code will display the message, as the point (5,5) is firmly inside the defined square. In fact, it is the center point.

Conclusion

The SQL Server release 2008 supports many interesting new features, and among them is support for spatial data. In this article, you learned about the geometry and geography types, and saw how these can be used in regular C# applications. For instance, you learned how data points can be read and written, and how you can utilize latitude and longitude values to show points on a map.

Although it has been previously possible to store for example latitudes and longitudes using simple float fields, SQL Server 2008 makes this much easier. Each geometry or geography data type in a table can store one of more points, and thus very complex polygons can be formed if need be. This support allows you to define only a single field in your database table, and store one or more points in it. This would be difficult using regular float fields.

Another benefit of the new special data types is the fact that you can do calculations based on these values. SQL Server 2008 contains nice support for different calculations, and guessing that the next SQL Server versions would further improve things, doesn’t seem far-fetched.

This article is from http://www.developer.com/db/article.php/3839056/Using-new-location-aware-data-types-in-SQL-Server-2008.htm

 

 

 

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…)

October 12, 2009

How to improve IIS security?(part 1)

Filed under: Server technologies, Windows — Tags: , , , , , , — Jackson @ 9:21 pm

Securing your IIS 6.0 installation  is an important task. The amount of work required can vary greatly depending on the complexity of your application as well as your infrastructure and how these combine with your need to secure content.

 

Too often, Web server security is seen as merely a series of steps taken to tighten access to the server. But at Microsoft, the policy is to implement defense-in-depth. This begins with an actual written policy that describes the actions to take should you be hacked. Securing your IIS installation is just one of several tactics, but it is an important one. In this column, I’ll cover nine important steps you can take to get a lot of security improvements with little impact on your applications, administration tasks, or Web server. Keep in mind that these tips are based on my experience and not necessarily Microsoft practice. 

1. Place your content on a non-system drive 

Let’s say your Web site files are stored at C:\inetpub\wwwroot. IIS receives a request for http://website/../../. What folder is IIS going to deliver from? In this case, it’s the root of the C drive, as “..” is a valid file system command that says move up one directory level (this is sometimes referred to as the parent path as it represents a path of the parent folder without knowing the actual name).

 

This is no different than opening a command window in the same folder and typing “cd..”. As a result, the URL http://website/../../winnt/system32/cmd.exe is often found in IIS log files. This attack will fail when using the latest versions of Internet Explorer® as they will not permit “..” in a URL, but attackers will use other HTTP clients to try to circumvent this failsafe. Of course, IIS 6.0 also includes protections against this sort of attack. IIS will utilize a canonicalization routine to map the URL back to the intended file to ensure that the user does not leave the root path of the site. Nevertheless, placing Web content on a non-system drive is an extra safeguard you can put in place to protect your system data should an attacker somehow circumvent these built-in countermeasures.

 

 

2. Disable Parent Paths

 There’s more than one way to do a directory traversal attack. As a result, it is best to ensure that parent paths are disabled. In IIS 6.0, the ability to use parent paths in files and ASP scripts is disabled by default, and it’s best to keep it that way to prevent attackers from injecting code into your applications that may allow them to browse your directory structure. Be sure to have your developers write code that does not make use of “..” in a URL or script when at all possible.

  

3. Check and Double-check Your NTFS Permissions

 

Proper access control lists (ACLs) on your files are the bedrock of your Web server security. You can harden all you want but if you mess up here, the game is over. So here’s how you should set permissions. Execute permission is needed for binary executables such as DLLs and EXEs. You should set Read permission for static content and scripts. You may have thought scripts required the Execute permission, but they don’t so you should not allow it. Only grant Write permission to security principals and resources that require it. Anywhere you permit Write and Execute, monitor for appropriate content. Create a group for users who need to publish to a Web site and assign Write permissions to the group. This makes administration easier.

 

Systernals provides a great tool called AccessEnum for helping you inspect your permissions. For more information, see sysinternals.com/Utilities/AccessEnum.html.

 

 

4. Know the Group Membership of the Anonymous User and Enforce Restrictive Permissions

 

The IUSR account (named IUSR_servername) is the account user to provide anonymous access to Web content. Created during the installation of IIS, IUSR is unique to each server. When anonymous access is enabled and NTFS permissions allow the kind of access requested (for example, Read permission for the IUSR account), IIS will access the content as if the request were made by someone who logged on as the IUSR user. This involves some sleight of hand behind the scenes that can get a bit involved. In a nutshell, though, IIS knows the password of the IUSR account and uses that password to automatically log the user onto the server.

 

Just like any user, the IUSR account has some group memberships. Giving permissions to any of these groups gives the IUSR account access to the content. The default memberships are: Everyone, Users, Guests, Authenticated Users, Network, Domain Users (if IIS is on a domain controller), and Web Anonymous Users (if the IIS portion of the Security Configuration Wizard has been run).

 

You can verify membership by using the W3Who.dll program from the IIS 5.0 Resource Kit. This ISAPI executable will report on the group memberships and rights of whoever invokes it. Put this file in a folder that has NTFS execute permissions for the IUSR account and allow anonymous access. Also configure the folder to allow Execute in the IIS manager and permit the executable to run in the Web Service Extensions configuration. Then invoke the DLL directly by typing http://servername/folder/w3who.dll to get the report.

 

If you don’t have a Web Anonymous Users group on your Web server, you should create one and add the IUSR account to this group. You can then take the extra measure of denying Write and or Execute permissions to this group in strategic locations. One of the key benefits of this approach is that you can add more users to the Web Anonymous Users group thereby enforcing more restrictive permissions on those special users who may try to poke around where they don’t belong.

 

 

5. Limit Ports Exposed to an Untrusted Network

 

Each open port on a Web server has a specific service listening for incoming requests. Typically, IIS listens on port 80 for HTTP and 443 for HTTPs connections. IIS has no requirement for any ports to be open other than those you want to use to communicate with the client. An attacker will find all the ports your server has open and attempt to exploit the listening service. As a result, it is very important to reduce the number of ports and services you expose to an untrusted network to the bare minimum.

 

The IIS server will typically communicate with a firewall which is designed to filter out all traffic that does not conform to a specific set of rules. Firewalls are highly reliable devices in general, but can be compromised due to misconfiguration or exploitation just like any other device. To practice defense-in-depth, design your site as if the firewall were local on the IIS server.

 

There are three techniques available aside from using commercial software. You can disable unnecessary services, use Windows® Firewall for port filtering, or use IPSec for port filtering, encryption, and authentication. Here’s what you need to do.

 

You can disable unnecessary services in the Service console. There you will notice that Windows Server™ 2003 has fewer services enabled by default than Windows 2000 did, but you should verify the services that are running to ensure they are all necessary in your environment and disable any that are not.

 

There is some risk involved as you may disable a service that is required by your server for purposes other than delivering Web content. The Security Configuration Wizard that is installed with Service Pack 1 (SP1) will help you safely reduce the number of services used by your server. You can do even more fine tuning if you take some time to study what these services do.

 

The most complete documentation I’ve found on disabling services is “The Threats and Countermeasures Guide”. You’ll find a complete list of the services installed, what they do, and what ports they use in the Services section. This is a must-have reference.

 

You can also disable File and Print Sharing and in some cases the Client for Microsoft Networks (as shown in Figure 1). This works well when you have a network card dedicated to communicating to the untrusted network that is restricted to Internet protocols.

Figure 1  Disable Services

 

 

 

 

  

Figure 1  Disable Services

Figure 1  Disable Services

 

Typically you will want your IIS server to communicate with other devices on the network to provide additional services for administration, authentication, database access, and monitoring. These services require additional ports and services to be available over the network. In this situation, you will want two networks available to IIS. One network connects to the firewall that receives requests from an untrusted network and has a minimum number of ports and services exposed. The other is the network that has been designed for secure internal communication, and can allow more services to be enabled. In this situation, it is very important to monitor IIS carefully so that if the server were to be compromised, the attack would quickly be identified to prevent the attacker from gaining access to the back-end network.

 

If you use Windows Firewall (see Figure 2), included with SP1, for port filtering you’ll find that it’s easy to restrict the ports exposed by the server. You can also specify which IP addresses the server will accept connections from. This allows you to create a rule that says “only communicate with the firewall’s IP address on ports 80 and 443.” When you implement port filtering in this way, you further reduce the exposure of ports to the untrusted network. In addition, by requiring IIS to communicate only with a specific IP address, such as a firewall, you help to prevent attacks that would redirect the IIS traffic to another device that may have been compromised by an attacker. You access the Windows Firewall settings by clicking the Advanced tab in the network interface properties. You can also use the Netsh command-line tool to configure the Windows Firewall from a command prompt or a script. You can find more information on Netsh by taking a look at “Help: Administering Windows Firewall with Netsh”.

Figure 2  Windows Firewall

 

 Figure 2  Windows Firewall

Your third choice, as I mentioned, is to use IPSec for port filtering, encryption, and authentication between servers. IPSec is great for securing connections to back-end network devices and has more capabilities than Windows Firewall. For details see “How To: Use IPSec to Provide Secure Communication Between Two Servers”.

Review the Scanf and Printf in SQL Server 2008

There are two extended stored procedures to implement the Scanf and Printf. When a string were extracted and spliced, it would simplify significantly the SQL codes to use them appropriately.
1.xp_sscanf . It can be used to split the character string whose format is relatively fixed, which is a good idea for the guys tired of the substring and the charindex .There is a example for how to split the IP address.The relatively simple and common code is below:
if(object_id(’f_getip’) is not null)
drop function f_getip
go
create function dbo.f_getip(@ip varchar(100))
returns @t table(a int,b int,c int,d int)
as
begin
    set @ip=replace(@ip,’.',’ ‘)
    declare
    @s1 varchar(3) , @s2 varchar(3),
    @s3 varchar(3) , @s4 varchar(3)
    exec xp_sscanf @ip,’%s %s %s %s’,@s1 output,@s2 output,@s3 output,@s4 output
    insert into @t select @s1,@s2,@s3,@s4
    return
end
go
select * from dbo.f_getip(’192.168.0.1′ )
go
/*
a           b           c           d
———– ———– ———– ———–
192         168         0           1
*/
2. xp_sprintf .
The character string could be spliced without worry that the plus and quotation marks were too many to control .For example, a stored procedure for dynamic implementation of SQL statement:
if(object_id(’p_select’) is not null)
drop proc p_select
go
create proc p_select(@tb varchar(100),@cols varchar(100),@wherecol varchar(100),@value varchar(100))
as
begin
    declare @s varchar(8000)
    exec xp_sprintf @s output,’select %s from %s where %s=”%s”’,@cols,@tb,@wherecol,@value
    exec(@s)
end
go

exec p_select ’sysobjects’,'id,xtype,crdate’,'name’,'p_select’

/*

Older Posts »

Powered by WordPress

Close
E-mail It