Archive for tag: .Net

FTP upload with .Net

If you are looking for a simple way for your application to move files between remote servers than it is worth considering FTP.  The following code shows how simple it is to upload a file via FTP with c#.

// File to be uploaded
string fileName = @"c:\temp\MyFile.zip";

// URL containg remote location and name of file
string remoteServer = "ftp://[ServerName]/" + Path.GetFileName(fileName);

// Please don't store userNames and passwords like this!
string userName = "";
string pass = "";

//Create the request
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(remoteServer);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(userName, pass);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

// Read the file to be uploaded into a byte array
FileStream stream = File.OpenRead(fileName);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();

// Get the stream for the request and write the byte array to it
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

Retrieving WhoIs information via .Net

Retrieving WhoIs information for domains via code is a relatively straight forward process with only one catch, you have to find the right WhoIs server to query.

Luckily I have found a great WhoIs Server List produced by Nir Sofer which lists the top level domains and their server.  The list is available for download here.

The code for retrieving the WhoIs query result is below:

string whoisServer = "";
string ret = "";
Socket s = null;

s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(new IPEndPoint(Dns.Resolve(whoisServer).AddressList[0], 43));

s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
byte[] buffer = new byte[1024];
int recv = s.Receive(buffer);
  while (recv > 0)
  {
    ret += Encoding.ASCII.GetString(buffer, 0, recv);
    recv = s.Receive(buffer);
  }
s.Shutdown(SocketShutdown.Both);

s.Close();
return ret;

Using the ASP.Net Login control in umbraco

The following is a step by step guide to using the ASP.Net login control in umbraco.

Step 1

Create a new DocType and associated template called Login Example.

Login Example Screen 1

Step 2

Go to the new Login Example template and add the form tag and login control code as shown below.

Screen shot 2010-01-08 at 15.53.49

Step 3

Now go to the content node and create a page called Login using the 'Login Example' docType.  If 'Login Example' docType is not available ensure you have it as an allowed child node of the parent docType.

Login Example Screen 3

Step 4

Now you can view your new login page!Login Example Screen 4

Step 5

To use your login page you will need to go to the Members section and create a member type.  This must be created before you try and create your first member.  Also, if you plan to use the createUserWizard control you will need to update your web.config as per my previous post to reference this member type.

Login Example Screen 5

Step 6

Now you can create your user.

Login Example Screen 6

Step 7

The final step in the whole process is to secure the portion of the site that you want to be members only.  To do this go to the content node you want to secure, right click and choose 'Public Access'  This will then give you the option to choose 'User Based' or 'Role Based' security.  Once you select one of these options you will then be prompted to choose your Login page (just select the login page node from the tree) and the error page which will be displayed if a user is valid, but doesn't have sufficient privileges.

Using .Net Membership controls with umbraco

The asp.net membership controls will work almost straight out of the box with the umbraco membership provider with the exception of the CreateUserWizard control which requires a small change to be made to your web.config file.

There is an umbracoMembershipProvider section in the web.config file that contains a key called 'defaultMemberTypeAlias'.  The value in this key must correspond to a MemberType that exists in your Members section.

When the createUserWizard control runs it will create the user with the details supplied and then try and assign them to the memberType in the key.  If you haven't changed this value to match a real memberType you will receive an error and the user won't be created.

Open Source .Net component for zipping files

I am currently working on a backup package for umbraco and one of the first things I had to do was compress the files prior to transfer.  Luckily there is a very good open source component to do this called SharpZipLib.

The following code from the SharpZipLib sample library shows just how easy it is to zip all the files in a folder.

string[] filenames = Directory.GetFiles(args[0]);

using (ZipOutputStream s = new ZipOutputStream(File.Create(args[1]))) {

    s.SetLevel(9); // 0 - store only to 9 - means best compression

    byte[] buffer = new byte[4096];
    
    foreach (string file in filenames) {
        
        // Using GetFileName makes the result compatible with XP
        // as the resulting path is not absolute.
        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
        
        // Setup the entry data as required.
        
        // Crc and size are handled by the library for seakable streams
        // so no need to do them here.

        // Could also use the last write time or similar for the file.
        entry.DateTime = DateTime.Now;
        s.PutNextEntry(entry);
        
        using ( FileStream fs = File.OpenRead(file) ) {

            // Using a fixed size buffer here makes no noticeable difference for output
            // but keeps a lid on memory usage.
            int sourceBytes;
            do {
                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                s.Write(buffer, 0, sourceBytes);
            } while ( sourceBytes > 0 );
        }
    }
    
    // Finish/Close arent needed strictly as the using statement does this automatically
    
    // Finish is important to ensure trailing information for a Zip file is appended.  Without this
    // the created file would be invalid.
    s.Finish();
    
    // Close is important to wrap things up and unlock the file.
    s.Close();
}

IPhone Development with MonoTouch

If you are a .Net developer and would love to be able to develop apps for the iPhone without learning Objective-C then I may have your solution.

iphonesmallSome  of you may be familiar with an open source project called Mono which was aimed at making .Net applications run on the linux platform.  A similar project has now been built by Novell called MonoTouch, which allows iPhone applications to be written in .Net.

Having used the project for the past three months, I have to say that I am very impressed.  It is still a bit of a learning curve at the start and the current online help is very limited, however if you can stick with it the results are amazing.

The biggest issue for most .Net developers is going to be the fact that you still need an Mac to run MonoTouch.  Also, although MonoTouch is free to download and run on a simulator, you will need to pay 399 euro to register it before you can download apps to your phone.