CodeConsults Ltd

Providing C#, ASP.NET and SQL Server Software Consultancy and Contracting Services...

WinForms screen capture

clock March 18, 2008 09:09 by author Admin

For a recent project we've been working on we needed to get a screen shot of a form and it's contents.  After much checking on the net for some sample code, all of which used GDI32 and User32 calls, we gave up looking and decided to investigate ourselves.

In the end it was so simple and clean that we just can't believe that this isn't documented that well anywhere on the web.  The code below is an extract of our code that takes the forms position on the screen, creates a bitmap of the contents of the screen from co-ordinates passed to it and then saves the resultant screen shot to a file

using (Bitmap bitmap = new Bitmap(ParentForm.Size.Width, ParentForm.Size.Height))
{
  using (Graphics g = Graphics.FromImage(bitmap))
  {
    g.CopyFromScreen(new Point(ParentForm.DesktopLocation.X, ParentForm.DesktopLocation.Y), new Point(0, 0), ParentForm.Size);
  }

  bitmap.Save(@"C:\test.jpg", ImageFormat.Jpeg);
}

Enjoy Smile

Currently rated 4.5 by 8 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Ajax comes to EmigratingToOz.com

clock February 9, 2008 10:05 by author Admin

The goal of the EmigratingToOz.com website is to be the oracle of information about Australia for us UK poms and to help them in the emigrating process.  To that end, one of the things we needed to do was also supply real-time information about Australia from the point of view of weather, money and time.

Initially, the website was set up to actively get this information from a variety of sources and simply display on the page via the master page.  However, the weather information in particular, comes from a slowish website that was killing the inital load time of the site.

The solution was simply to implement Ajax calls to get the information required in an asynchronous manner.  Using the generic library that we created to demostrate Ajax calls on our main website, we were able to implement the calls for all of the data in one quick afternoon.  The result is a quicker and more pleasing experience...

Currently rated 4.4 by 7 people

  • Currently 4.428571/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Showing a Windows form full screen

clock January 31, 2008 03:13 by author Admin

Ok....quite simple you might think!  And yes it is, but only if you know how!

For a small project that we are working on at the moment we needed to show a Windows Form in full screen mode without the taskbar etc...  It is quite simple in the end but needs a couple of Win32Api calls, but that is simple enough.  The one thing that is easy to forget is that you need to set the FormBorderStyle property for the form to None, otherwise you will still have the menu bar showing....

To acheive the full screen mode create a simple class with the code below in it

[DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
public static extern int GetSystemMetrics(int which);

[DllImport("user32.dll")]
public static extern void SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int X, int Y, int width, int height, uint flags);

private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private static IntPtr HWND_TOP = IntPtr.Zero;
private const int SWP_SHOWWINDOW = 64;

public static int ScreenX
{
  get { return GetSystemMetrics(SM_CXSCREEN); }
}

public static int ScreenY
{
  get { return GetSystemMetrics(SM_CYSCREEN); }
}

public static void SetWindowFullScreen(IntPtr hwnd)
{
  SetWindowPos(hwnd, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
}

Then in your application simply create a new instance of the form and call the Show method on the form.

Form form1 = new Form();
form1 .Show(this);

Then finally create an OnLoad handler for the form and call the SetWindowFullScreen method on our helper class and that is it....

WinApi.SetWindowFullScreen(Handle);

Currently rated 4.3 by 7 people

  • Currently 4.285714/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


New CodeConsults website - Emigrating To Oz

clock January 17, 2008 13:18 by author Admin

We've recently started a new project website called Emigrating To Oz

Its a site centering around providing a resource of information for people wishing to emigrate to Australia, but its still in its infancy and we are targetting a Q2 2008 release with all the bells and whistles, but in the meantime the site is live so that we can begin getting it indexed and tested.

There's plenty of work to do and content to add and we're hoping that in time it will become an excellent resource for us Poms who are looking at possible life Down Under 

Currently rated 4.4 by 7 people

  • Currently 4.428571/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


A neater way of getting data out of a DbDataReader

clock November 25, 2007 06:55 by author Admin

Previously I have always done the following to iterate through a DbDataReader

  while(reader.Read())
  {
    int index = reader.GetOrdinal("User_Description");
    list.Add(reader[index] as string);
  }

But today I stumbled upon the following which is so much neater:

  foreach (DbDataRecord dbDataRecord in reader)
  {
    int index = dbDataRecord.GetOrdinal("User_Description");
    list.Add(dbDataRecord[index] as string);
  }

I just think it's a lot neater and clearer as to what's going on....

Currently rated 4.4 by 8 people

  • Currently 4.375/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Getting the application path using reflection and C#

clock November 23, 2007 13:54 by author Admin
Just recently I had a problem whereby there was a case which resulted in the current working directory changing before some of my code had run.  As I hadn't catered for this case it came up with a crash which was easily fixed by getting the current application path and then combining this with the filename which I wished to access.  Heres the code that I used to acheive this in a nice clean fashion and create a path to a configuration file (configurationFilename):

Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string fullConfigurationFilename = Path.Combine(Path.GetDirectoryName(uri.AbsolutePath), configurationFilename);
fullConfigurationFilename = HttpUtility.UrlDecode(fullConfigurationFilename);

 

By using reflection to get the location of the currently executing assembly I am not relying on the actual .exe location (or website location in fact), but instead using the actual dll's location from which the current code is running.  You might wish to use the actual application's path or the website root path, but in the scenario that I am using this in, the assembly's path is exactly what I wanted.

Currently rated 4.4 by 5 people

  • Currently 4.4/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Auto-generating a sitemap conforming to Sitemap Protocol 0.9

clock November 23, 2007 13:51 by author Admin
Having recently installed BlogEngine.NET, I was interested to see the auto-generated sitemap that Mads had created.  Basically, he implemented a custom HttpHandler that when requested would respone with XML that conformed to the Sitemap Protocol 0.9 which is dictated by sitemaps.org.  This is an XML schema that all of the major search engines have signed up to which include Google, Yahoo! and Microsoft.

What I wanted to do is to implement this for my own site, but the custom handlers of Mads was tailored to BlogEngine.NET, so it required a bit of tweaking.  Now, I have a Web.sitemap for my website, so in the scheme of wanting to do things from a generic point of view, I decided to implement the HttpHandler to utilise the Web.sitemap file to generate the sitemap response.  To do this, first we have to load up the sitemap file...

XmlSiteMapProvider xmlSiteMap = new XmlSiteMapProvider();
NameValueCollection myCollection = new NameValueCollection(1);
myCollection.Add("siteMapFile", "Web.sitemap");
xmlSiteMap.Initialize("provider", myCollection);
xmlSiteMap.BuildSiteMap();

Then we have to navigate through the tree structure identifying the nodes that we are interested in...

private static void ProcessNode(XmlWriter writer, SiteMapNode node, string attribute)
{
 foreach (SiteMapNode siteMapNode in node.ChildNodes)
 {
  string actualUrl;
  if (siteMapNode.HasChildNodes)
  {
   ProcessNode(writer, siteMapNode, attribute);
  }
  actualUrl = siteMapNode[attribute];
  if (string.IsNullOrEmpty(actualUrl))
  {
   actualUrl = siteMapNode.Url;
   if (string.IsNullOrEmpty(actualUrl))
   {
    continue;
   }
  }
  WriteUrl(actualUrl, writer);
 }
}


And lastly building up the XML response...

if(Uri.IsWellFormedUriString(actualUrl, UriKind.Relative))
{
 FileInfo fileInfo = new FileInfo(HostingEnvironment.MapPath(actualUrl));
 writer.WriteStartElement("url");
 writer.WriteElementString("loc", HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, "") + actualUrl);
 writer.WriteElementString("lastmod", fileInfo.LastWriteTime.ToString("yyyy-MM-dd"));
 writer.WriteElementString("changefreq", "monthly");
 writer.WriteEndElement();
}


I have implemented this HttpHandler in a seperate component, simply to allow me to reference this utility from other websites that I have written, but you may decide to simply plug in the HttpHandler to your main project....the decision is yours.

Now, hopefully you've also realised that you'll need to reference the HttpHandler in the website's web.config......like so...

     <httpHandlers>
      <add verb="*" path="sitemap.axd" type="CodeConsults.HttpHandlers.Generic.Sitemap" validate="false"/>
     </httpHandlers>

Now you can run your website, point your favoured browser to http://website/sitemap.axd and voila, your sitemap is available for all to see.  But the last stage should be to update your robots.txt file to tell the search engines that you have a nice sitemap for them to use. To do this simply open your robots.txt file and enter the following...

     sitemap: http://www.codeconsults.com/sitemap.axd

And that's it! Here's a link to the source code for the class...  I'll leave the rest to you

Currently rated 4.5 by 4 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Alternative to Server.MapPath...use HostingEnvironment.MapPath

clock November 23, 2007 13:50 by author Admin
A call to the following context sensitive MapPath function does exactly what the documentation says it does.

    System.Web.HttpContext.Current.Server.MapPath("\filename.txt");

 

It returns the physical file path that corresponds to the specified virtual path on the Web server.  But this isn't always what you want as it works on the current context which may be a web form running in a sub-directory of the main website.

In this case the solution is simple.  Use the following code to map the path to a physical path on the server

    System.Web.Hosting.HostingEnvironment.MapPath("\filename.txt");

Currently rated 4.7 by 6 people

  • Currently 4.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Getting the Calling method through Reflection

clock November 23, 2007 13:45 by author Admin
Having recently created a simple framework for other developers to use, I needed to create a custom Exception class to use when throwing exceptions.

When throwing an exception in a WinForms application I always generate my own Exception class, which adds some other useful information that I can package along with the actual exception that was originally thrown.  Although the Call Stack is included in the actual exception, one thing that I like to do is tell the developer the method in which the exception was originally thrown.  This removes the need for the developer to navigate through the exception as all they are initially after is where the Exception occured.

In the past I would have normally simply passed in the method name like so:

    throw new Exception(connSettings, MethodBase.GetCurrentMethod().Name, "Argument is Null", ex);

But I decided to spend some time making this transparent.  In the end I was able to put this in the actual Exception class using the following method which is called as a part of the constructor of the Exception class:

    private void SetCallingMethod()
    {
        method = new StackFrame(2, false).GetMethod().Name;
    }

In this we open up a new stack trace and navigate to the second frame in the trace (remembering that frame 1 of the stack will result in the constructor method).  Now the code to create the new exception is simpler:

    throw new Exception(connSettings, "Argument is Null", ex);

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


LinkedIn

View Russ Quinn's profile on LinkedIn

Search

Tags

Categories


Calendar

<<  February 2012  >>
SuMoTuWeThFrSa
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

Archive

Disclaimer

The opinions expressed herein are our own personal opinions and do not represent anybody's outside of CodeConsults Ltd.

© Copyright 2012

Sign in