Friday, September 23, 2005

Theme & Personalization in .Net 2

If you want provide the feature to let user select their own theme. You may need to write your own ProfileProvider and save the setting in users table. Here are my study in Theme & Personalization.
1. Theme
Theme is for the look and feel of web pages. Themes can use CSS files also. Just put the CSS file under specific theme folder, the page will use it.
File structure:
[Web App Root]\App_Themes\Blue\blue.shin
Then you can appay this skin in several way:

//In Single Page

//In Page_PreInit Event
void Page_PreInit(object sender, System.EventArgs e)
{ this.Theme = "Blue";}
2. Personalization
Let's save the Theme setting in Profile. In web.config file, add
〈 profile defaultProvider="myProfileProvider"〉
〈 providers〉
〈 add name="myProfileProvider" type="Corp.Framework.Shared.Security.myProfileProvider, Corp.Framework.Shared" connectionStringName="ConnID"/〉
〈 /providers〉
〈 properties〉
〈 add name="Theme" defaultValue="Blue"/〉
〈 /properties〉
〈 /profile〉

//In Page_PreInit Event, you load user's setting from Profile
void Page_PreInit(object sender, System.EventArgs e)
{
this.Theme = Profile.Theme;
//Page.Theme = (string)HttpContext.Current.Profile["Theme"];
}
3. myProfileProvider
myProfileProvider inherits from the SettingsProvider abstract class, which inherits from the ProviderBase abstract class.
class myProfileProvider : ProfileProvider
{
#region Private Member
private string _applicationName;
#endregion // Private Member

#region Constructor
///
/// Default Constructor
///

public myProfileProvider()
: base()
{
}
#endregion // Constructor
#region Initialize
///
/// Initialize the Profile Provider Class
///

/// Provider name
/// NameValueCollection containing the provider configuration settings
public override void Initialize(string name, NameValueCollection config)
{
}
#endregion //Initialize

#region Get Application Name
public override string ApplicationName
{
get { return _applicationName; }
set { _applicationName = value; }
}
#endregion
#region GetPropertyValues
///
/// Get Property Values
///

/// Context
/// Collection of Property Value
public override SettingsPropertyValueCollection
GetPropertyValues(SettingsContext context,
SettingsPropertyCollection ppc)
{
// In Web form, user login by their email, here username pass the email
string email = (string)context["UserName"];
bool isAuthenticated = (bool)context["IsAuthenticated"];

SettingsPropertyValueCollection svc =
new SettingsPropertyValueCollection();

foreach (SettingsProperty prop in ppc)
{
SettingsPropertyValue pv = new SettingsPropertyValue(prop);
switch (prop.Name)
{
case "Theme":
pv.PropertyValue = GetTheme(email, isAuthenticated, (string)prop.DefaultValue);
break;
default:
throw new ProviderException("Unsupported property.");
}
svc.Add(pv);
}
UpdateActivityDates(email, isAuthenticated, true);
return svc;
}
#endregion //GetPropertyValues

#region SetPropertyValues
///
/// Set Perperty Values
///

/// Context
/// Collection of Property value
public override void SetPropertyValues(SettingsContext context,
SettingsPropertyValueCollection ppvc)
{

}
#endregion //SetPropertyValues


#region UpdateActivityDates
/// Updates the LastActivityDate and LastUpdatedDate values
/// when profile properties are accessed by the
/// GetPropertyValues and SetPropertyValues methods.
/// Passing true as the activityOnly parameter will update
/// only the LastActivityDate.
///

/// Current user's email
/// is Authenticated
/// Activity
private void UpdateActivityDates(string email, bool isAuthenticated, bool activityOnly)
{
DateTime activityDate = DateTime.Now;
}
#endregion //UpdateActivityDates


#region GetTheme
///
/// Retrieves theme from the database during the call to GetPropertyValues.
///

/// Current user's email
/// is Authenticated
///
private string GetTheme(string email, bool isAuthenticated, string defaultTheme)
{
if (!isAuthenticated)
{
return defaultTheme;
}
if (null == email)
throw new ArgumentNullException("email");
// check if username is empty
if (email.Length == 0)
throw new ArgumentException("Argument is empty", "username");
try
{
// create the object manager
IUsersManager usersManager = ManagerFactory.CreateManager(Utilities.PortalConnStringID);
// Validate
IUsers user = usersManager.RetrieveByemail(email);
if (user.IsEmpty)
return defaultTheme;

if (string.IsNullOrEmpty(user.theme))
return defaultTheme;
else
return user.theme;
}
catch
{
throw;
}

}
#endregion
}

Variables in ASP.NET Page

今天花了一个多小时在Debug这个程序
var items = [];
for (int i=0; i〈items.length; i++)
...

浏览器告诉我在line **上Expected ;

知道什么错误了吗? 原来是int i的问题,一会儿用C#,一会儿用Javascript, 把int i和var i混了。害得我好久都没找到问题所在。

客户支持:
今天又花了一天的时间在查一个客户反应的问题:已经有5天时间他们收不到任何Order! 他们的用户网上购物时的信用卡都被Decline!

让他们把Verisign的帐号给我们,上去看了之后,发现所有的Transaction在Verisign上都查不到。而我们这一边则显示Transaction Fail.

以前用VB做的Dll运行几天后总会罢工,这次还以为是同样的问题,重新注册过,还是不行。

在源码取得Credit Card配置前和把信用卡送到Verisign处理之后插入几行跟踪信息,最后才发出问题在他们在5天前改了Verisign的密码,但没有相应在我们的网站上更新密码,所以显示的具体Transaction是“User Authentication Fail".

还好错误不在我们。

Visual Studio 2005 的ReportViewer

Team里用Visual Studio 2005做开发一有三个月了,在这三个月里已经重装了Visual Studio 2005 三次了。先是June 的CTP(Community Technology Preview)版本,发现ReportViewer控件在Design模式下,不管是Win Form还是Web Form属性显示是空的,然后回到Beta 2, 属性显示正常了,但是在Web上Paging和Zoom时会出错,这时刚好要给客户Demo, 只好当夜换成Aug 的CTP版本。这次Paging和Zoom都没有问题,而且还多了导出到PDF和Excel的功能。最后还是有Bug, 当Refresh时ObjectDataSource不会保持ViewState!
这个问题出在我们是程序动态给ObjectDataSource赋值,代码如下:
///
/// Function to create report using ReportViewer in UserControl
///

/// Full path name of .rdlc file
/// The datasource name use in .rdlc file
/// The class name in which provide a method to retrieve data for report
/// The method name in a class to retrieve data for report, this method can return a IList as datasource for report
/// Parameter collection to pass to the method
/// Parameters to pass to report (.rdlc)
public void CreateReport(string reportRdlc, string datasourceName, string dsTypeName, string dsSelectMethod, ParameterCollection dsParamas, Microsoft.Reporting.WebForms.ReportParameter[] repParams)
{
//ObjectDataSource ObjectDataSource1 = new ObjectDataSource(dsTypeName, dsSelectMethod);
hid_dataSourceTypeName = dsTypeName;
hid_dataSourceSelectMethod = dsSelectMethod;
ObjectDataSource1.TypeName = dsTypeName;
ObjectDataSource1.SelectMethod = dsSelectMethod;
//ObjectDataSource1.ID = datasourceName;
ObjectDataSource1.SelectParameters.Clear();
foreach (Parameter p in dsParamas)
{
ObjectDataSource1.SelectParameters.Add(p);
}
ReportViewer1.Attributes.Add("hid_dataSourceTypeName", dsSelectMethod);
ReportViewer1.Attributes.Add("hid_dataSourceSelectMethod", dsSelectMethod);
this.ReportViewer1.LocalReport.DisplayName = reportRdlc.Replace(".rdlc","");
this.ReportViewer1.LocalReport.ReportPath = reportRdlc;

this.ReportViewer1.LocalReport.DataSources.Clear();
Microsoft.Reporting.WebForms.ReportDataSource reportDatasource1 = new Microsoft.Reporting.WebForms.ReportDataSource();
reportDatasource1.Name = datasourceName;
//reportDatasource1.DataSourceId = datasourceName;
reportDatasource1.DataSourceId = ObjectDataSource1.ID;
this.ReportViewer1.LocalReport.DataSources.Add(reportDatasource1);
this.ReportViewer1.LocalReport.SetParameters(repParams);
this.ReportViewer1.LocalReport.Refresh();
}

最后跟踪发现Refresh回到服务器之后,用ReportViewer的Refresh之后,ObjectDataSource的TypeName和SelectMethod的值就丢了。只好给他加个补丁:
protected void ReportViewer1_PreRender(object sender, EventArgs e)
{
ObjectDataSource1.TypeName = hid_dataSourceTypeName;
ObjectDataSource1.SelectMethod = hid_dataSourceSelectMethod;
}
public string hid_dataSourceTypeName
{
get { return Convert.ToString(ViewState["hid_dataSourceTypeName"]); }
set { ViewState["hid_dataSourceTypeName"] = value; }
}
public string hid_dataSourceSelectMethod
{
get { return Convert.ToString(ViewState["hid_dataSourceSelectMethod"]); }
set { ViewState["hid_dataSourceSelectMethod"] = value; }
}
不知道大家有没有其它办法。

Tuesday, June 21, 2005

How to Recover VSS Password

A. If you only want to recover admin password in "common" database, which is default database installed by VSS.
1. Creating a new sourcesafe database or install VSS in another box with a new admin password.
2. Copy the um.dat file over the existing um.dat. And you're able to login as admin with the new password.
3. After you login to "common", you can create new database in VSS.

B. Recover others database's password
1. Create a temporary directory, such as C:\SSTEMP.
2. Print the USERS.TXT file, located in the main directory of the SourceSafe server installation. This will give you a list of current users that you can use later to add back into SourceSafe.
3. Use the Admin tool to create a new database in the temporary folder.
4. Run DDCONV . This executable can be found in the server copy of SourceSafe. If you are running Visual SourceSafe 6.0, DDCONV is located in C:\Program Files\Microsoft Visual Studio\Common\VSS\win32. For example: DDCONV C:\SSTEMP
5. Copy the UM.DAT file from the temporary directory to the SourceSafe data directory. Rename or Delete the RIGHTS.DAT and STATUS.DAT files in the SourceSafe data directory.
6. run the Analyze in the Win32 subdirectory with the -F parameter.
7. Finally, with the administrator program, add all the users back into the system, using the USERS.TXT printout that you made in step 2. If you get "Access denied..." or "...directory already exists..." errors, just click the OK key.


Ref:
http://seclists.org/lists/pen-test/2002/Jun/0052.html
http://dotnet.org.za/gangatha/archive/2005/03/17/15617.aspx
http://dotnet.org.za/gangatha/articles/19185.aspx

Friday, April 08, 2005

VC Malloc/Free new/delete Memory Leak 防止内存泄漏

1. BSTR
BSTR bstrText = ::SysAllocString(L"Test");
SysFreeString(bstrText);

2. char*
char* lpszText2 = _com_util::ConvertBSTRToString(bstrText);
delete[] lpszText2;

lpszText2= new char[500];
free(lpszText2);
lpszText2 = NULL;//p所指向的内存释放, 但p还是指向它, the address of “p” is not changed

A. 由ConvertStringToBSTR分配的内存得手工删除
用BoundsChecker查以下语句有内存泄漏
const char* cstrBaseKeyName;
MSXML2::IXMLDOMDocument2Ptr XmlDocPtr;
MSXML2::IXMLDOMNodePtr foundNode;
...
foundNode=XmlDocPtr->selectSingleNode( _com_util::ConvertStringToBSTR(strBaseKeyName.c_str()) ); //<--Memory Leak Here
...

分析: ConvertStringToBSTR转换会分配一块内存,必须用SysFreeString删除, 修改如下后再检查就正常了
...
BSTR bstr = _com_util::ConvertStringToBSTR(strBaseKeyName.c_str()); foundNode=XmlDocPtr->selectSingleNode( bstr );
::SysFreeString(bstr);
bstr = NULL;
...

B: 由ConvertBSTRToString分配的内存得手工删除
function GetNodeValue(const char* cstrAttributeName, std::string& strAttributeValue)
{
MSXML2::IXMLDOMElementPtr elptr;
...
strAttributeValue = _com_util::ConvertBSTRToString( _bstr_t( elptr->getAttribute(_bstr_t(cstrAttributeName)) ) ); //<--Memory Leak Here
...
}

同样的问题,要修改成
...
char * szChar;
szChar= _com_util::ConvertBSTRToString( _bstr_t( elptr->getAttribute(_bstr_t(cstrAttributeName)) ) );
strAttributeValue=szChar;
delete[] szChar;
...

C. 用new 创建的对象要删除
...
ECBPara *pECBPara;
pECBPara = new ECBPara(pCtxt, dwdiid, dwdfid, dwofid, pin, filepath, fullpath);
result = MyDownload(pECBPara); //<--pECBPara用完后没有删除
...

要加上一句
delete pECBPara;


为了防止发生内存泄漏这样棘手的故障,在VC编程时应当注意遵循几个规范:
其一,如果一个类包含有指针并且分配了指针值,那么就需要构造相应的析构函数以删除该指针;
其二,如果一个函数分配了一块内存并把该内存块返回给调用它的函数使用,那么它返回的必须是一个指针而非一个引用,因为引用不能被程序删除;
其三,即使一个函数分配了一段内存并在同一函数的稍后部分删除了该内存段,也要尽可能将内存块分配到堆栈中;
最后,就是决不要试图改变一个指针值,除非已经删除指针所指的对象或通过数组指向了该指针所指向的内存,而且也不要对new返回的指针进行加1运算。

程序中的内存泄露主要有:
1 用new,malloc,GolbalAlloc等函数分配的队堆内存没有用delete,free,GlobalFree等分别对应的函数释放.这些内存在Debug时候都可以信息的,但只有new在Debug的时候回正确的指出出错的行.因为在Debug版本中Visual C++6.0对new进行了重定义,建议大家分配内存时尽量使用new函数.
2 在绘图时创建的GDI对象没有释放,但如果是使用MFC的GDI对象类,出错的几率会小很多.用new创建的对象会被检测到,而如果使用局部变量,在局部变量失效后自动释放,不会造成内存泄露.
3 创建的线程,窗口等句柄的资源,在失效后没有释放掉.

使用Performance Monitor检测内存泄漏
NT的内核在设计过程中已经加入了系统监视功能,比如CPU的使用率,内存的使用情况,I/O操作的频繁度等都作为一个个Counter,应用程序可以通过读取这些Counter了解整个系统的或者某个进程的运行状况。Performance Monitor就是这样一个应用程序。
为了检测内存泄漏,我们一般可以监视Process对象的Handle Count,Virutal Bytes 和Working Set三个Counter。Handle Count记录了进程当前打开的HANDLE的个数,监视这个Counter有助于我们发现程序是否有Handle泄漏;Virtual Bytes记录了该进程当前在虚地址空间上使用的虚拟内存的大小,NT的内存分配采用了两步走的方法,首先,在虚地址空间上保留一段空间,这时操作系统并没有分配物理内存,只是保留了一段地址。然后,再提交这段空间,这时操作系统才会分配物理内存。所以,Virtual Bytes一般总大于程序的Working Set。监视Virutal Bytes可以帮助我们发现一些系统底层的问题; Working Set记录了操作系统为进程已提交的内存的总量,这个值和程序申请的内存总量存在密切的关系,如果程序存在内存的泄漏这个值会持续增加,但是Virtual Bytes却是跳跃式增加的。
监视这些Counter可以让我们了解进程使用内存的情况,如果发生了泄漏,即使是隐式内存泄漏,这些Counter的值也会持续增加。但是,我们知道有问题却不知道哪里有问题,所以一般使用Performance Monitor来验证是否有内存泄漏,而使用BoundsChecker来找到和解决问题。

Friday, March 11, 2005

Interview Question

http://www.dotnetspider.com/exams/
http://www.geekinterview.com/
http://www.job-interview.net/interviewlib.htm Interview Library
C# Interview Questions
ASP.NET Interview Question
Tough ASP.NET interview questions
http://www.interviewcorner.com/

ASP.NET JOBS
http://www.avanade.com/country/contact.aspx
http://www.navantis.com/english/about/careers/job_dotnet.htm
雅虎公司C#笔试题

==============================================
Design Pattern- Singleton
Private constructor
Static instance and method
lock object

HTTP- Get/Post
GET puts form values (her search criteria) into the URL string
POST embeds the form values inside the body of the HTTP

ViewState: ViewState allows the state of server objects (serializable) to be stored in a hidden field on the page

Remoting
MVC
request
Value/Ref :
OOP/OOD : Inheritance, Polymorphism, Encapsulation
SQL - Cursor - purpose: cursor doing roundtrip it will make network line busy

Class/Object : Class is a blueprint which objects are created
Dispose
Implement IDisposable interface to release unmanaged resource like COM
Void Dispose()

Abstract class/Interface:
Interface cannot provide code of any method or property. All the methods and properties defined in Interface are by default public and abstract. Multiple inheritance is possible in .Net through Interfaces.
Abstract class can provide complete code of methods.

DLL HELL
What is .Net

Box/UnBox

-----------------------------------IBM笔试题---------------------------------------------
1.一个粗细均匀的长直管子,两端开口,里面有4个白球和4个黑球,球的直径、两端开口的直径等于管子的内径,现在白球和黑球的排列是wwwwbbbb,要求不取出任何一个球,使得排列变为bbwwwwbb。
2.一只蜗牛从井底爬到井口,每天白天蜗牛要睡觉,晚上才出来活动,一个晚上蜗牛可以向上爬3尺,但是白天睡觉的时候会往下滑2尺,井深10尺,问蜗牛几天可以爬出来?
3.在一个平面上画1999条直线最多能将这一平面划分成多少个部分?
4.在太平洋的一个小岛上生活着土人,他们不愿意被外人打扰,一天,一个探险家到了岛上,被土人抓住,土人的祭司告诉他,你临死前还可以有一个机会留下一句话,如果这句话是真的,你将被烧死,是假的,你将被五马分尸,可怜的探险家如何才能活下来?
5.怎样种四棵树使得任意两棵树的距离相等。
6.27个小运动员在参加完比赛后,口渴难耐,去小店买饮料,饮料店搞促销,凭三个空瓶可以再换一瓶,他们最少买多少瓶饮料才能保证一人一瓶?
7.有一座山,山上有座庙,只有一条路可以从山上的庙到山脚,每周一早上8点,有一个聪明的小和尚去山下化缘,周二早上8点从山脚回山上的庙里,小和尚的上下山的速度是任意的,在每个往返中,他总是能在周一和周二的同一钟点到达山路上的同一点。例如,有一次他发现星期一的8点30和星期二的8点30他都到了山路靠山脚的3/4的地方,问这是为什么?
8.有两根不均匀分布的香,每根香烧完的时间是一个小时,你能用什么方法来确定一段15分钟的时间?
9. 在房里有三盏灯,房外有三个开关,在房外看不见房内的情况,你只能进门一次,你用什么方法来区分那个开关控制那一盏灯?
10. 一个经理有三个女儿,三个女儿的年龄加起来等于13,三个女儿的年龄乘起来等于经理自己的年龄,有一个下属已知道经理的年龄,但仍不能确定经理三个女儿的年龄,这时经理说只有一个女儿的头发是黑的,然后这个下属就知道了经理三个女儿的年龄。请问三个女儿的年龄分别是多少?为什么
-------------------------------------IBM面试题-------------------------------------------
1. Describe your greatest achievement in the past 4-5 years?
2. What are your short & long term career objectives? What do you think is the most ideal job for you?
3. Why do you want to join IBM? What do you think you can contribute to IBM?
--------------------------------------微软面试题------------------------------------------
  这些问题往往遵循以下一些基本主题:难题、运算、应用、头脑。
1. 你让某些人为你工作了七天,你要用一根金条作为报酬。这根金条要被分成七块。你必须在每天的活干完后交给他们一块。如果你只能将这根金条切割两次,你怎样给这些工人分?
2. 一列火车以每小时15英里的速度离开洛杉矶,朝纽约进发。另外一列火车以每小时20英里的速度离开纽约,朝洛杉矶进发。如果一只每小时飞行25英里的鸟同时离开洛杉矶,在两列火车之间往返飞行,请问当两列火车相遇时,鸟飞了多远?
3. 假设一张圆盘像唱机上的唱盘那样转动。这张盘一半是黑色,一半是白色。假设你有数量不限的一些颜色传感器。要想确定圆盘转动的方向,你需要在它周围摆多少个颜色传感器?它们应该被摆放在什么位置?
4. 假设时钟到了12点。注意时针和分针重叠在一起。在一天之中,时针和分针共重叠多少次?你知道它们重叠时的具体时间吗?
5. 你有两个罐子,分别装着50个红色的玻璃球和50个蓝色的玻璃球。随意拿起一个罐子,然后从里面拿出一个玻璃球。怎样最大程度地增加让自己拿到红球的机会?利用这种方法,拿到红球的几率有多大?
6. 中间只隔一个数字的两个奇数被称为奇数对,比如17和19。证明奇数对之间的数字总能被6整除(假设这两个奇数都大于6)。现在证明没有由三个奇数组成的奇数对。
7. 一个屋子有一个门(门是关闭的)和3盏电灯。屋外有3个开关,分别与这3盏灯相连。你可以随意操纵这些开关,可一旦你将门打开,就不能变换开关了。确定每个开关具体管哪盏灯。
8. 假设你有8个球,其中一个略微重一些,但是找出这个球的惟一方法是将两个球放在天平上对比。最少要称多少次才能找出这个较重的球?
9. 假设你站在镜子前,抬起左手,抬起右手,看看镜中的自己。当你抬起左手时,镜中的自己抬起的似乎是右手。可是当你仰头时,镜中的自己也在仰头,而不是低头。为什么镜子中的影像似乎颠倒了左右,却没有颠倒上下?
10. 你有4瓶药。每粒药丸的重量是固定的,不过其中有一瓶药受到了污染,药丸的重量发生了变化,每个药丸增加了一点重量。你怎样一下子测出哪瓶药是遭到污染的呢?
11. 下面玩一个拆字游戏,所有字母的顺序都被打乱。你要判断这个字是什么。假设这个被拆开的字由5个字母组成:
  A.共有多少种可能的组合方式?   B.如果我们知道是哪5个字母,那会怎么样?   C.找出一种解决这个问题的方法。
12. 某合唱团急需前往演唱会场,途中必需跨过一座桥,四个人从桥的同一端出发,你得帮助他们到达另一端,天色很暗,而他们只有一只手电筒。一次同时最多可以有两人一起过桥,而过桥的时候必须持有手电筒,所以就得有人把手电筒带来带去,来回桥两端。手电筒是不能用丢的方式来传递的。 四个人的步行速度各不同,若两人同行则以较慢者的速度为准。 Bono需花1分钟过桥 Edge需花2分钟过桥 Adam需花5分钟过桥 Larry需花10分钟过桥 问:最快他们四个人可以在多少分钟内全部过桥呢?怎样过?(Micrsoft面试时要求你必须在五分钟内答出来才可能获得聘用)
13. 如果你有一个5夸脱的水桶和一个3夸脱的水桶,如何准确量出4夸脱的水?
14. 你有一袋糖,有红色的,蓝色的,绿色的。闭上眼睛,拿出两块颜色一样的糖,你需要拿多少次才能确保有两块颜色相同的?
15. 如果你有两个桶,一个装的是红色的颜料,另一个装的是蓝色的颜料。你从蓝色颜料桶里舀一杯,倒入红色颜料桶,再从红色颜料桶里舀一杯倒入蓝颜料桶。两个桶中红蓝颜料的比例哪个更高?通过算术的方式来证明这一点。
16. 10个红球,10个白球,两个相同的包,如何放置才能使任意从一包中拿一个球是红球的可能性最高?是多少?
17. 三层、四层二叉树有多少种?
18. 1——100000数列按一定顺序排列,有一个数字排错,如何纠错?写出最好方法。两个数字呢?
19. 烧一根不均匀的绳要用一个小时,如何用它来判断半个小时?(参考答案:两边一起烧)
20. 为什么下水道的盖子是圆的?(从复旦大学一位计算机系教授那里听来的答案:因为如果是方的、长方的或椭圆的,那无聊之徒拎起来它就可以直接扔进地下道啦!但圆形的盖子嘛,就可以避免这种情况了)
21. 有7克、2克砝码各一个,天平一只,如何只用这些物品三次将140克的盐分成50、90克各一份?(怎么,还让说答案?自己动动脑子吧!)

--------------------------------------Intel面试题------------------------------------------
1.设计一个重采样系统,说明如何anti-alias。
2.y1(n)=x(2n),y2(n)=x(n/2),问:
如果y1为周期函数,那么x是否为周期函数? 如果x为周期函数,那么y1是否为周期函数? 如果y2为周期函数,那么x是否为周期函数? 如果x为周期函数,那么y2是否为周期函数?
3.如果模拟信号的带宽为5kHz,要用8k的采样率,怎么办。
4.某个程序在一个嵌入式系统(200M的CPU,50M的SDRAM)中已经最优化了,换到另一个系统(300M的CPU,50M的SDRAM)中运行,还需要优化吗?
5.x^4+a*x^3+x^2+c*x+d最少需要做几次乘法。
6.三个float:a,b,c
问值: (a+b)+c==(b+a)+c (a+b)+c==(a+c)+b
7.把一个链表反向填空。
8.下面哪种排序法对12354最快?
A. quick sort B. buble sort C. merge sort
9.哪种结构平均来讲获取一个值最快?
A. binary tree B. hash table C. stack
10.
#include “stdafx.h” #include struct bit { int a:3; int b:2; int c:3; }; int main(int argc, char* argv[]) { bit s; char *c = (char*)&s; *c = 0x99; cout < < > char *reverse(char* str) { int len=0, i=0; char *pstr=str, *ptemp,*pd; while(*++pstr) len++; pstr--; //ptemp=(char*)malloc(len+1); ptemp=(char*)malloc(len+1); pd=ptemp; while(len--){ *ptemp=*pstr; ptemp++; pstr--; i++; } *ptemp=*pstr; ptemp++; *ptemp=‘’; return pd; } main() { char string[40]= “Hello World!”; char *pstr=string; printf(“%s”, pstr); printf(“%s”, reverse(pstr)); }
--------------------------------------Intel面试题------------------------------------------
1.每天中午从法国塞纳河畔的勒阿佛有一艘轮船驶往美国纽约,在同一时刻纽约也有一艘轮船驶往勒阿佛。已知横渡一次的时间是7天7夜,轮船匀速航行,在同一航线,轮船近距离可见。 请问今天中午从勒阿佛开出的船会遇到几艘从纽约来的船?
2.巴拿赫病故于1945年8月31日。他的出生年份恰好是他在世时某年年龄的平方,问:他是哪年出生的?
--------------------------------------Intel实验室笔试题------------------------------------------
1.写出下列信号的奈亏斯特频率
(1)f(t)=1+cos(2000pait)+sin(4000pait) (2)f(t)=sin(4000pait)/pait (3)f(t)=(sin(4000pait)的平方)/pait
2.有两个线程
void producer() { while(1) { GeneratePacket(); PutPacketIntoBuffer(); Signal(customer); } } void customer() { while(1) { WaitForSignal(); if(PacketInBuffer>10) { ReadAllPackets(); ProcessPackets(); } } }
(1)有没有其他方法可以提高程序的性能 (2)可不可以不使用信号之类的机制来实现上述的功能
3.优化下面的程序
(0)sum=0 (1)I=1 (2)T1=4*I (3)T2=address(A)-4 (4)T3=T2[T1] (5)T4=address(B)-4 (6)T5=4*I (7)T6=T4[T5] (8)T7=T3*T5 (9)sum=sum+T6 (10)I=I+1 (11)IF I http://www.microtrends.net/company/contactus/contact.htm
rolia:nealzhao email: nealzhao@yahoo.com.cn 905-882-9844 Ext:151 ZhaoRui

面试谈工资待遇:
面试的时候很多HR会PUSH你先报价, 或者告诉他们目前工资, 以下是几种比较好的滑头回答
Say something like:

"I am looking for a salary that is in line with my level of experience, education and the current market."

They might then say something like. We need to know what that salary expectation is so that we know if we are going to make an acceptable offer.

A good response then is: "I have done my research and I am confident that as long as you make a fair offer that it will be acceptable."

Basically just keep stressing that you are not looking for an unusually high salary but you also do not want a salary that is below market rate because you want to be happy and remain with the company for a long term.


小公司,无benefits,pay 不高有意发简历给下面的地址,或者给我nealzhao@yahoo.com.cn
At times we have openings for experienced, full-time developers proficient in Visual Studio .Net - Our office is currently located in Richmond Hill.
Candidates must have the following skills and qualifications:
Visual Studio .NET, C#, .Net framework Good understanding of XML Web development experienceExperience working with the SQL language Experience in ADO Experience in Transact-SQL (preferably up to SQL Server 2000) Understanding of Web Services -Multi-tier development experience perferred Understanding and interest in learning Visual Studio.NET in web development In addition, the candidate must demonstrate an ability to learn, show good problem-solving skills, and also have excellent communication habits. They must also be able to understand and implement detailed specifications (as written in a requirements/specifications document).
Please send your resume by email, addressed to the following:
Microtrends Computing Services Inc.Attention: Human Resourcesjobs@microtrends.net

Tuesday, February 08, 2005

MSDE 与 osql

MSDE是一个free的简化版Sql Server, 它没有Enterprice Manager管理介面。所以安装后要用命令行的osql工具做设置。

一、MSDE安装
http://www.microsoft.com/sql/msde/downloads/download.asp 下载,43M,
1.要安裝为默认的实例名,并使用「Windows 的用户验证模式」
setup SAPWD=AStrongSAPwd
2.指定实例名,使用「混合模式」
setup SAPWD=AStrongSAPwd SECURITYMODE=SQL [INSTANCENAME=InstanceName]
3. 测试安装是否成功
osql -S 机器名实例名 -U sa
osql -S 机器名实例名 -E

二、OSQL使用
1. 连接
osql -U userid 用用户userid连接
osql -E 用trusted connection连接
2.选择数据库
use databasename
go
select * from tablename
go
3.建立数据库
create database 数据库名
4. 建立一个新的登陆用户
exec sp_grantlogin 用户名 //用windows验证
EXEC sp_addlogin 用户名,密码 //SQL Server验证
5.上面的用户名只能登陆服务器,还不能对数据库进行操作
EXEC sp_grantdbaccess window用户名, 用户名
6.给用户表访问权限
GRANT SELECT ON tablename TO username
GRANT UPDATE ON tablename TO username
GRANT DELETE ON tablename TO username
7.更改密码
exec sp_password 旧密码,新密码,用户名

Friday, January 14, 2005

.Net Programming

Tech Blogs
http://dflying.cnblogs.com/
Scott's SP.NET 2.0 Tips, Tricks, Recipes and Gotchas


.NET的重用单元叫集合(assembly). 因此一个集号可认为是--个组件;.NET和C#中的任何程序部包含一个或多个集合. 集会是一个逻辑性自描述性包;它包含MSIL, 元数据和可选资源.在.Net下编写的任何程序,不管它是一个重用的组件还是一个独立的运行控序.它都是一个集合;




1. Regulation
public static bool isEmail(string inputEmail)
{
//inputEmail = NulltoString(inputEmail);
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}


2. Create cryptographic random password salt number
public static string CreatePwdSalt()
{
// salt size
const int saltSize = 6;

// generate a cryptographic random number using the cryptographic
// service provider
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[saltSize];
rng.GetBytes(buff);

// return the Base64 string representation of the random number
return Convert.ToBase64String(buff);
}



3. Hash Password using salt
public static string CreatePasswordHash(string sPwd, string sSalt)
{
// password hash size
const int hashSize = 100;

string saltAndPwd = string.Concat(sPwd, sSalt);
byte[] result = new byte[hashSize];

// create the service provider
SHA1 sha = new SHA1CryptoServiceProvider();
result = sha.ComputeHash(Encoding.ASCII.GetBytes(saltAndPwd));

// return the password hash value
return Convert.ToBase64String(result);
}

4. Write log to application event log
//Usage:
// catch (Exception ex)
// {
// CommonUtil.LogAppEvent("LoginUser", "Exception encountered during login.", ex, EventLogEntryType.Error, "DAL");
// return LoginResults.LoginException;
// }

public static void LogAppEvent(string funcName, string sMsg, Exception ex, EventLogEntryType eType, string sSource)
{
System.Diagnostics.EventLog lApp = null;
StringBuilder sb = new StringBuilder();

sb.Append("Function: " + funcName + "\n\n");
sb.Append("Message: " + sMsg + "\n\n");

if (ex != null)
{
if (ex.GetType() == Type.GetType("SQLException"))
{
SqlException se = (SqlException)ex;
sb.Append("SQL Exception:\n");
sb.Append("Error: " + se.Number.ToString() + "\n");
sb.Append("Source: " + se.Source + "\n");
sb.Append("On procedure: " + se.Procedure + "\n");
sb.Append("At line number: " + se.LineNumber.ToString() + "\n");
sb.Append("Description: " + se.Message + "\n\n");
sb.Append("Stack: " + se.StackTrace);
}
else if (ex.GetType() == Type.GetType("ArgumentException")
ex.GetBaseException().GetType() == Type.GetType("ArgumentException"))
{
ArgumentException ae = (ArgumentException)ex;
sb.Append("Source: " + ae.Source + "\n");
sb.Append("Description: " + ae.Message + "\n");
sb.Append("Argument: " + ae.ParamName + "\n\n");
sb.Append("Stack: " + ae.StackTrace);
}
else
{
sb.Append("Source: " + ex.Source + "\n");
sb.Append("Description: " + ex.Message + "\n\n");
sb.Append("Stack: " + ex.StackTrace);
}
}

try
{
// Create a new EventLog object
lApp = new System.Diagnostics.EventLog();

// Set the name of the Log
lApp.Source = sSource;

// Write the log
lApp.WriteEntry(sb.ToString(), eType);
}
catch
{
}
finally
{
// Dispose our object
lApp.Dispose();
}
}

5. Web.Config





//意思就是告诉Asp.Net系统,当在程序中使用System.Configuration.ConfigurationSettings.GetConfig("applications/AdminData")这个静态方法来读取applications/AdminData配置节的时候,会调用Corp.Portal.ProviderConfigurationHandler这个类来对这个配置节进行处理, 而Assembly名为Corp.Portal。

























6. Form Authentication
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, oUser.us_login, DateTime.Now, DateTime.Now.AddMinutes(60), false, string.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
//重定向到Default.aspx
Response.Redirect(Request.ApplicationPath + "/Default.aspx");
// 将已验证身份的用户重定向回最初请求的 URL
FormsAuthentication.RedirectFromLoginPage("*", false);

7. 自定义配置节
.net规定,所有能够处理配置节的类必须要实现IConfigurationSectionHandler接口, 即实现object Create(object parent,object configContext,XmlNode section)方法,这个方法不需要主动调用,它是在ConfigurationSettings.GetConfig这个静态方法的时候自动调用的.

8. web\PageBase.cs基类:
protected void CheckLogin(string application)
{
UserProfile oUP = (UserProfile)System.Web.HttpContext.Current.Session["UserProfile"];
ApplicationInfo info = (ApplicationInfo)oUP.Applications[application];
if (info.app_isLogin == "N") //user not yet logged into the application
{
if (info.app_intsecurity == "N") //different security DB
{
LoginApp();
}
}
}

protected virtual void LoginApp()
{}

protected override void OnError(EventArgs e)
{
ApplicationLog.WriteError(ApplicationLog.FormatException(Server.GetLastError(), UNHANDLED_EXCEPTION));
base.OnError(e);
}


7. 访问当前Session
Session mySession = System.Web.HttpContext.Current.Session;

8. Field Validators not working on different server -- force your application to reference another script version
adding the following tag to the section of the web.config file :

Mutil Tier Structure .Net Sample


Solution: Projects Name Space Objects File

----------Portal Corp.Portal Login Login.aspx.cs
----------Common Corp.Portal.Common CommonUtil CommonUtil.cs
SqlHelper SqlHelper.cs
----------AdminInfo Corp.Portal.Admin.Info UserInfo UserInfo.cs
UserProfile UserProfile.cs
LoginResults EnumInfo.cs
MenuInfo MeneInfo.cs
RoleInfo RoleInfo.cs
GroupInfo GroupInfo.cs
----------AdminBAL Corp.Portal.Admin.BAL UserBAL UserBAL.cs
----------AdminDAL Corp.Portal.Admin.DAL UserDAL UserDAL.cs


=================================================
Login.aspx.cs Corp.Portal
=================================================
protected void btnLogin_Click(Object sender, EventArgs e)
{
UserInfo oUser = new UserInfo(UserDAL.GetUserByEmail(null,null,UserEmail.Text));
if (oUser.us_login == null) {
//Login failed
}
LoginResults result = UserBAL.LoginUser(username, password, "W");
//LoginResults.LoginOK, LoginClientNotAllowed, LoginInvalidUser ...
//if good
UserProfile oUP = UserBAL.GetUserProfile(oUser.us_login, "W");
//Set Session and more process
}

=================================================
EnumInfo.cs Corp.Portal.Admin.Info
=================================================
public enum LoginResults
{
LoginOK = 0,
LoginFailed,
LoginException,
LoginInvalidUser,
LoginNotAllowed,
LoginClientNotAllowed
}

=================================================
UserInfo.cs Corp.Portal.Admin.Info
=================================================
public class UserInfo
{
//Properties
public string us_login;
public string us_online;
...
//A valid DataSet containing a User record in a DataTable
public UserInfo(DataSet ds)
{
LoadUserInfo(ds.Tables[0].Rows[0]);
}
//A valid DataRow representing a User record
public UserInfo(DataRow dr)
{
LoadUserInfo(dr);
}
private void LoadUserInfo(DataRow dr)
{
this.us_login = dr["us_login"].ToString();
...
}
public bool IsOnline();

}


=================================================
UserProfile.cs Corp.Portal.Admin.Info
=================================================
public class UserProfile
{
//Properties
public UserInfo User;
public Hashtable Roles;
public Hashtable Groups;
public Hashtable Applications;
public Stack History;

public UserProfile()
{
this.User = new UserInfo();
this.Roles = new Hashtable();
this.History = new Stack(5);
}
public bool IsInRole(string sRoleCode);
public bool IsInGroup(string sGrpCode);
...
}

=================================================
UserBal.cs Corp.Portal.Admin.BAL
=================================================
public static LoginResults LoginUser(string sLogin, string sPwd, string sClientType)
{
UserInfo oUser = UserDAL.GetUserInfo(null,null,sLogin);
//if good, update user last login
UserDAL.UpdateUserLastLogin(null,sLogin);
//validate the supplied password
string pwdHash = CommonUtil.CreatePasswordHash(sPws, oUser.us_pwdsalt);
if (!pwdHash.Equals(oUser.us_password)) return LoginResults.LoginFailed;
}

public static UserProfile GetUserProfile(string sLogin, string sClientType)
{
SqlConnection cn = null;
DataSet dsGroup = null;
DataSet dsMenu = null;
GroupInfo oGroup = null;
MenuInfo oMenu = null;
UserProfile oProfile = new UserProfile();
cn = new SqlConnection(SqlHelper.GetConnectionString(null));
cn.Open();
oProfile.User = UserDAL.GetUserInfo(null, cn, sLogin);
dsGroup = GroupDAL.GetGroupListByUser(null, cn, sLogin);
//for each row in dsGroup
oGroup = new GroupInfo(dsGroup.Tables[0].Rows[i]);
oProfile.Groups.Add(oGroup.gr_code, oGroup);
}

=================================================
UserDal.cs Corp.Portal.Admin.DAL
=================================================
public static DataSet GetUserByEmail(SqlTransaction tr, SqlConnection cn, string sEmail)
{
bool mustDisposeConnection = false;
SqlCommand cmd = null;
StringBuilder sb = new StringBuilder();
sb.Append("SELECT * from Users ");
sb.Append("WHERE us_email = @us_email");
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sb.ToString();
cmd.Parameters.Add("@us_email", SqlDbType.VarChar, 128).Value = sEmail;
if (tr == null)
{
if (cn == null)
{
try
{
cn = SqlHelper.GetConnection(SqlHelper.GetConnectionString(null));
mustDisposeConnection = true;
}
catch (Exception ex)
{
...
}
}
try
{
return SqlHelper.ExecuteDataset(cn, cmd);
}
catch
{
...
}
finally
{
if (mustDisposeConnection)
{
if (cn.State == ConnectionState.Open)
cn.Close();
cn.Dispose();
}
}
}
else
{
try
{
return SqlHelper.ExecuteDataset(tr, cmd);
}
catch (Exception ex)
{
...
}
}
}