Archive for August, 2009


NET Error Message:

System.BadImageFormatException was unhandled

How to Copy / Extract DLL from GAC

I was successfully get the DLL with below step in Win7,

Note:
There is no GAC folder if you access with Windows File Explore. Only avaiable with Command line.

  1. Open command prompt and go to c:\windows\assembly\gac
  2. Required dll will be in form of a directory, change directory to to the dll (cd {dll name})
  3. Check directory for folder name (dir)
  4. Change directory to folder with long name
  5. You will get the dll in this folder
  6. Run copy command to copy to your desired directory

Have fun.

And you can using following code to use a GAC assembly,

Background (steps to put a DLL in GAC)
First, in the command prompt, go to the folder in which the project DLL is saved. Then, create a strong name for that DLL by using the command sn -k [strong name.snk]. Then, put that strong name in the [assembly: AssemblyKeyFile("strongnamepath")] line in assemblinfo.cs, and build that project. Again in command prompt, type gacutil /i [assemblyname]. Now, the DLL is moved to GAC. In the code available for download, you will find out how to use the GAC DLL.

Using the code
You need to move the correct DLL to the GAC by following the above steps. In our example, PutitinGAC is the DLL to be moved to GAC.

The first step to do to refer a DLL in GAC is to assign it to the local assembly object fromGAC. While loading, the DLL version number and public key token should match that of the DLL in the GAC (c:\Winnt\assembly). In the DLL’s properties, you can find the public key and version details.

[code:c#]
Assembly fromGAC = Assembly.Load("PutitinGAC, " +

Sina股票数据接口, 实时股票数据接口大全

股票数据的获取目前有如下两种方法可以获取:
1. http/javascript接口取数据
2. web-service接口

1.http/javascript接口取数据

1.1Sina股票数据接口

以大秦铁路(股票代码:601006)为例,如果要获取它的最新行情,只需访问新浪的股票数据
接口:

http://hq.sinajs.cn/list=sh601006

这个url会返回一串文本,例如:

var hq_str_sh601006=”大秦铁路, 27.55, 27.25, 26.91, 27.55, 26.20, 26.91, 26.92,
22114263, 589824680, 4695, 26.91, 57590, 26.90, 14700, 26.89, 14300,

C#中根据当前时间获取本周,本月,本季度,本月初,本月末等时间段的代码

If your application redirects (navigates) from one ASP.NET Web page to another, you will frequently want to pass information from the source page to the target page. For example, you might have a page where users can select items to purchase. When users submit the page, you want to call another page that can process the information that the user has entered.

You can pass information between pages in various ways, some of which depend on how the redirection occurs. Options include the following:

  • Use a query string, which appends information onto the URL of the target page. You can use a query string when using a HyperLink [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink(VS.80).aspx ] control to build navigation into a page or when you are programmatically redirecting to another page using the Redirect [ http://msdn.microsoft.com/en-us/library/t9dwyts4(VS.80).aspx ] method.

    Passing values in a query string works even if the pages are not in the same Web application; it also works if you want to pass information to a page that is not an ASP.NET Web page. If the target page is an ASP.NET Web page, you can read the value of the query string out of the QueryString [ http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring(VS.80).aspx ] property of the HttpRequest [ http://msdn.microsoft.com/en-us/library/system.web.httprequest(VS.80).aspx ] object.

    NoteNote

    Never pass sensitive data using a query string, because the information is visible to users and can easily be modified, thus representing a potential security risk.

  • Use session state to store information that is then accessible to all ASP.NET Web pages in the current application. However, this takes server memory, and the information is stored until the session expires, which can be more overhead than you want for simply passing information to the next page. For details, see ASP.NET State Management Overview [ http://msdn.microsoft.com/en-us/library/75x4ha6s(VS.80).aspx ] .

  • On the target page, read control values and public property values directly out of the source page. This strategy works in two situations: when the source page cross-posts to the target page (for more information, see How to: Post ASP.NET Web Pages to a Different Page [ http://msdn.microsoft.com/en-us/library/ms178140(VS.80).aspx ] ), and when you call the Transfer [ http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer(VS.80).aspx ] method to transfer execution from the source to the target page on the server. The strategy of reading values directly from the source page is described in this topic.

Getting Public Property Values from the Source Page

If you are designing the source page specifically for sharing information with target pages, and both pages are ASP.NET Web pages, in the source page you can add public properties that expose information you want to share between pages. You can then read the values of the properties in the target pages.

NoteNote

You can read source page properties in the target page only if both pages are in the same Web application.

To get public property values from the source page

  1. On the source page, create one or more public properties.

    The following code example shows a property named CurrentCity that exposes the value of a TextBox [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox(VS.80).aspx ] control named textCity.

    Visual Basic
    Public ReadOnly Property CurrentCity() As String
        Get
            Return textCity.Text
        End Get
    End Property

  ASP.Net 1.1后引入了对提交表单自动检查是否存在XSS(跨站脚本攻击)的能力。当用户试图用之类的输入影响页面返回结果的时候,ASP.Net的引擎会引发一个 HttpRequestValidationExceptioin。默认情况下会返回如下文字的页面:

Server Error in ‘/YourApplicationPath’ Application

A potentially dangerous Request.Form value was detected from the client
(txtName=”“).

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (txtName=”“).

….

  这是ASP.Net提供的一个很重要的安全特性。因为很多程序员对安全没有概念,甚至都不知道XSS这种攻击的存在,知道主动去防护的就更少了。ASP.Net在这一点上做到默认安全。这样让对安全不是很了解的程序员依旧可以写出有一定安全防护能力的网站。

  但是,当我Google搜索 HttpRequestValidationException 或者 “A potentially dangerous Request.Form value was detected from the client”的时候,惊奇的发现大部分人给出的解决方案竟然是在ASP.Net页面描述中通过设置 validateRequest=false 来禁用这个特性,而不去关心那个程序员的网站是否真的不需要这个特性。看得我这叫一个胆战心惊。安全意识应该时时刻刻在每一个程序员的心里,不管你对安全的概念了解多少,一个主动的意识在脑子里,你的站点就会安全很多。

  为什么很多程序员想要禁止 validateRequest 呢?有一部分是真的需要用户输入”<>“之类的字符。这就不必说了。还有一部分其实并不是用户允许输入那些容易引起XSS的字符,而是讨厌这种报错的形式,毕竟一大段英文加上一个ASP.Net典型异常错误信息,显得这个站点出错了,而不是用户输入了非法的字符,可是自己又不知道怎么不让它报错,自己来处理报错。

  对于希望很好的处理这个错误信息,而不使用默认ASP.Net异常报错信息的程序员们,你们不要禁用validateRequest=false。

  正确的做法是在你当前页面添加Page_Error()函数,来捕获所有页面处理过程中发生的而没有处理的异常。然后给用户一个合法的报错信息。如果当前页面没有Page_Error(),这个异常将会送到Global.asax的Application_Error()来处理,你也可以在那里写通用的异常报错处理函数。如果两个地方都没有写异常处理函数,才会显示这个默认的报错页面呢。

  举例而言,处理这个异常其实只需要很简短的一小段代码就够了。在页面的Code-behind页面中加入这么一段代码:

protected void Page_Error(object sender, EventArgs e)
{

方法一:
现在假设有两个页面A、B,我们的目的是把A页面的数据提交到B页面。
首先在A页面建立B页面需要访问A页面的数据项的访问属性。

public

Fix solution for Security Exception on Godaddy share hosting

Problem

Some old story: works locally, get’s screwed up on deployment:

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy.

C#中使用SendMessage

在C#中,程序采用了的驱动采用了事件驱动而不是原来的消息驱动,虽然.net框架提供的事件已经十分丰富,但是在以前的系统中定义了丰富的消息对系统的编程提供了方便的实现方法,因此在C#中使用消息有时候还是大大提高编程的效率的。

定义消息

在c#中消息需要定义成windows系统中的原始的6进制数字,比如

const int WM_Lbutton = 0×0; //定义了鼠标的左键点击消息

public const int USER = 0×000 // 是windows系统定义的用户消息

消息发送

消息发送是通过windows提供的API函数SendMessage来实现的它的原型定义为

[DllImport("User.dll",EntryPoint="SendMessage")]

private static extern int SendMessage(

int hWnd,   // handle to destination window

int Msg,    // message

int wParam, // first message parameter

int lParam // second message parameter

);

消息的接受

在C#中,任何一个窗口都有也消息的接收处理函数,就是defproc函数

你可以在form中重载该函数来处理消息

protected override void DefWndProc ( ref System.WinForms.Message m )

{

switch(m.msg)

{

case WM_Lbutton :

///string与MFC中的CString的Format函数的使用方法有所不同

string message = string.Format(“收到消息!参数为:{0},{}”,m.wParam,m.lParam);

MessageBox.Show(message);///显示一个消息框

break;

default:

base.DefWndProc(ref m);///调用基类函数处理非自定义消息。

break;

}

}

其实,C#中的事件也是通过封装系统消息来实现的,如果你在DefWndProc函数中不处理该

那么,他会交给系统来处理该消息,系统便会通过代理来实现鼠标单击的处理函数,因此你可以通过

defproc函数来拦截消息,比如你想拦截某个按钮的单击消息

C#中其他的消息处理方法

在C#中有的时候需要对控件的消息进行预处理,比如你用owc的spreedsheet控件来处理Excel文件,你不想让用户可以随便选中

数据进行编辑,你就可以屏蔽掉鼠标事件,这个时候就必须拦截系统预先定义好的事件(这在MFC中称为子类化),你可以通过C#提供的一个接口

IMessageFilter来实现消息的过滤

public class Form: System.Windows.Forms.Form,IMessageFilter

{

const int WM_MOUSEMOVE = 0×00

public bool PreFilterMessage(ref Message m) 

{  Keys keyCode = (Keys)(int)m.WParam & Keys.KeyCode; 

if(m.Msg == m.Msg==WM_MOUSEMOVE) //||m.Msg == WM_LBUTTONDOWN

{

//MessageBox.Show(“Ignoring Escape…”);  

return true; 

} 

return false; 
}
}

备注:主要描述在调用API函数SendMessage时数据类型的转换。


SendMessage是一个在user32.dll中声明的API函数,在C#中导入如下:

using System.Runtime.InteropServices;
[DllImport("user32.dll", EntryPoint="SendMessageA")]public static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

本文描述其参数 lParam 的用法,主要是数据类型之间的转化

● 一种最简单的处理方式是声明多个SendMessage函数(overload),用所需的数据类型直接替换IntPtr。例如:

//声明:[DllImport("user32.dll", EntryPoint="SendMessageA")]private static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam,  string lParam);[DllImport("user32.dll", EntryPoint="SendMessageA")]private static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam,  ref Rectangle lParam);
//调用:string s = "hello, floodzhu";SendMessage(this.textBox1.Handle, WM_SETTEXT, IntPtr.Zero, s);

Rectangle rect = new Rectangle();SendMessage(this.richTextBox1.Handle, EM_GETRECT, (IntPtr)0, ref rect);

● 对要求返回字符串的类型(out string)可以用 StringBuilder 代替,此时不需要 out/ref。例如:

[DllImport("user32.dll", EntryPoint="SendMessageA")]private static extern int SendMessage (IntPtr hwnd, int wMsg, int wParam, StringBuilder lParam);private void button1_Click(object sender, System.EventArgs e){    const int buffer_size = 1024;    StringBuilder buffer = new StringBuilder(buffer_size);    SendMessage(this.textBox1.Handle, WM_GETTEXT, buffer_size, buffer);    //MessageBox.Show(buffer.ToString());}

● 如果想用 InPtr 类型统一处理的话,可以借助于 Marshal 或者 GCHandle 的相关方法。例如:

[DllImport("user32.dll", EntryPoint="SendMessageA")]private static extern int SendMessage (IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

private void button2_Click(object sender, System.EventArgs e){    Rectangle rect = new Rectangle();    IntPtr buffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Rectangle)));    Marshal.StructureToPtr(rect, buffer ,true);

    SendMessage(this.richTextBox1.Handle, EM_GETRECT, (IntPtr)0, buffer);

    rect = (Rectangle)Marshal.PtrToStructure(buffer, typeof(Rectangle));

    Marshal.FreeHGlobal(buffer);}

或者

private void button2_Click(object sender, System.EventArgs e){    Rectangle rect = new Rectangle();    GCHandle gch = GCHandle.Alloc(rect);

    SendMessage(this.richTextBox1.Handle, EM_GETRECT, (IntPtr)0, (IntPtr)gch);    rect = (Rectangle)Marshal.PtrToStructure((IntPtr)gch, typeof(Rectangle));

    gch.Free();}

SendMessage-------PostMessage1、首先是返回值意义的区别,我们先看一下 MSDN 里的声明:

LRESULT SendMessage(

         HWND hWnd,

         UINT Msg,

         WPARAM wParam,

         LPARAM lParam

);

BOOL PostMessage(

         HWND hWnd,

         UINT Msg,

         WPARAM wParam,

         LPARAM lParam

);

  其中 4 个参数的意义是一样的,返回值类型不同(其实从数据上看他们一样是一个 32 位的数,只是意义不一样),LRESULT 表示的是消息被处理后的返回值,BOOL 表示的是消息是不是 Post 成功。

2、PostMessage 是异步的,SendMessage 是同步的。

  PostMessage 只把消息放入队列,不管消息是否被处理就返回,消息可能不被处理;而 SendMessage 等待消息被处理完了之后才返回,如果消息不被处理,发送消息的线程将一直被阻塞。

3、如果在同一个线程内,SendMessage 发送消息时,由 USER32.DLL模块调用目标窗口的消息处理程序,并将结果返回。SendMessage 在同一线程中发送消息并不入线程消息队列。PostMessage发送消息时,消息要先放入线程的消息队列,然后通过消息循环分派到目标窗口(DispatchMessage)。

 如果在不同线程内,SendMessage 发送消息到目标窗口所属线程的消息队列,然后发送消息的线程在 USER32.DLL模块内监视和等待消息处理,直到目标窗口处理完返回。SendMessage 在返回前还做了很多工作,比如,响应别的线程向它SendMessage。Post 到别的线程时,最好用 PostThreadMessage 代替PostMessage,PostMessage 的 hWnd 参数可以是 NULL,等效于 PostThreadMessage +GetCurrentThreadId。Post WM_QUIT 时,应使用 PostQuitMessage 代替。

4、系统只整编(marshal)系统消息(0 到 WM_USER 之间的消息),发送用户消息(WM_USER 以上)到别的进程时,需要自己做整编。

  用 PostMessage、SendNotifyMessage、SendMessageCallback 等异步函数发送系统消息时,参数里不可以使用指针,因为发送者并不等待消息的处理就返回,接受者还没处理指针就已经被释放了。

5、在 Windows 2000/XP 里,每个消息队列最多只能存放 10,000 个 Post的消息,超过的还没被处理的将不会被处理,直接丢掉。这个值可以改得更大:[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows] USERPostMessageLimit,最小可以是4000。

PostMessage只负责将消息放到消息队列中,不确定何时及是否处理

    SendMessage要等到受到消息处理的返回码(DWord类型)后才继续

    PostMessage执行后马上返回

    SendMessage必须等到消息被处理后才会返回。

Tip/Trick: Localization and Master Pages

Today, I found a great solution to create Multilingual Websites (Localization)

Powered by WordPress | Theme: Motion by 85ideas.