Thursday, May 03, 2012

Grant execute perms on all SPROCS to a user

Recently we had a problem getting grant permissions going on all sprocs in a db we'd deployed.

Please see the brilliant 'The Code Project' article by Sumit Amar with the solution:

http://www.codeproject.com/Articles/5860/Grant-Execute-on-all-procedures-to-a-user

Thursday, February 09, 2012

Asserting Exception messages in unit tests

I found a handy little class for checking against specific exception types and their messages which is a nice upgrade from the standard "ExpectedException" attribute.

I must credit the author of this, found on Stack Overflow. Link here: http://stackoverflow.com/questions/113395/how-can-i-test-for-an-expected-exception-with-a-specific-exception-message-from

The class is as follows:


public static class ExceptionAssert
{
  public static T Throws(Action action) where T : Exception
  {
    try
    {
      action();
    }
    catch (T ex)
    {
      return ex;
    }
    Assert.Fail("Exception of type {0} should be thrown.", typeof(T));

    //  The compiler doesn't know that Assert.Fail
    //  will always throw an exception
    return null;
  }
}
An example of a test that makes use of this class is below
[TestMethod]
public void GetOrganisation_MultipleOrganisations_ThrowsException()
{
  OrganizationList organizations = new Organizations();
  organizations.Add(new Organization());
  organizations.Add(new Organization());

  var ex = ExceptionAssert.Throws(
              () => organizations.GetOrganization());
  Assert.AreEqual(MyRes.MultipleOrganisationsNotAllowed, ex.Message);
}

Thursday, January 05, 2012

Downloading Zip Files

Downloading Zip files from a remote host can be a tricky business...

You can approach it in the following way:


private void GetDownloadDocument(string filename, Uri url)
        {
            // Create a stream for the file
            Stream stream = null;

            // This controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;

            // Buffer to read bytes in chunk size specified above
            byte[] buffer = new Byte[bytesToRead];

            // The number of bytes read
            try
            {
                //Create a WebRequest to get the file
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);

                //Create a response for this request
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;

                //Get the Stream returned from the response
                stream = fileResp.GetResponseStream();

                // prepare the response to the client. resp is the client Response

                //Indicate the type of data being sent


                System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
                resp.ContentType = "application/octet-stream";


                //Name the file
                resp.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

                int length;
                do
                {
                    // Verify that the client is connected.
                    if (resp.IsClientConnected)
                    {
                        // Read data into the buffer.
                        length = stream.Read(buffer, 0, bytesToRead);

                        // and write it out to the response's output stream
                        resp.OutputStream.Write(buffer, 0, length);

                        // Flush the data
                        resp.Flush();

                        //Clear the buffer
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        // cancel the download if client has disconnected
                        length = -1;
                    }
                } while (length > 0); //Repeat until no data is read
            }
            finally
            {
                if (stream != null)
                {
                    //Close the input stream
                    stream.Close();
                }
            }


        }

But this can present a number of problems - particularly with regards to Internet Explorer in its ability to allow the file to be downloaded. Far better to take the 'present a link approach' as per below:


public string DownloadZipToServer(string fileName, Uri url)
        {
            // Get the file from the remote server and save it to a local (to the server) folder, before returning the path.

            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
            // Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
            string pathToFile = "";
            string mainUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            string relativePathToFile = mainUrl + "/Docs/" + fileName;

            using (Stream stream = fileResp.GetResponseStream())
            {
                pathToFile = System.Web.HttpContext.Current.Server.MapPath("/Docs/" + fileName);
                using (FileStream fs = new FileStream(pathToFile, FileMode.Append))
                {
                    int length = 0;
                    int bytesToRead = 1000;
                    byte[] buffer = new byte[bytesToRead];

                    do
                    {
                        length = stream.Read(buffer, 0, bytesToRead);
                        fs.Write(buffer, 0, length);

                    } while (length > 0);
                }
            }

            return relativePathToFile;
        }

Then present the result of this method as a standard hyperlink.



Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Z