How to store uploaded files?

There two way to store files which are uploaded by our client users. One is storing the data in the database, and the other is in the work folder, such as /wwwroot/uploadfiles/.

If you choose the database, you are a wise guy. Because the data can be fully controlled, it can be defined who is allowed to get the file data and who is not allowed. This is the briefness idea of building a role-base file system.

Storing the file in the directory folder is more accepted. Files are available in the directory that can be copied, moved or deleted. It is also available for the anti-virus programs. If you walk this way, you must consider two issues.

1. The repeat files name.

EX : xxx.doc is in the folder which was uploaded by user Jim. And xxx.doc is also ready to upload by user Lilei someday later. Overwrite or rename? The choice comes to you application.

2. User get your file name or the rule of naming files.

EX: What is the names of your xls and doc files in your computer? Sheet1.xls Sheet2.xls...
And what is the names of your files in your /wwwroot/uploadfiles/ folder? 20050601001.doc 20050601002.doc ....
If the curious user get a link http://www.hello.com/uploadfiles/20050601001.doc, why don't he type http://www.hello.com/uploadfiles/20050601002.doc in his browser address or other names? It will be a nightmare if some one run Flashget >> Add batch download.

In asp.net, some article suggests to add .config or other extend file name which is not available to client users defined by .Net Framework. EX: 20050601001.doc->20050601001.doc.config. And then move the extend file name added before when downloading? EX: 20050601001.doc.config->20050601001.doc.

 

The tip below is also useful both in asp.net ,asp , php and so on.

1.Get a hash function like MD5.

2.Hash the file name string and current time, and use the hash value to rename the uploaded file.

EX: User is uploading the file "New Microsoft Excel sheet.xls" and the hash value with DateTime.Now.ToStirng() is "28EA63A14517E01AD745F9A7EC142C6B.xls". The download link is like this Download It


Here is some code maybe useful written in C#.

public static string SaveFile(System.Web.UI.HtmlControls.HtmlInputFile UpLoadPath)
{
string filePath = UpLoadPath.PostedFile.FileName ;
if(filePath != "")
{
int i= filePath.LastIndexOf("\\") ;
string fileName =filePath.Substring(i) ;
string fileExt = System.IO.Path.GetExtension(fileName );
fileName=Security.Encrypt(DateTime.Now.ToString()+fileName).Replace("-","");;
UpLoadPath.PostedFile.SaveAs((System.Web.HttpContext.Current.Request.MapPath("/UploadFiles/"))+fileName+fileExt) ;
return fileName+fileExt;
}
else
{return "#";}
}

public static bool CheckFileExt(string fileExt)
{
fileExt = fileExt.ToLower();
if((fileExt!=".doc")&&(fileExt!=".xls")&&(fileExt!=".ppt")&&(fileExt!=".jpg")&&(fileExt!=".gif")&&(fileExt!=".txt")&&(fileExt!=".zip")&&(fileExt!=".rar")) {
return false;}
else
{
return true;
}
}

public static string Encrypt(string cleanString)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
Byte[] hashedBytes = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

return BitConverter.ToString(hashedBytes);
}

 

<INPUT id=UpLoadPath type=file name=File1 runat="server">

DataLogicLayer.Attachments.Add(this.txtDescription.Text, UpLoadPath.PostedFile.FileName.Substring(UpLoadPath.PostedFile.FileName.LastIndexOf("\\")), DataLogicLayer.Attachments.SaveFile(UpLoadPath), Int32.Parse(this.Page.User.Identity.Name),issueID);

 

 

Sort DataGrid with Stored Procedure in ASP.NET

DataGrid can be sorted easily with in-line SQL (SQL script embedded directly in your code) ,but how is with stored procedure?

This article will show you an example of two-way sorting dataGrid with stored procedure.

You may be familiar with creating the dataGrid,retrieving data from the database , in this case you can jump to the main point, that is 'HOW TO WRITE THE STORED PROCEDURE?'

  1. Create the DataGrid

    <?xml:namespace prefix = asp /> <asp:datagrid id=MyList AllowPaging="True" AutoGenerateColumns="False" AllowSorting="True" runat="server">
    <COLUMNS>
    <asp:BoundColumn HeaderText="Issue ID" SortExpression="IssueID" DataField="IssueID"> </asp:BoundColumn>
    <asp:BoundColumn HeaderText="Category" SortExpression="Category" DataField="Category"> </asp:BoundColumn>
    ...
    </COLUMNS>
    </asp:datagrid>

  2. Show the List

    private void Page_Load(object sender, System.EventArgs e)
    {
    if(!Page.IsPostBack)
    {
    ViewState["SortExpression"]="IssueID";
    ViewState["SortDirection"] = "DESC";
    ShowList();
    }
    }

     

    public void ShowList()
    {
    try
    {
    int par = -1;
    if(Request["Action"]!="All")
    {
    par = Int32.Parse(this.Page.User.Identity.Name);
    }
    MyList.DataSource = DataLogicLayer.Issues.ListIssues(par,ViewState["SortExpression"].ToString(),ViewState["SortDirection"].ToString());
    MyList.DataKeyField = "IssueID";
    MyList.DataBind();
    }
    catch(Exception e)
    {
    ...
    }
    }

     

    void MyList_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
    ViewState["SortExpression"]=e.SortExpression;
    if(ViewState["SortDirection"].ToString() == "DESC")
    {
    ViewState["SortDirection"] = "ASC";
    }
    else
    {
    ViewState["SortDirection"] = "DESC";
    }
    ShowList();
    }

  3. The DataLogicLayer function

    public static DataSet ListIssues(int userID,string sortExpression,string sortDirection)
    {
    SqlDataAdapter dadGet = new SqlDataAdapter("IssuesList", ConfigurationSettings.AppSettings["ConnectionString"]);
    dadGet.SelectCommand.CommandType = CommandType.StoredProcedure;
    dadGet.SelectCommand.Parameters.Add("@UserID", userID);
    dadGet.SelectCommand.Parameters.Add("@SortExpression", sortExpression);
    dadGet.SelectCommand.Parameters.Add("@SortDirection", sortDirection);
    DataSet dstImages = new DataSet();
    dadGet.Fill(dstImages);
    return dstImages;
    }

  4. The Stored procedure


    CREATE Procedure IssuesList
    (
    @UserID int,
    @SortExpression nvarchar(50),
    @SortDirection nvarchar(50)
    )
    AS
    DECLARE @SQL VARCHAR(2048)
    if( @UserID=-1)
    begin
    SET @SQL = 'select IssueID,Title,Category,Severity,Status,DateCreated from Issues order by '+@SortExpression+' '+@SortDirection
    end
    else
    begin
    SET @SQL = 'select IssueID,Title,Category,Severity,Status,DateCreated from Issues where OwnerID='+CONVERT(VARCHAR, @UserID)+' order by '+@SortExpression+' '+@SortDirection
    end
    EXEC (@SQL)
    GO

 


Send email via IIS using SmtpMail class

When our users forget their password,we have to set a new one and email it to them,because usually password in our database is encrypted with md5 or other arithmetic.

The face of the login page may like this:


 

The following steps will show how to send the new password to forgetful user named royhwa@gmail.com.

1. Check your IIS if the SMTP service had installed.


2. Add the appSettings in your Web.config file
<?xml version="1.0" encoding="utf-8" ?>
<CONFIGURATION>
<APPSETTINGS>
<ADD value="1" key="AlowEmail" />
<ADD value="Royhwa@localhost" key="AdministratorEmail" />
</APPSETTINGS>
<SYSTEM.WEB>
...

 

3. The MakeRadomCode() and Engypt(…) in Securiy.cs
public static string Encrypt(string cleanString)
{
Byte[] clearBytes = new UnicodeEncoding().GetBytes(cleanString);
Byte[] hashedBytes = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);

return BitConverter.ToString(hashedBytes);
}

public static string MakeRandomCode()
{
char[] s = new char[]{ '2','3','4','5','6','7','8','9','a'
,'b','c','d','e','f','g','h','i','j','k','m','n','o','p','q'
,'r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G'
,'H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W'
,'X','Y','Z','#','$','&','(',')','.'};
string num = "";
Random r = new Random();
for(int i = 0; i < 8; i++)
{
num += s[r.Next(0, s.Length)].ToString();
}
return num;
}

 

4. The SendEmail(…) in Globals.cs
public static bool SendEmail(string to, string subject,string message)
{
string AlowEmail=ConfigurationSettings.AppSettings["AlowEmail"].ToString();
if(AlowEmail=="0") return false;

string from =ConfigurationSettings.AppSettings["AdministratorEmail"].ToString();
try
{
MailMessage em = new MailMessage();
em.To = to;
em.From = from;
em.Subject = subject;
em.Body = message;
//SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(em);
return true;
}
catch
{
return false;
}
}


5. this.lbtnEmailPassword.Click += new System.EventHandler(this.lbtnEmailPassword_Click);
private void lbtnEmailPassword_Click(object sender, System.EventArgs e)
{
if (!Page.IsValid) return;
this.lbtnEmailPassword.Enabled = false;
try
{
int userID = DataLogicLayer.Users.getUserIDbyEmail(this.txtEmail.Text.ToLower());
if(userID!=0)
{
User user = Users.getUserbyID(userID);
string newPassword= Security.MakeRandomCode();
if(Globals.SendEmail(user.Email,"Your new password in RHITS","The new password is : "+newPassword))
{
user.Password = DataLogicLayer.Security.Encrypt(newPassword);
Users.UpdateUserDetail(user);
DataLogicLayer.Globals.ShowMsg(Msg,"New password send !",Color.Green);
}
else
{
DataLogicLayer.Globals.ShowMsg(Msg,"Password can be reset !",Color.Red);
}
}
else
{
DataLogicLayer.Globals.ShowMsg(Msg,"Wrong email address !",Color.Red);
}
}
catch(Exception ex)
{
DataLogicLayer.Globals.ShowMsg(Msg,ex.Message,Color.Red);
}
}


6. New password is send



7. User get it

Remarks from http://msdn.microsoft.com/library
If the SmtpServer Property is not set, mail is by default queued on a Windows system, ensuring that the calling program does not block network traffic. If the SmtpServer property is set, the mail is delivered directly to the specified server.
But not SmtpMail.SmtpServer = "localhost";


All the files needed by IIS(V5.1) of windows XP

I don't have a CD-ROM.

It took me an hour to find all the files from internet.

Here it is.

download: iis_xp_sp2.rar (11.3 MB) Cool, someone uploaded to Google.

 

About Ads in GWB

I know the maintenance of Geekswithblogs will cost a lot of money. And the advertisement helps paying the cost. Maybe will earn some money after the cost, because the advertisment which is such a big space is in every memeber's blog.

I think there should be a default setting which allows showing adv in our blog and there is also a option to hide the adv.

For example:

iframe
{VISIBILITY="hidden";
height=0;}

I do not like 'Powered by PRWeb' very much.

Install and config mpich on linux(FC4)

1.Dowload mpich.tar.gz 

 http://www-unix.mcs.anl.gov/mpi/mpich/downloads/mpich.tar.gz

2.Install mpich

 #cd ~
 #tar zxvf mpich.tar.gz
 #cd mpich-1.2.7
 #./configure -prefix=/usr/local/mpich
 #make
 #make install

3.Set the Env

 open ~/.bashrc
 Add the following at the end of bashrc.

 export  LINUX_MPIHOME=/usr/local/mpich
 export  PATH=$PATH:$LINUX_MPIHOME/bin
 export  LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$LINUX_MPIHOME/lib
 export  MANPATH=$MANPATH:$LINUX_MPIHOME/man

4.Set the SSH authtication

 After the previous steps, mpich is working. But it required your password 
 to run the program everytiom.
 Configure the SSH authtication will resolve the trouble.
 
 #ssh-keygen -t dsa
 #cp cp ~/.ssh/id-dsa.pub ~/.ssh/authorized_keys2
 #chmod go-rwx ~/.ssh/authorized_keys2
 #ssh-agent $SHELL
 #ssh-add


 If you are multi-nodes environment, do this on your nodes once. 
 Collect all the nodes' authorized_keys2 together in a folder and 
 give the folder to every nodes.
 #ssh shallow

 I do mpich on one sigle computer, so try multi-nodes yourself. 
 

5.Test your install

 cd /root/mpich-1.2.7/example/basic
 mpicc -o cpi cpi.c
 mpirun -np 4 cpi

6.Result

 pi is approximately 3.1415926544231239, Error is 0.0000000008333307
 wall clock time = 0.001951
 Process 2 of 4 on xx
 Process 1 of 4 on xx
 Process 3 of 4 on xx
 


Enjoy it!~

Royhwa
2005-10-20
 
(There is something wrong with the feedback.)To Cathy:
Try 4.Set the SSH authtication
I suggest to install MPICH2 which is easier to use and more powerful.

Here it is: http://www-unix.mcs.anl.gov/mpi/mpich2/

PlayCards Problem in Google Code Jam China

Problem Statement

You are playing a card game, and in your hand, you are holding several cards. Each card has a suit, 'S', 'H', 'D', or 'C', and a value between 1 and 10, inclusive. You may play cards as part of a set, which is three or more cards of the same value, or as part of a run, which is three or more cards of the same suit, in sequential order. (Runs may not wrap, thus, 9-10-1 is not a valid run.) Each card may be played only once.
For example, "1 S", "1 H" and "1 D" would be a valid set. "2 S", "3 S", and "4 S" would be a valid run.
You want to play as many cards as possible, maybe in several plays (see example 4). Given a String[] cards representing the cards held in your hand, you are to return an int indicating the maximum number of cards you can play. Each card will be given in the form "value suit" (quotes added for clarity).

Definition
Class: PlayCards
Method: maxCards
Parameters: String[]
Returns: int
Method signature: int maxCards(String[] cards)
(be sure your method is public)

Constraints
-
cards will contain between 0 and 20 elements, inclusive.
-
No two elements of cards will be the same.
-
Each element of cards will be of the form "value suit" (quotes added for clarity).
-
Each number represented will be between 1 and 10, inclusive, with no leading zeroes.
-
Each suit represented will be 'S', 'H', 'D', or 'C'.

Examples
0){"1 S", "2 S", "3 S"}
Returns: 3
We have a run of three cards, which we can play.
1){"4 C", "4 D", "4 S", "3 S", "2 S"}
Returns: 3
We can take the 4's as a set, or we can take the 2-3-4 run. Either way, we play 3 cards.
2) {"1 S", "2 S", "2 H", "3 H", "3 D", "4 D", "4 C", "5 C", "5 S"}
Returns: 0
We've got lots of cards, but no way to put three together.
3){"1 S", "2 S"}
Returns: 0
Since we have to play at least three cards at a time, there's nothing to do here.
4){"1 S", "2 S", "10 S", "5 S", "8 S",
"3 H", "9 H", "6 H", "5 H", "4 H",
"10 D", "5 D", "7 D", "4 D", "1 D",
"2 C", "4 C", "5 C", "6 C", "7 C"}
Returns: 9
The best we can do is to take the set of 4s, the 5-6-7 C, and the remaining three 5s. We could have taken the 4-5-6-7 of C, or all four 5s, but we would not end up playing as many cards.

(c)2003, TopCoder, Inc. All rights reserved.

 

The point is to get the best way to play cards. I thought this way to resolve this problem.

1.Store all possibility ways to play cards.

For Example:{"4 C", "4 D", "4 S", "3 S", "2 S","4 H","5 S","6 S","7 S"}

0 4C 4D 4H 4S
1 4D 4H 4S
2 4C 4H 4S
3 4C 4D 4S
4 4C 4D 4H
5 2S 3S 4S 5S 6S 7S
6 2S 3S 4S
7 3S 4S 5S
8 4S 5S 6S
9 5S 6S 7S
10 2S 3S 4S 5S
11 3S 4S 5S 6S
12 4S 5S 6S 7S
13 2S 3S 4S 5S 6S
14 3S 4S 5S 6S 7S

2.Circle the arraylist. When a element going out, we check the left elements whose id is bigger than the gone element in the array to see if they was destroyed.

For example:
0 go out, all the elements are destroyed. Game over.
Back to 0, let 1 go and 2 3 4 ...

Then do another circle in the left arraylist. When there is a element going out, we record the length of this element and add this value to the value we record in previous circle.

3.Print the max value we recorded. This is the max cards we can play.

4.The code:

The problem of using ArrayList

What is the value of j? 5 or 6?

Not all codes have return value

It is not allowed to write code like this.

Why???

static int Main(string[] args)
{
int a,b;
if(a>b) return 1;
if(a<b) return -1;
if(a==b) return 0;
}

Get All Hrefs Using C# in ASP.net

First i use regular expression which is in MSDN Library examples:

But the Regex does not working satisfactorily somehow, where there is some blanks.

Consider these hrefs:

<a href="link" >EX</a>

< a href = link >EX</a>

 

I wrote the code like this.

Firstly, find the 'href' tag which means that here is a href. <a href="link" >EX</a>

Use SubString to get the string from 'href' to '>'. <a href="link" >EX</a>

And replace href= '"" or other chars. href="link" > to link >

Then indexof blank space to cut the link. link > to link

 

The code is here:

Issue Tracking System

Effective project management is the key to complete any project on time and within budget. Within every project there are multiple issues that need to be tracked, prioritized, and dealt with. Company has several projects that must be completed on time for the company to be profitable. Missing the planned deadlines for any of these projects will cause the company to lose money.

The managers of projects are tracking issues in several different ways. Some are manually tracking issues in notebooks and others are tracking issues in text documents. Not only tracking the issues, but also the statistics of the issues becomes a troublesome issue. The unclear of the responsibility blocks the communication between the members of the project and it event becomes the fuse of denying one’s work.

By creating a hosted application, each project lead can easily record and track issues in one central location. Not only will everyone have access to just the data they need, but having the data stored in one location, will make it easier for management to determine if any critical issues are not being addressed. Issue tracking system is a useful system, which is applied in a lot of companies on technique-support, custom-support and project management. It can improve the quality of service and the pace of solving problems.

The first chapter of this thesis simply introduces the scheme. Chapter 2 introduces the requirement of issue tracking system. In system designing chapter, this thesis introduces the design. The state graph in this chapter is the key point of issue tracking system. The database designing chapter refers normal form, stored procedure and foreign key of SQL Server 2000. ASP.NET is effective in web programming and the project developing chapter introduces some detail of programming using C# which is meted in this system. Refactoring which is a popular technique is included in this thesis. The end of this paper talks about the level of this system and the problems which are not resolved yet.

The primary focus of this design is to help developers work together well. A good issue-tracking system should have at least the following properties:
1. Low barrier to participation.
2. Straightforward navigation.
3. Controlled information flow.

 

Click here to view AVI Shows



A User Control ASCX to do custom paging of your datagrid

There are too much code in my old posts. The code is always boring....

So, i just post what i am thinking in this post and later.

There are many datagrids in our web pages, and one day the custom paging is required. What is the wisest way to achieve this? I suggest the following method.

1.Write a user control ascx naming CustomPaging.ascx.

2.Drag the CustomPaging.ascx to bottom of the datagrid in the webform which you want to custom paging .

3.Use Session to connect them.

 

The user control ascx is like this:

The webform:

The page view:

 


How to use?

protected CustomPaging CustomPaging1;

private void Page_Load(object sender, System.EventArgs e)
  {
      CustomPaging1.MyDataList = "MyList";//your datagrid name
   string SessionName = "MyList_InformationsListAdmin421321";//Be sure give a only string
   CustomPaging1.CurrentPage = SessionName;
 
   if( Session[SessionName]!=null)
   {      
    MyList.CurrentPageIndex = Int32.Parse((Session[SessionName]).ToString());
    }

   if(!Page.IsPostBack)
   {     MyDataBind();   }


  }

Install RealPlayer on Fedora.

Notice:

Fedora has moved beyond "libstdc++.so.5", in order to install you'll need to install the "compat-libstdc++" rpm which should fulfill the requirements.

compat-libstdc++-33-3.2.3-47.fc4.i386.rpm is in FC4-i386-disc3.iso.

Export the rpm and install it, then your RealPlayer will work.

RealPlayer-10.0.6.776-20050915.i586.rpm is here .

ASP.net Application using One ASPX And Some ASCX

Can we design asp.net application like this?

  • Only one ASPX page named Default.aspx and some ASCX controls.
  • In the Default.aspx there is a placeholder and a navigation which contains many linkbuttons.
  • When we click the linkbuttons, ASCX controls are loaded.

For example.

I click the ChangePassword linkbutton, the placeholder loads the ChangePassword.ascx. But when i click the save button in the ChangePassword.ascx, the ASCX control disappears. Because the Page_Load of Default.aspx executes first.

I should told the Page_Load of Default.aspx to remember ASCX control. I add a ViewState["ControlName"] to the Default.aspx.

The Page_Load is like this:

private void Page_Load(object sender, System.EventArgs e)
{
    If(ViewState["ControlName"]!=null) {
        //Code : PlaceHolder load the Control
    }
}

The LinkButton is like this:

private void button_click(object sender, System.EventArgs e)
{
    ViewState["ControlName"]="ChangePassword.ascx" // or other name
    //Code : PlaceHolder load the Control
}

It seems play good. But as Page_Load executes before buttonclick, every time i click linkbutton, the Page_Load loads the previous control in flash time and then tune to button_click loading the current control. Is this what i wanted? NO!

I cudgel my brains for the Page_Load and button_click, but failed.

Automatic logon in Windows XP without registry editor

1. Click Start, and then click Run.
2. In the Open box, type control userpasswords2, and then click OK.
3. Clear the "Users must enter a user name and password to use this computer" check box, and then click Apply. 
4. In the Automatically Log On window, type the password in the Password box, and then retype the password in the Confirm Password box.
5. Click OK to close the Automatically Log On window, and then click OK to close the User Accounts window.

«May»
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789