junwei's profileRichard's footprint on ....PhotosBlogListsMore ![]() | Help |
|
May 30 System.Threading.TimerIn one of our system, there is a task which demands to check the incoming mail task periodically and send it out if any. Since it is a sole task, no need to much communicated heavily between threads, just scan the database mail table to pull out these task and send. Compared the currently existing three different APIs in .NET, one is mainly for windows form application, one is for accurate and complex server multiplethread application, and the third one is the lightweight timer for simple thread task, it is System.Threading.Timer. I chose the last one as my solution. Here I put the presudo codes for further reference.
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(WorkerClass.ExecuteMailTask));
timer.Change(1000,0); // specify start timer after 1 second
...
in my WorkerClass, I define one static method ExecuteMailTask to stop timer temporarily and execute the mail task. the following is the preseudo codes
ExecuteMailTask(object state)
{
Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +"mail monitor task is running on thread #"+Thread.CurrentThread.ManagedThreadId);
System.Threading.Timer t = (System.Threading.Timer)state; t.Change(Timeout.Infinite, Timeout.Infinite);// first stop the timer teporarily
... // necessary codes to pull out mail data
t.Change(0,20000); //restart the timer
}
I have omitted the exeption handling codes, in a product enviroment, wrap above codes in a try ...catch.. finally block will be an apropriate choice when robustness is considered.
April 08 FilegroupThe first edition of SQLServer I used is SQLServer 2000. Filegroup had existed at that time, but actually I don't start to explore this feature until these several days. Under default circumstance, the database engine would create one database data file and one log file both of which belong to the PRIMARY filegroup which is also the default filegroup if not specified. The main purpose of employing filegroup is to ease the burden of the database management typically including backup&restore activities. Filegroup usage with multiple disk drivers will gain performance improvement, for example, you have the sample table data spread accross three data file, A.ndf, B.ndf and C.ndf all of which reside in the same filegroup and have each of file reside on different disk driver. Then you will gain better I/O capacity and performance when the sample table data is accessed since the multiple disk heads will in paralle read these 3 drives. That's the reason behind the scene that employing filegroup improve performance.
Also you possibly use filegroup when do table partition during which you first create partition function to designate the partition range, then you create partition schema use the first steps' partition function and direct the database engine that data should go to different filegroups, thirdly you corelates the schema with the concreate table.
Go over the syntax for adding or modify filegroup(file)
use master;
go;
alter testdb;
add filegroup FG_1;
modify filegroup FG_1 default;
add file
(
name=Data1
filename=E:\demo\fg.ndf
size=10MB
maxsize=500MB
filegrowth=10MB
),
(
name=Data2
...
) to filegroup FG_1 March 24 positioned elementI am involved in the div+css layout design since it is so popular and is becoming standard for web front end UI design. Today I reread thru the 9th section of CSS2 on w3.org. this section is focus on the visual formatting model one of which is about positioned element typically about relative&absolute position. Here are several important statements excerpt from this section.
1. The containing block of one positioned box is established by the nearest positioned ancestor, or if none exists, the initial containing block.
so what's a positioned box? normally it is a block element like div with position css style attribute set to non static value. What's initial containing block? also in the above doc, it says the root of document tree generates the containing block, aka initial containing block.
2. In CSS2.1, a box may be laid out according three positioning schemes, normal flow, float and absolutely positioning. the relative positioning is included in the normal flow scheme, in the absolute positioning scheme, a box is removed from the normal flow entirely and assigned a position with respect to its containing block.
March 23 System.Data.SqlTypesDuring development of our management system, I built an utility class to read sql statement from several xml files. Each function module of system will be stored as one standlone file as such to ease maintenance task. In each file, I predefined sql statement schema for stored procedures and ordinary statements. To be concreate, each statement will correspond to one single element which has several attributes to describe its functionality and comments and has child element called params which has cascading child element param which in turn has four attribute to describe the parameter's name, size, type. All these seemed good and it worked fine for now. The problem was I used string value to assign this type attribute, though data type can be CLR's, can be SqlServer's, can be data provider's. Which one I should choose wisely? Today, I reread from MSDN about data type of CLR & native data type of SQL Server 2005 & mapped data type of Sqlserver data provider. Here I exepted some important words for memo:
The System.Data.SqlTypes namespace provide class for native data type of Sql Server, such as SqlDecimal, SqlDateTime, SqlString. The classes under this namespace have corresponding native data type of Sql Server and yield better performance than SqlDbType enumeration since behind the scene those data type conversion used SqlXXX types.
It's clear now. February 28 Lumisoft.Net & network security policyThis week, my focus and task is to test email attachment parsing functionality of our project. In this module, we used the third part open source software-LumiSoft.Net to monitor some designated email account, in a infinite loop, this component will connect to the email server with the correct email user account and password supplied, when the email arrived inbound the mailbox, this component will read the mail and save the annexes of mail to local directory, then the contents of the annex will be parsed by another module. Not difficult, is not it? initially I did think so.
quickly I finished my code:
Pop3_Client client=new Pop3_Client();
client.Connect("emailserverIpOrDomainname","port",false); --the third parameter designates whether use SSL connection
client.Authenticate("validuseremailaccount","password",false);
...
The interesting thing begin to happen immediately after I deployed my app into LAN circumstance. The app can correctly connect to our company's external email server, exchange server2007 and get the attachments. but it failed when testing in company's internal email server, exchange server2003. The thrown exception said this account is prohibited to log on to this computer. At first, I suspected that it must be related to email server settings. but I can't figure out concretely where, since I am not familiar to network security very much. It turned out finally that it is company's network security strategy causes this problem. Then internal LAN is based domain, the staff no of each emplyee is banged with his computer and it is not allowed that some employee log into the domain from other computer with his staff no. and the email server assigns every employee email account using his staff no, but on the email server, there is an option stating that this account which happens to be the account I used in code to connect to internal exchange server is allowed only.
This is a good lesson. I think. September 18 Unit Test is not easyI know that I should provide all necessary info for the function and i am able to do unit test comfortably. but under complex circumstance i don't know how, could you please shed light on it? My app contains three projects with in a solution,one is for web site, one is a class library project for business logic tier and the other is also class library project for data access tier. I paste my code here: Business Logic Tier: PO.cs public class PO { private PODao dao=new PODao(); public bool InsertPO(POEntity) { ... //some validation logic return dao.InsertPO(POEntity); } }
DataAccess Tier: PODao.cs public class PODao { public bool InsertPO(POEntity) { //use Enterprise Lib to execute database operation Database db = DatabaseFactory.CreateDatabase(); ... //construct DbCommand try{ db.ExecuteNonQuery(cmd); return true; } catch{ //exception logic puts here return false; } } }
Asp.net presentation tier: in the button click event handler on my POSubmit.aspx page,I wrote some codes like the followings: button_click() { POEntity entity=new POEntity(); ....assign POEntity property value from web controls value PO po=new PO(); po.InsertPO(entity); } and I put the connection string info in the web.config file. Now How can I do unit test for this InsertPO method of PO class in the business logic tier? My steps is as followings: first right click on the "InsertPO" method name within VSTS IDE, this will generate plumbing unit test codes as followings for this method
/// <summary> POEntity po = null; // TODO: Initialize to an appropriate value bool expected = true; actual = target.InsertPO(po); Assert.AreEqual(expected, actual, "PO.InsertPO(POEntity) did not return the expected value.");
As you said, I need to provide each information for the function i am testing, I was able to use some fake data to mock POEntity,but this unit test will fail when executing, I think it is that the code highlighted with red color(Database db = DatabaseFactory.CreateDatabase();) caused this unit test fail, because this code will use the connection string info I stored in web.config file to create a instance of Database class, howerver, when executing unit test, it can't get this connection string info. How should I provide such kind of information for my unit test? Actually when doing unit test, I always puzzled how to do with such circumstance. google for unit test, there are a lot of samples demonstrating how to do unit test for a method whose function is calculate sum of two addend and alike, but those samples was not so helpful I think. August 12 Reread asp.net security modelAn old long article from MSDN talked about asp.net security model. I reread it quickly due to current existing project need feeling it was worth reading for each asp.net programmer if you want to deeply understand the security infrastructrue of asp.net.
Although it is an introductory material, I 'd recommand this article
and this one
July 31 An xss samplescenario: some forums without input well validated and guest message is allowed to input.
step:leave the following code snippet
<img src="http://google.com/images/logo.gif" onload="window.location='http://kelekingone.spaces.msn.com'" />
and submit your message. result:each time this message viewed, it will bring you to http://kelekingone.spaces.msn.com. July 27 SET XACT_ABORT ONToday, when I viewed Duwamish source code, I found this sqlserver option. I remembered in my program I always checked the @@error variable and then made decision to make sure the atomicy of the whole transaction. Since there existed this SET XACT_ABORT ON option, I think it can be a better choice because of its elegence and simplicity. April 26 it comes too late!I found the following article on MS support site during sqlserver2000 personal edition setup. It's this article that should have solved one of my problem long before.
Q:Can I rename the server after installing Sqlserver2000?
A:Yes. You can. The Sqlserver2000 service will identify the modified name automatically during its first startup after renaming. But you must do addtional steps to update the sysservers table.
As to the default instance:
sp_dropserver <old_servername>
go sp_addserver <new_servername> , local go As to the named instance:
sp_dropserver <old_servername\instancename>
go sp_addserver <new_servername\instancename> , local go BTW:the MS support site has silverlighted~ March 24 Mind your sqlserver service pack number The other day,when I run my asp.net 2.0 web application, an anoy exception always be thrown stated that "under default setting sqlserver2005 doesn't allow remote connection, Named pipe 40 error". But actually I was connecting to sqlserver 2000.
after a lot of searching, I resolved this problem by updating sqlserver2000 to sp3.
The connetion string i was using is "server=ip;database=dbname;user id=username;password=pwd"
October 30 Trivial Tasks It has been almost 3 weeks since I began to know windows media services. As I dave into this space, It seems that a dead corner appears when considering authentication plug-in. I looked through the media service SDK attentively but found no clue to this problem. Over the last few days, I have frequently accessed the related newsgroups and forums to try to find its corresponding solution. No luck, again. This morning, I opened my mailbox and checked mail as usual. How I was looking forward to receiving several useful discussions!
I described my problem briefly and post it to the newgroup. Since I have to wait 12 hours for the response due to the time zone difference, I began to read others' threads with the intention of whether I could find minimum valuable clue about my problem. Finally, I found that some guy was in the same situation as I did. I quickly replied to him and asked him for his solution, but due to the aforementioned reason, I have to wait until tomorrow morning for the feedback.
Another one said himself that he had implemented the custom plug-in, but can't enable it in media service. He post the related error messages within which the server complained that some dependencies of some assembly missing. I can't remember the error code HRESULT clearly. So I want to reproduce this error on my own system, but another thing happened. I followed the instruction of the SDK, but when I "Add References" to project, the windowsmediaserverice.dll did not appear in the list while the SDK did said this. I had to browse to the folder and selecte manually. But another thing! After I adding necessary import directives, the VS intelligence list functionality did not work. hehe~, so a lot of trouble!
these trivial problems did took me much time. But it is these problems that made me attain experience. Fuslogvw.exe, the assembly loading log tool provided by framework SDK which I have never used proved that it is helpful when debugging or locating such assembly binding problems as
FileNotFoundException, BadImageException and so on. At least, I had no such experience on this a year ago. October 17 Windows Media Service Series (2)Let's resume the explorer to windows media service. After quickly reading media service online book, the summary is:
Typically after you have installed the windows media service, setup a streaming media system is a steps process.
That is all what I have got today. I will keep going on tomorrow~ October 14 To Do Windows Media ServicesMS stated that Windows Media Service had provide perfect solution for Video On Demand situation. Considering our current requirements (a bit like online movie cinema), the most important is that we must install this service on Windows server 2003 prior to delve into it further more. Only do this can we know what functionality it can provider, how far it is away from our requirements. So next week, I will be focus on this task. And another thing I must do is to resume to study the Training cource "How to analysis requirements and define MS solution architects". This course has been divided into several modules. As to me, I would like to study the "Concept Design" module and the "analysis requirements" module. In reality, I always lay me in a situation: so many information around within which only very little I need. I hope to get some instructions and tips about how to do with this situation, what's the criteria of the granulity when dividing related information? October 09 SilverLightThe other day, I saw this piece of news: SilverLight V1.0 had been released. Today I saw that V1.1 beta released news on MS site. So quickly!
This afternoon, I downloaded V1.0 to experiment it. I was told that VSTS SP1 should be installed so that can some VS templates be installed within VS IDE. After long wait and pacience, I downloaded SP1 but failed to installed it cause of unexpected error! Frustrated! Go on, tommorrow! October 02 Precompile Directives And AssertionC# enables developers to use #if precompile directives to state that if some symbol has been defined, then some statement(s) will be executed. It is a common scenario that we always want to do some test by writing some statements when developing program (usually debug mode) but want to remove it after deploying. That's where #if precompile directive can take effect. if we write the following code snippets:
#define DEBUG // this line must be at the most top of the source code file
...
#if DEBUG
Console.WriteLine("DEBUG symbol has been defined!");
#endif
...
the red highlighted code will excute or not in term of whether the DEBUG symbol has been defined.
Assertion enables developers to state that if some condition is satisfied, the execute flow will continue. Otherwise it will pop a window to ask u to debug or retry or ignore it. In this way, we can make sure that some condition must be satified before some given operation. Both the Debug class and the Trace class have an Assert() method to test some condition accepting a boolean value as in parameter, the only difference is that Debug.Assert() overload methods won't evaluated in Release mode resulting in no performance degrade, but Trace.Assert() will be evaluated in both Debug mode and Release mode resulting in some minor performance overhead. Assume the folowing codes:
...
int i=0;
...
Debug.Assert(i==5);
Console.WriteLine("i detected to equal to 5");
...
if we must assure that some conditon must be satisfied before some operation, we can use assertion to meet the need.
September 21 FormsAuthenticationThis morning, when I debug my web app, I found a strange phenomenon. My web app used forms authentication, but after login from login page, There will be two identical authentication cookies issued along with server response. The partial authentication section is as following in web.config:
<authentication mode="forms">
<forms loginUrl="login.aspx" path="/" ...>
</forms>
</authentication>
<authorization>
<deny user="?"/>
</authorization>
Originally I wrote the following codes:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,userName,DateTime.Now,DateTime.Now.AddMinutes,false,"");
string encryptedToken = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsAuthName, encryptedToken));
FormsAuthentication.RedirectFromLoginPage(userName,false);
I started a tcp monitor and found that two Set-Cookie http header sent to client along with the response, after reading MS RedirectFromLoginPage API doc which states that this method will auto call SetAuthCookie method to issue an authentication cookie and append it to response cookie collection! That's why there are two Set-Cookie header exists.
So in this case, I have to code like this:
Response.Redirect(FormsAuthentication.GetDefaultUrl(userName,false)); // right way
instead of the codes the bold red line shows. And in the subsequent request, this authentication cookie will attach to each request to indicate that one user has been authenticated within a session. If you use tcp monitor, you will see that each subsequent request uses a Cookie http header to pertain this value.
And another tip: this kind of cookie is session cookies, it was stored in memory and when session expired or when browser window is closed, it will be removed from browser. September 06 Auto generating Visio diagram I knew a bit VSTO, but I have never explorered it further. Because of a VBA project, I began to utilitize this tech. It's required that visio diagrams must be generated autmatically against data stored as plain text, or in database, or other forms. Originally I got no clue about that. What I was confused is how such text data was converted to a diagram. After searching, I got some tutorial material on this, especially materials from MSDN. There is a standlone visio SDK downloadable freely. It is a good place to start. VBA usage in visio is also talked about. August 26 GlobalizationThe day before yesterday, Customers report that our app throw exception with a message saying that string was not recongnized as a valid datetime string when excecuting a search by specifying a datetime filter. After checking the app log, I found that on our server output culture info name "zh-CN", but on custom server output "en-GB". That made me delve into the DateTime type API, in turn, found that its ToString overloaded methods and Parse method are all associated with a specific culture. and this culture determined such as number format, date format, time format and currency format. If according a culture, a datetime string is valid, when trying to call parse method, the FormatException will be thrown.
It is said in MSDN that you have several ways to resolve this problem:
If you don't designate in any of the above loction, asp.net will provide you a default setting which set culture to "" and set autouserbase to false. Since the invariant culture associates with English language but none of any country/region and has its culture name a empty string. It seems that it should associate with english language. But the fact is on my own machine under IIS it always output "zh-CN" even though I changed it on region options via control panel but under asp.net built in development server, each time I change the region setting, it will reflect what I made. So confused! |
|
|