Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries for the ‘C#’ Category

C# code snippet to get a screenshot of a process

A small code snippet to get a screenshot of a process

Screenshot of this application.

image

Code behinds

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ProcessScreenshot
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTake_Click(object sender, EventArgs e)
        {
            Process[] ps = Process.GetProcessesByName(txtProcess.Text.Trim());
            if (ps.Length == 0)
            {
                MessageBox.Show(string.Format("There is no process named {0}", txtProcess.Text));
                return;
            }
            Process proc = Process.GetProcessesByName("notepad")[0];
            if (SetForegroundWindow(proc.MainWindowHandle))
            {
                RECT srcRect;
                if (!proc.MainWindowHandle.Equals(IntPtr.Zero))
                {
                    if (GetWindowRect(proc.MainWindowHandle, out srcRect))
                    {
                        int width = srcRect.Right - srcRect.Left;
                        int height = srcRect.Bottom - srcRect.Top;

                        var bmp = new Bitmap(width, height);
                        Graphics screenG = Graphics.FromImage(bmp);

                        try
                        {
                            screenG.CopyFromScreen(srcRect.Left, srcRect.Top,
                                                   0, 0, new Size(width, height),
                                                   CopyPixelOperation.SourceCopy);

                            if (!Directory.Exists(txtPath.Text))
                                Directory.CreateDirectory(txtPath.Text);

                            string fileName = DateTime.Now.ToString("HHmmss-") +
                                              Guid.NewGuid().ToString().Substring(0, 6) + ".png";
                            bmp.Save(Path.Combine(txtPath.Text.Trim(), fileName), ImageFormat.Png);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            screenG.Dispose();
                            bmp.Dispose();
                        }
                    }
                }
            }
        }

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

        [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        #region Nested type: RECT

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        #endregion
    }
}

Prism Design Goals

Prism was designed to help you design and build rich, flexible, and easy-to-maintain WPF and Silverlight applications. The Prism Library implements design patterns that embody important architectural design principles, such as separation of concerns and loose coupling. Using the design patterns and capabilities provided by the Prism Library, you can design and build applications using loosely coupled components that can evolve independently but that can be easily and seamlessly integrated into the overall application.

Prism is designed around the core architectural design principles of separation of concerns and loose coupling. This allows Prism to provide many benefits, including the following:

  • Reuse. Prism promotes reuse by allowing components and services to be easily developed, tested and integrated into one or more applications. Reuse can be achieved at the component level through the reuse of unit-tested components that can be easily discovered and integrated at run time through dependency injection, and at the application level through the use of modules that encapsulate application-level capabilities that can be reused across applications.
  • Extensibility. Prism helps to create applications that are easy to extend by managing component dependencies, allowing components to be more easily integrated or replaced with alternative implementations at run time, and by providing the ability to decompose an application into modules that can be independently updated and deployed. Many of the components in the Prism Library itself can also be extended or replaced.
  • Flexibility. Prism helps to create flexible applications by allowing them to be more easily updated as new capabilities are developed and integrated. Prism also allows WPF and Silverlight applications to be developed using common services and components, allowing the application to be deployed and consumed in the most appropriate way. It also allows applications to provide different experiences based on role or configuration.
  • Team Development. Prism promotes team development by allowing separate teams to develop and even deploy different parts of the application independently. Prism helps to minimize cross-team dependencies and allows teams to focus on different functional areas (such as UI design, business logic implementation, and infrastructure code development), or on different business-level functional areas (such as profile, sales, inventory, or logistics).
  • Quality. Prism can help to increase the quality of applications by allowing common services and components to be fully tested and made available to the development teams. In addition, by providing fully tested implementations of common design patterns, and the guidance needed to fully leverage them, Prism allows development teams to focus on their application requirements instead of implementing and testing infrastructure code.

Overview of Windows Presentation Foundation

WPF is a set of .NET Framework classes that you can use to build attractive and functional UIs for Windows-based client applications.

WPF uses the DirectX graphics engine to provide sophisticated graphics and efficient rendering.

WPF enables you to develop applications by using both declarative markup and managed code.

Typically, you use XAML to implement the appearance of your application and you use a .NET Framework managed programming language, such as C#, to implement behavior.

This separation of appearance from behavior offers many advantages when you build graphical applications.

For example, designers can work on the appearance of an application at the same time as developers independently work on the code-behind functionality.

You can use WPF to create stand-alone applications and applications that are hosted in a Web browser.

When you create stand-alone applications, you use the Window class and you use menu bars, toolbars, and dialog boxes as the building blocks of your application.

When you create browser-hosted applications, you use the Page class as your foundation and you provide hyperlinks to enable users to navigate between the pages in your application.

In both cases, you can use the Application class to share session data, properties, and resources across your application.

WPF includes many other features that enhance the experience of the developer and the end user.

For example, the WPF layout system makes it easy for you to develop controls and layouts that adapt to differing window sizes and display settings.

This is an essential part of the modern user experience.

The WPF data-binding system makes it easy for you to implement two-way data binding between controls and data sources.

Finally, the graphics system includes support for highly sophisticated two-dimensional graphics, three-dimensional graphics, and animations that you can use to create genuinely engaging applications.

Optional Parameters in C# 4.0

Just like other languages such as vb, and c/c++, C# can support the optional parameters from 4.0.

here is a code snippet

   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:          MyTest("P1", "P2");
   6:          MyTest("P1");
   7:      }
   8:   
   9:      static void MyTest(string parameter1, string parameter2="Default Value 2")
  10:      {
  11:          Console.WriteLine("Para1={0}, Para2={1}", parameter1, parameter2);
  12:      }
  13:  }

And the returning result will be

Para1=P1, Para2=P2

Para1=P1, Para2=Default Value 2

and the parameter2 will use the default value in the definition if you do not give a value. Quite convenience, isn’t it?

Call SQL Server Management Objects (SMO) in C#

Overview of SMO

SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server. You can use SMO to build customized SQL Server management applications. Although SQL Server Management Studio is a powerful and extensive application for managing SQL Server, there might be times when you would be better served by an SMO application.

SMO in SQL Server 2008 is compatible with SQL Server 2000, SQL Server 2005, SQL Server 2008 and SQL Server 2008 R2. SMO in SQL Server 2005 is compatible with SQL Server 2000, SQL Server 2005. So, you can easily manage a multi-version environment with a higher version of SMO.

Install SMO

Microsoft SQL Server 2008 Management Objects Collection (a component of Feature Pack for Microsoft SQL Server 2005/2008)

The Management Objects Collection package includes several key elements of the SQL Server 2008 management API, including Analysis Management Objects (AMO), Replication Management Objects (RMO), and SQL Server Management Objects (SMO). Developers and DBAs can use these components to programmatically manage SQL Server 2008.

By default, the SMO assemblies are installed in the C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies, you can track this folder to see whether SMO installed successfully.

 

Call SMO in C#

These are the minimum files that are required to build an SMO application, and they are under the C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ folder

Microsoft.SqlServer.ConnectionInfo.dll

Microsoft.SqlServer.Smo.dll

Microsoft.SqlServer.Management.Sdk.Sfc.dll

Microsoft.SqlServer.SqlEnum.dll

Here is a demo of script all jobs in sql server

   1:  Server server = new Server(ServerName);
   2:  JobServer server2 = server.JobServer;
   3:  foreach (Job job in server2.Jobs)
   4:  {
   5:      WriteToFile(job, PathToWriteScripts);
   6:  }

Versioning and optional parameters

The restrictions on default values for optional parameters may remind you of the restrictions on const fields or attribute values, and they behave very similarly. In both cases, when the compiler references the value, it copies it directly into the output. The generated IL acts exactly as if your original source code had contained the default value. This means if you ever change the default value without recompiling everything that references it, the old callers will still be using the old default value. To make this concrete, imagine this set of steps:

  1. Create a class library  with a class like this:
    public class MyDemo
    {
    	public static void PrintValue(int value = 10)
    	{
    		System.Console.WriteLine(value);
    	}
    }
  2. Create a console application (Application.exe) that references the class library:
    public class Program
    {
    	static void Main()
    	{
    		MyDemo.PrintValue();
    	}
    }
  3. Run the application—it’ll print 10, predictably.
  4. Change the declaration of PrintValue as follows, then recompile just the class library:
    public static void PrintValue(int value = 20)
  5. Rerun the application—it’ll still print 10. The value has been compiled directly into the executable.
  6. Recompile the application and rerun it—this time it’ll print 20.

This versioning issue can cause bugs that are hard to track down, because all the code looks correct. Essentially, you’re restricted to using genuine constants that should never change as default values for optional parameters. There’s one benefit of this setup: it gives the caller a guarantee that the value it knew about at compile-time is the one that’ll be used. Developers may feel more comfortable with that than with a dynamically computed value, or one that depends on the version of the library used at execution time.

Of course, this also means you can’t use any values that can’t be expressed as constants anyway—you can’t create a method with a default value of “the current time,” for example.