How To Create And Initialize A String Array In C#



TODO:

Have you wanted to create and initialize a string array in C#?

 

SOLUTION: 

string[] myArray = new string[] { "string1", "string2", "string3" };

 

 

NOTES:

No notes for this topic.

How To Create A Zip File Using C#



TODO:

Have you ever wanted to create a .zip file using C#?

 

SOLUTION:

 

public static string Compress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Prevent compressing already compressed files.
                if ((File.GetAttributes(fi.FullName)
                    & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fi.Extension != ".zip")
                {
                    // Create the compressed file.
                    using (FileStream outFile =
                                File.Create(fi.FullName + ".zip"))
                    {
                        using (GZipStream Compress =
                            new GZipStream(outFile,
                            CompressionMode.Compress))
                        {
                            // Copy the source file into the compression stream.
                            inFile.CopyTo(Compress);

                            return fi.FullName + ".zip";
                        }
                    }
                }

                return "";
            }

 

NOTES:

There are no notes on this topic.

How To FTP A File Using C# And FtpWebRequest



TODO:

Have you ever wanted to FTP a file using C#?

 

SOLUTION:

 

private static bool FTPFile(string fileName, string shortFileName, ref string ErrMsg)
{
    FtpWebRequest request = null;
    FtpWebResponse response = null;
    byte[] fileContents = null;
    try
    {   
        request = (FtpWebRequest)WebRequest.Create(_ftpUrl + shortFileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        if (fileName.ToUpper().EndsWith(".ZIP"))
            request.UseBinary = true;

        request.Credentials = new NetworkCredential(_ftpUserName, _ftpPassword);

        using (FileStream stream = File.OpenRead(fileName))
        {
            fileContents = new byte[stream.Length];
            stream.Read(fileContents, 0, fileContents.Length);
        }

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        response = (FtpWebResponse)request.GetResponse();
        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
        response = null;
        return true;
    }
    catch (Exception x)
    {
        ErrMsg = x.Message;
        return false;
    }
    finally
    {
        response = null;
        request = null;
    }
}

 

NOTES:

Note that I set the transfer mode to binary.  You can detect any file you want there as needed.

How To Create A Custom Configuration File Using C#



TODO:

Have you ever wanted to have your own configuration file that you could easily turn into an object?

 

SOULTION:

File:  MyConfiguration.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DevelopersAlley.Configuration
{
    [Serializable()]
    public class MyConfiguration
    {
        public string Name { get; set; }
        public string LogoURL { get; set; }
    }
}

 

In your calling class: 

 

//open up and use our config file
MyConfiguration _Configuration = null;
string _ConfigFile = "C:\\DevelopersAlley.config";
string _Name = "";
string _LogoURL = "";

using (StreamReader oReader = File.OpenText(_ConfigFile))
{
      _Configuration = (MyConfiguration)(new XmlSerializer(_Configuration.GetType()).Deserialize(new StringReader(oReader.ReadToEnd())));
     oReader.Close();

     _Name = _Configuration.Name;
     _LogoURL = _Configuration.LogoURL;
}

 

 

NOTES:

No notes on this topic.

How to reuse the Select portion of a LINQ to SQL Query



TODO:

Have you ever wanted to reuse the select portion of a LINQ to SQL query.  For instance if you are selecting only a certain number of fields, you can reuse that code, so that you ensure it is common across the board.

 

SOLUTION:

Method:

 

public IQueryable<Customer> GetBaseCustomerData(MyDataContext currentContext, ref string ErrorMessage)
{
     try
     {
           return (
                    from c in currentContext.Customers
                    select new Customer
                    {
                        CustomerId = c.CustomerId,
                        CustomerFirstName = c.CustomerFirstName,
                        CustomerMI = c.CustomerMI,
                        CustomerLastName = c.CustomerLastName,
                    }
                );
     }
     catch (Exception ex)
     {
           ErrorMessage = ex.Message;
           return null;
     }
}

 

To Call:

 

To call:
var customers = (GetBaseCustomerData(base._Context, ref errorMsg)
                            .Where(cc => (cc.CustomerId == customerId)

 

 

NOTES:

customerId is a local variable for which I want to fetch data for.