存档

2011年7月 的存档

databases

2011年7月31日 没有评论

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PMS.PMSClass;
using System.Data.SqlClient;
using System.Collections;
using System.IO;
namespace PMS
{
public partial class frmDataBackup : Form
{
public frmDataBackup()
{
InitializeComponent();
}
public string strg;//声明字段
private void button1_Click(object sender, EventArgs e)//备份数据库
{
try
{
strg = Application.StartupPath.ToString();//得到应用程序路径
strg = strg.Substring(0, strg.LastIndexOf(“\\”));//截取路径
strg = strg.Substring(0, strg.LastIndexOf(“\\”));//截取路径
strg += @”\Backup”;//添加路径信息
string sqltxt =//设置SQL字符串
@”BACKUP DATABASE db_PMS TO Disk=’” + strg + “\\PMS.bak” + “‘”;
if (File.Exists(strg + “\\PMS.bak”))//判断文件是否存在
{
File.Delete(strg + “\\PMS.bak”);//删除文件
SqlConnection conn = DBConnection.MyConnection();//创建数据库连接对象
conn.Open();//连接数据库
SqlCommand cmd = new SqlCommand(sqltxt, conn);//创建数据库命令对象
cmd.ExecuteNonQuery();//执行操作
conn.Dispose();//释放数据库连接资源
if (MessageBox.Show(“备份成功”, “提示”, MessageBoxButtons.OK,//弹出消息对话框
MessageBoxIcon.Exclamation) == DialogResult.OK)
{
this.Close();//关闭窗体
}
}
else
{
SqlConnection conn = DBConnection.MyConnection();//创建数据库连接对象
conn.Open();//连接数据库
SqlCommand cmd = new SqlCommand(sqltxt, conn);//创建数据库命令对象
cmd.ExecuteNonQuery();//执行操作
conn.Dispose();//释放数据库连接资源
if (MessageBox.Show(“备份成功”, “提示”, MessageBoxButtons.OK,//弹出消息对话框
MessageBoxIcon.Exclamation) == DialogResult.OK)
{
this.Close();//关闭窗体
}
}
}
catch (Exception ex)//捕获异常
{
MessageBox.Show(ex.Message.ToString(), “提示”,//弹出消息对话框
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

private void button2_Click(object sender, EventArgs e)//还原数据库
{
try
{
SqlConnection conn = DBConnection.MyConnection();//创建数据库连接
string path = Application.StartupPath.ToString();//得到应用程序路径
path = path.Substring(0, path.LastIndexOf(“\\”));//截取路径
path = path.Substring(0, path.LastIndexOf(“\\”));//截取路径
path += “\\Backup\\PMS.bak”;//添加路径信息
string str =//创建SQL字符串
“use master restore database db_PMS from Disk=’” + path + “‘”;
conn.Open();//打开数据库连接
SqlCommand cmd = new SqlCommand(str, conn);//创建数据库命令对象
cmd.ExecuteNonQuery();//执行操作
conn.Close();//关闭连接
if (MessageBox.Show(“还原成功”, “提示”,//弹出消息对话框
MessageBoxButtons.OK, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
this.Close();//关闭数据库连接
}
}
catch//捕获异常
{
button2_Click(sender, e);//执行按钮Click事件
}
}
}
}

分类: 叽歪生活 标签:

CouchDB与SQLite两创始人联手开发NoSQL通用查询语言UnQL

2011年7月31日 没有评论

H-Online网站报道,知名NoSQL项目CouchDB的创始人(也是CouchBase公司的CTO)Damien Katz与著名开源嵌入式数据库项目SQLite的创始人Richard Hipp最近在共同从事一项重要的工作:为NoSQL制定一个通用的查询语言标准,扫除业界采纳这些新技术的大障碍。

这种新的语言名为UnQLUnstructured Query Language/非结构化查询语言的简称,读如“Uncle”),在很多方面都很像SQL,也有SELECTINSERTUPDATEDELETE等命令,但 是与SQL主要用来处理关系数据库中的表不同,UnQL处理的对象是文档数据库中的无序非结构化文档的集合(称为Collection)。在UnQL中, 文档就是可以用JSON描述的数据单位,但无需是JSON对象,也可以是整数、浮点数、字符串。与传统关系型数据库不同,Collection可以保护多 个结构不同的文档。UnQL中与CREATE TABLE和DROP TABLE命令对应的是CREATE COLLECTION和DROP COLLECTION。查询的WHERE子句指向的是与所存对象的字段对应的文档属性。

历史上,SQL语言的出现为关系型数据库得到广泛应用立下了汗马功劳。Katz相信统一的NoSQL查询语言也会产生类似的作用。而Hipp则表示,UnQL将基于他们丰富的SQL经验,在SQL之外补充适于后现代应用软件中非结构化、自描述数据格式的语法和概念。

目前语言标准的草稿已经可以在网站unqlspec.org上看到,但很不完整,只有语法树简单的语法说明,实例和代码都没有。

分类: 叽歪生活 标签: ,

ASP.NET异常处理准则

2011年7月30日 5 条评论

在开发应用程序的时候,异常处理是非常的重要的,我找到一些异常处理准则,将它共享出来,如有不同意见,欢迎提出来一起探讨。

1、决不“catch”一个Exception,却什么也不处理。如果您隐藏了异常,你永远不会知道是否发生过异常。

2、如果产生Exception,给用户提供一个友好的信息,但记录与有关错误的所有可能的细节,包括它的发生时间,方法和类的名字等实际的错误信息。

3、始终捕获特定的异常,而不是一般的异常和系统异常。

4、你可以有一个应用程序级(线程级)的错误处理程序,您可以用它处理所有一般异常。在一个’意外一般错误”中,这个错误处理程序应该捕获该异常并记录他,除此之外,在应用程序关闭之前应该做出友好的信息提示或者允许用户选择忽略异常继续。

5、不要在所有的方法中写的try – catch。只在有可能有某个特定的异常发生的方法中使用它。例如,如果你是一个文件读写操作,只需处理FileIOException。

6、不写非常大的try – catch块。如果需要,为您执行每个任务编写单独的try – catch程序,在try – catch中只有一段特定的代码。这将帮助你找到哪一段代码产生的异常,你可以给特定的错误信息给用户。

7、如果在你的应用需要,你可以写自己的自定义异常类。自定义异常不要继承SystemException基类。相反,继承ApplicationException。

8、当发生异常时,为了确保清理占据的资源,使用try / finally块。在finally子句中关闭的资源。使用try / finally块,即使发生异常,也能确保资源disposed。

9、错误消息应能帮助用户解决问题。不要给出例如”应用程序发生异常”, “有一个错误”等信息,相反要给出具体的信息“无法更新数据库。请确保登录ID和密码是正确的。”

10、当显示错误信息时,除了告诉什么是错误,该消息还应该告诉用户,不是“无法更新数据库。”,而是建议用户应怎样做:“无法更新数据库。请确保登录ID和密码是正确的。”

11、显示简短和友好的信息给用户。但要尽一切可能的记录实际的错误日志信息。这将有助于诊断问题。

12、在Global.asax中定义一个全局错误处理程序来捕获任何未在代码中处理异常。你应该在事件日志中记录所有的异常追踪和随后进行分析。

 

原文:http://hi.baidu.com/479775812/blog/item/76e4fdadc2ba58054b36d616.html

分类: 叽歪生活 标签:

asp.net三层架构异常处理

2011年7月30日 没有评论

异常可以分为系统异常和业务异常,业务异常必须被转化为业务执行的结果
DataAccess层不得向上层隐藏任何异常。
要明确区分业务执行的结果和系统异常。比如验证用户的合法性,如果对应的用户ID不存在,不应该抛出异常,而是返回(或通过out参数)一个表示验证结果的枚举值,这属于业务执行的结果。但是,如果在从数据库中提取用户信息时,数据库连接突然断开,则应该抛出系统异常。
BL层应根据业务的需要捕获某些系统异常,并将其转化为业务执行的结果。
UI层除了从调用BL层的API获取的返回值来查看业务的执行结果外,还需要截获所有的系统异常,并将其解释为友好的错误信息呈现给用户。
一般使用log4net实现日志记录和自定义异常处理。

更多的讨论:

http://topic.csdn.net/u/20090531/10/75a5a96a-f012-491f-9e7d-a4e9c4c17fc4.html

 

 

How to install and run NUnit in .Net

2011年7月29日 没有评论

Being new to the agile world, all of these new tools can be overwhelming. One of the first things you may want to do as an developer is write a test. As developers, we are curious about how good our code is, but how do you write a test? What tools do you use in the .Net environment? By the end of this tutorial, I will show you how to install, setup, and use NUnit to write your very first test. Once you learn how to write these tests, you will realize just how easy it is to test your code.

Prerequisites:

In order to follow along in this tutorial, you will need the following

  • Visual C# 2010 Express (any version Visual Studio 2010 should do)
  • NUnit (Please note that in order to get the NUnit client to run, you need to have .Net Framework 2.0 installed. It won’t matter if you are using a different version of the framework for your development.)

NUnit Installation:

To install NUnit click on the “.msi” file from the download page, link above, and double click the file and open the file once it’s been downloaded. The “Complete” setup type will be fine. Everything else is pretty much your standard installation. Once the installation is complete, the necessary DLLs will be on your computer and you will be ready to incorporate them into your test project.

Writing NUnit Tests:

Writing a test with NUnit is fairly straight forward. Lets start with the following method called “AddTwoNumbers”.

namespace NUnitTutorial
{
   public class MathObject
   {
      public int AddTwoNumbers(int num1, int num2)
      {
         int result = num1 + num2;
         return result;
      }
   }
}

What you can see is that the method simply adds two numbers together and returns the result. Lets write an NUnit test to make sure this method is returning what we expect. We need to do the following to write a test:

  1. Add a new class library project to your solution. This new project should have the following naming conventions “ProjectUnderTest_Test” where “ProjectUnderTest” is the name of the project that contains the methods you are writing the tests against. image This project will contain all of your tests. Above you will notice that I have a project called “NUnitTutorial” that contains the “AddTwoNumbers” method and a project called “NUnitTutorial_Tests” that will contain the unit tests for that method.
  2. Next add the following DLL to the test project “nunit.framework” image
  3. Write our test.

To write the test we first need to add a using for the project under test (NUnitTutorial) as well as the NUnit framework (NUnit.Framework).

using NUnit.Framework;
using NUnitTutorial;

Now lets add our test to the MathObject_Tests.cs file. We first need to let NUnit know that this class contains tests that need to be ran. To do this we mark the class with the following attribute “[TestFixture]”.

using NUnit.Framework;
using NUnitTutorial;

namespace NUnitTutorial_Tests
{
     [TestFixture]
     public class MathObject_Tests
     {
     }
}

Now, lets add the test method “AddTwoNumbers_returns_3_when_given_1_and_2”. (I always like to name my test methods this way so that I know what method they are testing as well as what the expected inputs and outputs are.) Once we add this method we need to add the attribute “[Test]” to it so that NUnit knows that this is a test to be ran. Note, that all test methods should be void methods, not return anything.

using NUnit.Framework;
using NUnitTutorial;

namespace NUnitTutorial_Tests
{
  [TestFixture]
  public class MathObject_Tests
  {
       [Test]
       public void AddTwoNumbers_returns_3_when_given_1_and_2()
       {            
       } 
  }
}

All that’s left is to call the method with our two inputs and assert that the result from the method is what we expect.

using NUnit.Framework;
using NUnitTutorial;

namespace NUnitTutorial_Tests
{
  [TestFixture]
  public class MathObject_Tests
  {
    [Test]
    public void AddTwoNumbers_returns_3_when_given_1_and_2()
    {
       MathObject mObject = new MathObject();
       int calculatedResult = mObject.AddTwoNumbers(1, 2);
       int exptResult = 3;
       Assert.AreEqual(exptResult, calculatedResult);
    }
  }
}
The above test simply calls the “AddTwoNumbers” method, giving it a 1 and a 2 and asserts that the result from the method is what we are expecting, which is a 3. Now, that we finished writing the test, we need to run it. Build your solution and generate those DLLs.

Running NUnit:

Start up the NUnit client by going to Program Files –> NUnit x.x.x –> NUnit. Once it is up and running, click on File->Open Project and navigate to where the DLLs generated from the test project are located. You want to load the test project DLL into NUnit. image Once the DLL is loaded, it will show you the tests that are in that DLL. image From here all you need to do is click the “Run” button and NUnit will run your tests and output the results. image As you can see, our test passed. Now what would have happen if the test had failed? Let’s find out. Lets change our expected result to be 4 and see what happens. image There you go all the information you need to get NUnit installed and on your way to creating tests and rock solid code.

How to: Create and Run a Unit Test

2011年7月29日 没有评论
Visual Studio 2010

 

Unit tests give developers and testers a quick way to check for logic errors in the methods of classes in C#, Visual Basic .NET, and C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.

This topic covers how to use Microsoft Visual Studio 2010 unit testing tools to automatically generate the skeleton for a unit test from existing code, add validation to fill in that skeleton, create a test category, create a test list, run a test, and read code coverage results.

For a description of the parts of a unit test see Anatomy of a Unit Test.

http://msdn.microsoft.com/en-us/library/dd286656.aspx

log4net使用详解

2011年7月29日 没有评论

 

转自(周公的专栏):http://blog.csdn.net/zhoufoxcn/archive/2008/03/26/2220533.aspx

说明:本程序演示如何利用log4net记录程序日志 信息。log4net是一个功能著名的开源日志记录组件。利用log4net可以方便地将日志信息记录到文件、控制台、Windows事件日志和数据库 (包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)中。并且我们还可以记载控制要记载的日志级别,可以记载的日志类别包括:FATAL(致命错 误)、ERROR(一般错误)、WARN(警告)、INFO(一般信息)、DEBUG(调试信息)。要想获取最新版本的log4net组件库,可以到官方 网站http://logging.apache.org/log4net/下载。现在的最新版本是1.2.10。

下面的例子展示了如何利用log4net记录日志 。

首先从官方网站下载最近版本的log4net组件,现在的最新版本是1.2.10。在程序中我们只需要log4net.dll文件就行了,添加对log4net.dll的引用,就可以在程序中使用了。

接着我们配置相关的配置文件(WinForm对应的是*.exe.config,WebForm对应的是*.config),本实例中是控制台应用程序,配置如下(附各配置的说明):

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<configSections>
<section name=”log4net” type=”System.Configuration.IgnoreSectionHandler”/>
</configSections>
<appSettings>
</appSettings>
<log4net>
<!–定义输出到文件中–>
<appender name=”LogFileAppender” type=”log4net.Appender.FileAppender”>
<!–定义文件存放位置–>
<file value=”D:log4netfile.txt” />
<appendToFile value=”true” />
<rollingStyle value=”Date” />
<datePattern value=”yyyyMMdd-HH:mm:ss” />
<layout type=”log4net.Layout.PatternLayout”>
<!–每条日志末尾的文字说明–>
<footer value=”by 周公” />
<!–输出格式–>
<!–样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] – info–>
<conversionPattern value=”记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] – 错误描述:%message%newline” />
</layout>
</appender>
<!–定义输出到控制台命令行中–>
<appender name=”ConsoleAppender” type=”log4net.Appender.ConsoleAppender”>
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%date [%thread] %-5level %logger [%property{NDC}] – %message%newline” />
</layout>
</appender>
<!–定义输出到windows事件中–>
<appender name=”EventLogAppender” type=”log4net.Appender.EventLogAppender”>
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%date [%thread] %-5level %logger [%property{NDC}] – %message%newline” />
</layout>
</appender>
<!–定义输出到数据库中,这里举例输出到Access数据库中,数据库为C盘的log4net.mdb–>
<appender name=”AdoNetAppender_Access” type=”log4net.Appender.AdoNetAppender”>
<connectionString value=”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:log4net.mdb” />
<commandText value=”INSERT INTO LogDetails ([LogDate],[Thread],[Level],[Logger],[Message]) VALUES (@logDate, @thread, @logLevel, @logger,@message)” />
<!–定义各个参数–>
<parameter>
<parameterName value=”@logDate” />
<dbType value=”String” />
<size value=”240″ />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%date” />
</layout>
</parameter>
<parameter>
<parameterName value=”@thread” />
<dbType value=”String” />
<size value=”240″ />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%thread” />
</layout>
</parameter>
<parameter>
<parameterName value=”@logLevel” />
<dbType value=”String” />
<size value=”240″ />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%level” />
</layout>
</parameter>
<parameter>
<parameterName value=”@logger” />
<dbType value=”String” />
<size value=”240″ />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%logger” />
</layout>
</parameter>
<parameter>
<parameterName value=”@message” />
<dbType value=”String” />
<size value=”240″ />
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%message” />
</layout>
</parameter>
</appender>
<!–定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。–>
<root>
<!–文件形式记录日志–>
<appender-ref ref=”LogFileAppender” />
<!–控制台控制显示日志–>
<appender-ref ref=”ConsoleAppender” />
<!–Windows事件日志–>
<appender-ref ref=”EventLogAppender” />
<!– 如果不启用相应的日志记录,可以通过这种方式注释掉
<appender-ref ref=”AdoNetAppender_Access” />
–>
</root>
</log4net>
</configuration>

程序文件:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using log4net;
//注意下面的语句一定要加上,指定log4net使用.config文件来读取配置信息
//如果是WinForm(假定程序为MyDemo.exe,则需要一个MyDemo.exe.config文件)
//如果是WebForm,则从web.config中读取相关信息
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Log4NetDemo
{
/// <summary>
/// 说明:本程序演示如何利用log4net记录程序日志信息。log4net是一个功能著名的开源日志记录组件。
/// 利用log4net可以方便地将日志信息记录到文件、控制台、Windows事件日志和数据库中(包括MS SQL Server, Access, Oracle9i,Oracle8i,DB2,SQLite)。
/// 下面的例子展示了如何利用log4net记录日志
/// 作者:周公
/// 时间:2008-3-26
/// 首发地址:http://blog.csdn.net/zhoufoxcn/archive/2008/03/26/2220533.aspx
/// </summary>
public class MainClass
{
public static void Main(string[] args)
{
//Application.Run(new MainForm());
//创建日志记录组件实例
ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//记录错误日志
log.Error(“error”,new Exception(“发生了一个异常”));
//记录严重错误
log.Fatal(“fatal”,new Exception(“发生了一个致命错误”));
//记录一般信息
log.Info(“info”);
//记录调试信息
log.Debug(“debug”);
//记录警告信息
log.Warn(“warn”);
Console.WriteLine(“日志记录完毕。”);
Console.Read();
}
}
}

运行结果:

控制台上的输出

 

Log4Net Tutorial in C# .net (How can I show log in a file?)

2011年7月29日 2 条评论

For logging service my choice is log4net from Apache Software Foundation. It is easy to use, open source and well documented. There are also so many logging services but they are not open source. So it is an easy and best solution for you.

Write Log in Console procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create a new console application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. write the main method like this:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;

namespace LogPractice
{
  class Program
  {
    void Main(string[] args)
    {
     log4net.Config.BasicConfigurator.Configure();
     log4net.ILog log = log4net.LogManager.GetLogger(Program);
log.Debug("THis is sadi's world!");
     log.Info("How beautyful the console looks like");
     log.Warn("You are great you did this");
     log.Error("Who make you know is the best");
     log.Fatal("sadi the great");
     Console.ReadLine();&nbsp; // Hold the output
     }
   }
 }

Using Log4net Write log in a file, Procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create an application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. Now put this web.config/app.config file in configuration tag.

 

 

this configuration creates a log file in C:\temp\log.txt.

 

5. To use log4net put this as a local class variable:   protected static readonly ILog log =
LogManager.GetLogger(Program);

 

 

<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
 <level value="DEBUG" />
 <appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
 <param name="File" value="C:\Try\logger\logger\bin\Debug\log.txt" />
 <param name="AppendToFile" value="true" />
 <rollingStyle value="Size" />
 <maxSizeRollBackups value="10" />
 <maximumFileSize value="10MB" />
 <staticLogFileName value="true" />
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
 </layout>
</appender>
</log4net>

6.    And do this to write messages in the log file.   log.Debug(“this text will be in log file”);

For Example:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;

namespace <code>LogPractice</code>
{
 class Program
 {
 protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
 static void Main(string[] args)
 {

 log4net.Config.XmlConfigurator.Configure();
 //————————–
 log.Warn("sadi the great");
 }
 }
}

7. Compile and run the application, and you’ll see output to the console

N.B : if you run this code log will show in the c:/temp/log.txt file.

GridView Sort

2011年7月26日 3 条评论

HOW TO: Using sorting / paging on GridView w/o a DataSourceControl DataSource

If you set AllowPaging=”true” or AllowSorting=”true” on a GridView control without using a DataSourceControl DataSource (i.e. SqlDataSource, ObjectDataSource), you will run into the following errors:

When changing the page on the GridView control:

The GridView ‘GridViewID’ fired event PageIndexChanging which wasn’t handled.

When clicking a column name to sort the column on the GridView control:

The GridView ‘GridViewID’ fired event Sorting which wasn’t handled.

As a result of not setting the DataSourceID property of the GridView to a DataSourceControl DataSource, you have to add event handlers for sorting and paging.

<asp:GridView ID=”gridView” OnPageIndexChanging=”gridView_PageIndexChanging” OnSorting=”gridView_Sorting” runat=”server” />

private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;

   switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = “ASC”;
break;

      case SortDirection.Descending:
newSortDirection = “DESC”;
break;
}

   return newSortDirection;
}

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;

   if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + ” “ + ConvertSortDirectionToSql(e.SortDirection);

gridView.DataSource = dataView;
gridView.DataBind();
}
}

GridView中ViewState

2011年7月26日 没有评论

ViewState

就在当前页面中保存数据的.

像session.是会话级别的.只要会话没有过期.session中存的数据就在.

viewstate是页面级别的.只要这个页面在.viewstate中存的数据就在.

就是说viewstate中存的数据只能在声明该变量的页面中使用.

比如在某页的page_load中声明了:ViewState["test"]=”fdasfdsa”;

那么在该页中的任何一个方法中都可以使用ViewState["test"]来直接得到值”fdsafdsa”.

分类: 叽歪生活 标签: ,

sqlserver连接错误:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。。。。

2011年7月23日 4 条评论

错误:

在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误。未找到或无法访问服务器。请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接。 (provider: 命名管道提供程序, error: 40 – 无法打开到 SQL Server 的连接)

在sql server configration manager中:

我的问题貌似就是TCP端口不是1433.。。

一次搞懂WCF 配置文件

2011年7月23日 没有评论

<a href=”http://cam.taoke.alimama.com/event.php?pid=mm_12451024_0_0&eventid=100157″ target=”_blank”><img src=’http://img.alimama.cn/topicfile/2008-12-09/12287979286590.gif’></a>

既然来到这里,就安心看完这篇文章。

1.WCF的服务端配置

服务端的配置文件主要包括endpoint、binding、behavior的配置。一个标准的服务端配置文件所包含的主要xml配置节如下所示:
<system.ServiceModel>

<services>
<service>
<endpoint/>
</service>
</services>

<bindings>
<!—定义一个或多个系统提供的binding元素,例如<basicHttpBinding> –>
<!—也可以是自定义的binding元素,如<customBinding>. –>
<binding>
<!—例如<BasicHttpBinding>元素. –>
</binding>
</bindings>

<behaviors>
<!—一个或多个系统提供的behavior元素. –>
<behavior>
<!—例如<throttling>元素. –>
</behavior>
</behaviors>

</system.ServiceModel>
1.1 <services>配置节
在<services>配置节中可以定义多个服务,每一个服务都被放到<service>配置节中,WCF的宿主程序可以通过配置文件找到这些定义的服务并发布这些服务。

<service> 配置节包含name和behaviorConfiguration属性。其中,name配置了实现Service Contract的类型名。类型名必须是完整地包含了命名空间和类型名。而behaviorConfiguration的配置值则与其后 的<behaviors>配置节的内容有关。<endpoint>是<service>配置节的主体,其 中,<endpoint>配置节包含了endpoint的三个组成部分:Address、Binding和Contract。由于具体的 binding配置是在<bindings>配置节中完成,因而,在<endpoint>中配置了 bindingConfiguration属性,指向具体的binding配置。如下所示:
<services>
<service name=”BruceZhang.MyService” behaviorConfiguration=”MyBehavior”>
<endpoint address=”"
binding=”netTcpBinding”
bindingConfiguration=”DuplexBinding”
contract=”BruceZhang.IHello” />
</service>
</services>

我们也可以定义多个endpoint,例如:
<services>
<service
name=”Microsoft.ServiceModel.Samples.CalculatorService”
behaviorConfiguration=”CalculatorServiceBehavior”>
<endpoint address=”"
binding=”wsHttpBinding”
contract=”Microsoft.ServiceModel.Samples.ICalculator” />
<endpoint address=”mex”
binding=”mexHttpBinding”
contract=” Microsoft.ServiceModel.Samples.IMetadataExchange” />
</service>
</services>

如果address值为空,那么endpoint的地址就是默认的基地址(Base Address)。例如ICalculator服务的地址就是http://localhost/servicemodelsamples/service.svc,而IMetadataExchange服务的地址则为http://localhost/servicemodelsamples/service.svc/mex。这里所谓的基地址可以在<service>中通过配置<host>来定义:
<service
name=”Microsoft.ServiceModel.Samples.CalculatorService”
behaviorConfiguration=”CalculatorServiceBehavior”>
<host>
<baseAddresses>
<add baseAddress=
http://localhost/ServiceModelSamples/service.svc”/>
</baseAddresses>
</host>
<endpoint … />
</service>

1.2 <behaviors>配置节

当我们在定义一个实现了Service Contract的类时, binding和address信息是客户端必须知道的,否则无法调用该服务。然而,如果需要指定服务在执行方面的相关特性时,就必须定义服务的 behavior。在WCF中,定义behavior就可以设置服务的运行时属性,甚至于通过自定义behavior插入一些自定义类型。例如通过指定 ServiceMetadataBehavior,可以使WCF服务对外公布Metadata。配置如下:
<behaviors>
<serviceBehaviors>
<behavior name=”metadataSupport”>
<serviceMetadata httpGetEnabled=”true” httpGetUrl=”"/>
</behavior>
<serviceBehaviors>
<behaviors>

在 WCF中,behavior被定义为Attribute,其 中,System.ServiceModel.ServiceBehaviorAttribute和 System.ServiceModel.OperationBehaviorAttribute是最常用的behavior。虽然,behavior作 为Attribute可以通过编程的方式直接施加到服务上,但出于灵活性的考虑,将behavior定义到配置文件中才是最好的设计方式。
利用ServiceBehavior与OperationBehavior可以控制服务的如下属性:
1、 对象实例的生命周期;
2、 并发与异步处理;
3、 配置行为;
4、 事务行为;
5、 序列化行为;
6、 元数据转换;
7、 会话的生命周期;
8、 地址过滤以及消息头的处理;
9、 模拟(Impersonation);

例如,通过ServiceBehavior设置对象实例的生命周期:
<behaviors>
<serviceBehaviors>
<behavior name=”metadataSupport”>
<instanceContextMode httpGetEnabled=”true” httpGetUrl=”"/>
</behavior>
<serviceBehaviors>
<behaviors>

原文:http://www.cnblogs.com/markxue/archive/2009/01/20/1378696.html

分类: 叽歪生活 标签: ,

WCF配置文件全攻略

2011年7月23日 没有评论

当今的软件系统开发,如果没有配置文件几乎是不可想象的事。没有配置文件,软件如何按照用户的要求对功能进行定制?没有配置文件,在对软件进行配置 安装的时候如何根据具体的硬软件环境进行修改?最重要的是没有配置文件,该如何应对软件系统的可扩展要求?不知不觉地,配置文件的编写与管理竟然成了软件 开发的重中之重。

WCF作为分布式开发的基础框架,在定义服务以及定义消费服务的客户端时,都使用了配置文件的方法。虽然WCF也提供硬 编程的方式,通过在代码中直接设置相关对象的属性来完成服务端与客户端的配置,然而这种方式并不利于后期的更改。无疑,配置文件为WCF带来了软件开发的 灵活性,它的使用也是WCF开发过程中最频繁的。

WCF的配置文件共分为两部分:服务端配置与客户端配置。两者由于功能的不同,在配置文件的使用上也略有不同。

1.WCF的服务端配置

服务端的配置文件主要包括endpoint、binding、behavior的配置。一个标准的服务端配置文件所包含的主要xml配置节如下所示:
<system.ServiceModel>

<services>
<service>
<endpoint/>
</service>
</services>

<bindings>
<!—定义一个或多个系统提供的binding元素,例如<basicHttpBinding> –>
<!—也可以是自定义的binding元素,如<customBinding>. –>
<binding>
<!—例如<BasicHttpBinding>元素. –>
</binding>
</bindings>

<behaviors>
<!—一个或多个系统提供的behavior元素. –>
<behavior>
<!—例如<throttling>元素. –>
</behavior>
</behaviors>

</system.ServiceModel>
1.1 <services>配置节
在<services>配置节中可以定义多个服务,每一个服务都被放到<service>配置节中,WCF的宿主程序可以通过配置文件找到这些定义的服务并发布这些服务。

<service> 配置节包含name和behaviorConfiguration属性。其中,name配置了实现Service Contract的类型名。类型名必须是完整地包含了命名空间和类型名。而behaviorConfiguration的配置值则与其后 的<behaviors>配置节的内容有关。<endpoint>是<service>配置节的主体,其 中,<endpoint>配置节包含了endpoint的三个组成部分:Address、Binding和Contract。由于具体的 binding配置是在<bindings>配置节中完成,因而,在<endpoint>中配置了 bindingConfiguration属性,指向具体的binding配置。如下所示:
<services>
<service name=”BruceZhang.MyService” behaviorConfiguration=”MyBehavior”>
<endpoint address=”"
binding=”netTcpBinding”
bindingConfiguration=”DuplexBinding”
contract=”BruceZhang.IHello” />
</service>
</services>

我们也可以定义多个endpoint,例如:
<services>
<service
name=”Microsoft.ServiceModel.Samples.CalculatorService”
behaviorConfiguration=”CalculatorServiceBehavior”>
<endpoint address=”"
binding=”wsHttpBinding”
contract=”Microsoft.ServiceModel.Samples.ICalculator” />
<endpoint address=”mex”
binding=”mexHttpBinding”
contract=” Microsoft.ServiceModel.Samples.IMetadataExchange” />
</service>
</services>

如果address值为空,那么endpoint的地址就是默认的基地址(Base Address)。例如ICalculator服务的地址就是http://localhost/servicemodelsamples/service.svc,而IMetadataExchange服务的地址则为http://localhost/servicemodelsamples/service.svc/mex。这里所谓的基地址可以在<service>中通过配置<host>来定义:
<service
name=”Microsoft.ServiceModel.Samples.CalculatorService”
behaviorConfiguration=”CalculatorServiceBehavior”>
<host>
<baseAddresses>
<add baseAddress=
http://localhost/ServiceModelSamples/service.svc”/>
</baseAddresses>
</host>
<endpoint … />
</service>

1.2 <behaviors>配置节

当我们在定义一个实现了Service Contract的类时, binding和address信息是客户端必须知道的,否则无法调用该服务。然而,如果需要指定服务在执行方面的相关特性时,就必须定义服务的 behavior。在WCF中,定义behavior就可以设置服务的运行时属性,甚至于通过自定义behavior插入一些自定义类型。例如通过指定 ServiceMetadataBehavior,可以使WCF服务对外公布Metadata。配置如下:
<behaviors>
<serviceBehaviors>
<behavior name=”metadataSupport”>
<serviceMetadata httpGetEnabled=”true” httpGetUrl=”"/>
</behavior>
<serviceBehaviors>
<behaviors>

在 WCF中,behavior被定义为Attribute,其 中,System.ServiceModel.ServiceBehaviorAttribute和 System.ServiceModel.OperationBehaviorAttribute是最常用的behavior。虽然,behavior作 为Attribute可以通过编程的方式直接施加到服务上,但出于灵活性的考虑,将behavior定义到配置文件中才是最好的设计方式。
利用ServiceBehavior与OperationBehavior可以控制服务的如下属性:
1、 对象实例的生命周期;
2、 并发与异步处理;
3、 配置行为;
4、 事务行为;
5、 序列化行为;
6、 元数据转换;
7、 会话的生命周期;
8、 地址过滤以及消息头的处理;
9、 模拟(Impersonation);

例如,通过ServiceBehavior设置对象实例的生命周期:
<behaviors>
<serviceBehaviors>
<behavior name=”metadataSupport”>
<instanceContextMode httpGetEnabled=”true” httpGetUrl=”"/>
</behavior>
<serviceBehaviors>
<behaviors>

原文:http://www.cnblogs.com/wayfarer/archive/2007/08/24/867987.html

分类: 叽歪生活 标签: ,

Save & Read Image From Database

2011年7月23日 3 条评论

ASP.NET provides a simple mechanism to upload image files to a database, like SQL Server. The images can be stored in a database table attribute that is of image data-type.

You can use the following SQL statement to create a table that can store image files:

create table myimages
(
imgid int identity(1,1) primary key,
imgname varchar(30) null,
imgfile image not null,
imgtype varchar(30) null
)

In the preceding code, the table attributes are:

  • imgid: To store the id of the image and it is the primary key of the table.
  • imgname: To store a name of the image.
  • imgfile: To store binary image data.
  • imgtype: To store the content type of the image

The images from the Web form can be loaded in the preceding database table. The uploading of image file from the web form can be categorized in the following tasks:

  1. Creating a Web form for uploading the image files.
  2. Uploading image files to database.

Creating the Web form for uploading the image files

The HTML form that uploads the image files to a database should meet the following requirements:

  • Use multipart/form-data encryption
  • Use the POST method.

You can use the following code snippet to create a form to up load the images:

<form enctype=”multipart/form-data” id=”Form2″ method=”post” runat=”server”>
<h3> Demo on working with image files</h3>
<asp:Label id=”Label1″ style=”Z-INDEX: 101; LEFT: 56px; POSITION: absolute; TOP: 120px” runat=”server”>Enter File name</asp:Label>
<asp:Button id=”Button2″ style=”Z-INDEX: 107; LEFT: 248px; POSITION: absolute; TOP: 264px” runat=”server” Text=”View images” Width=”96px”>
<asp:Button id=”Button1″ style=”Z-INDEX: 106; LEFT: 248px; POSITION: absolute; TOP: 216px” runat=”server” Text=”Upload Me”> <input id=”upload_file” type=”file” runat=”server” style=”Z-INDEX: 105; LEFT: 256px; POSITION: absolute; TOP: 160px”>
<asp:TextBox id=”txtimgname” style=”Z-INDEX: 102; LEFT: 256px; POSITION: absolute; TOP: 120px” runat=”server”>
</asp:TextBox>
</form>

In the preceding code, the enctype attribute notifies the server that the binary data will be uploaded. The form has a file field control by the name upload_file, which you can use to browse and locate the file. The form also has two button controls, one to upload and one to view. The interface looks like as shown in the figure:

Web Form to upload and retrieve image from SQL Server database

Uploading Image File to a Database

When the user clicks on the Upload me button, an event handler is invoked. In the event handler you can add the following code to upload the file in the database:

private void Button1_Click(object sender, System.EventArgs e)
{
Stream img_strm = upload_file.PostedFile.InputStream;
//Retrieving the length of the file to upload
int img_len = upload_file.PostedFile.ContentLength;
//retrieving the type of the file to upload
string strtype = upload_file.PostedFile.ContentType.ToString();
string strname = txtimgname.Text.ToString();
byte[] imgdata = new byte[img_len];
int n = img_strm.Read(imgdata, 0, img_len);
int result = SaveToDB(strname, imgdata, strtype);
}

In the preceding code, there are three main pieces of data that are important for uploading image:

Content-Type (strtype)
Name (strname)
ImageData (imgdata)

The preceding code the file to be uploaded is sptored in img_strm, object of stream class. In img_strm the file is stored in bimary format You should convert it to byte array before uploading it into database. The following statement of the preceding code snippet shows how the file is converted into byte array:

int n=img_strm.read(imgdata,0,imglen)

The Stream object provides the Read() method to convert file from binary to byte array. It accepts three paramters

  • buffer: Specifies an array of bytes.
  • Offset: Specifies the byte in the buffer from where the storing of data will begin.
  • Count: Specifies the maximum number of bytes to be read from the current stream.

You can download the rest of the code form the link given at the end of the article.

Retrieving an image from Database

 

The main code performing this functionality is given below. Its the event handler for the “view image” event. The image name that is written in the text box is displayed.

private void Button2_Click(object sender, System.EventArgs e)
{
connection.Open();
SqlCommand command1 = new SqlCommand(“select imgfile from myimages where imgname=@param”, connection);
SqlParameter myparam = command1.Parameters.Add(“@param”, SqlDbType.NVarChar, 30);
myparam.Value = txtimgname.Text;
byte[] img = (byte[])command1.ExecuteScalar();
MemoryStream str = new MemoryStream();
str.Write(img, 0, img.Length);
Bitmap bit = new Bitmap(str);
Response.ContentType = “image/jpeg”;//or you can select your imagetype from database or directly write it here
bit.Save(Response.OutputStream, ImageFormat.Jpeg);
connection.Close();
}

You can download example Save & Retrieve Images From Database Project, used in this tutorial.

source URL:http://www.beansoftware.com/ASP.NET-Tutorials/Save-Read-Image-Database.aspx

asp.net上传图片并保存到数据库中

2011年7月23日 没有评论

数据库中保存的是图像的数据。

前台:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”UploadWork.aspx.cs” Inherits=”meishuguan.UploadWork” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
<style type=”text/css”>
.style1
{
width: 100%;
}
.style2
{
height: 25px;
}
</style>
</head>
<body>
<script type=”text/javascript”>
function checkData() {
var fileName = document.getElementById(“UploadImage”).value;
alert(fileName);
//var fileName = document.getElementsByName(“UploadImage”).value;
if (fileName == “”)
return;
var exName = fileName.substr(fileName.lastIndexOf(“.”) + 1).toUpperCase();
//alert(exName)
if (exName == “JPG” || exName == “BMP” || exName == “GIF”) {
var imgpath = fileName.src;
alert(imgpath);
document.getElementById(“PreviewImage”).src = imgpath;
document.write(fileName);
}
else {
alert(“请选择正确的图片文件”)
document.getElementById(“PreviewImage”).value = “”
}
}
</script>
<form method=”post” runat=”server”>
<div>
<table>
<tr>
<td>
<asp:Label ID=”MessageLabel” runat=”server”></asp:Label>
</td>
<td>

</td>
</tr>
<tr>
<td>
<input id=”UploadImage” name = “UploadImage” type=”file” runat=”server” onchange=”checkdata()” />
</td>
<td>

<img id=”PreviewImage” alt=”" src=”" style=”height: 80px; width: 80px” /></td>
</tr>
<tr>
<td>
<asp:Button ID=”UploadButton” runat=”server” Text=”确定” OnClick=”UploadButton_Click” />
</td>
<td>

</td>
</tr>
</table>
</div>
</form>
</body>
</html>

 

后台:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
namespace meishuguan
{
public partial class UploadWork : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
{
HttpPostedFile UpFile = UploadImage.PostedFile;
int ImageLength = UpFile.ContentLength;
if (ImageLength == 0)
{
MessageLabel.Text = “请选择要上传的图片”;
return;
}
if (ImageLength > Int32.Parse(Application["MaxImageLength"].ToString()))
{
MessageLabel.Text = “图片大小不能大于2M”;
return;
}
Stream ImageStream = UpFile.InputStream;
Byte[] ImageByte = new Byte[ImageLength];
ImageStream.Read(ImageByte, 0, ImageLength);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string sqlstring = “insert into [Work](MID,image,length) values(@MID,@image,@length)”;
SqlCommand command = new SqlCommand(sqlstring, connection);
command.Parameters.Add(“@MID”, System.Data.SqlDbType.Int).Value = Session["MID"].ToString();
command.Parameters.Add(“@image”, System.Data.SqlDbType.Image, ImageLength).Value = ImageByte;
command.Parameters.Add(“@length”, System.Data.SqlDbType.Int).Value = ImageLength;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
MessageLabel.Text = “图片上传成功”;
}
}
}