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.

The Equivalent Of TOP In LINQ to SQL



TODO:

Have you ever wanted to use the SQL equivalent of TOP in LINQ to SQL?  To do so, you can use the 'Take()' method

 

SOLUTION:

var custquery = (from c in MyContext.Customers
       select new
       {
              c.Id,
              c.FirstName,
              c.LastName
       }).Take(1000);

return custquery.ToDataTable();

 

NOTES:

There are no notes on 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 List All Indexed Columns In A Particular Table



TODO:

Have you ever wanted to list all indexed columns in a particular table?

 

SOLUTION:

 

select
    t.name, ind.name, col.name
from 
    sys.indexes ind
inner join 
    sys.index_columns ic on 
      ind.object_id = ic.object_id and ind.index_id = ic.index_id
inner join
    sys.columns col on
      ic.object_id = col.object_id and ic.column_id = col.column_id 
inner join
    sys.tables t on 
      ind.object_id = t.object_id
where 
    ind.is_primary_key = 0 
    and ind.is_unique = 0 
    and ind.is_unique_constraint = 0
    and t.is_ms_shipped = 0
    and t.name ='MyTable'
order by
    t.name, ind.name, col.name

 

NOTES:

There are 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.

How To Redirect Certain Pages In IIS



TODO:

Have you ever wanted to disable redirection for certain pages in IIS 7?

 

SOLUTION:

1.  Create an empty file called Index.html in the ROOT directory for which you want to redirect.

2.  Now go to Content View, select Index.html, and choose HTTP Redirection

3.  Set the URL for where you want requests to redirected.

4.  Now you are good to go.  Any request that comes in using the default document will be redirected, and any request that comes in to a specific URL will not be redirected.  This comes in handy if you have a Sitmap HTTP Handler.

 

NOTES:

No notes apply to this topic.