Monday, January 28, 2008

C# Events

using System;
using System.Windows.Forms;
namespace EventsMadeSimple
{
    public partial class Form1 : Form
    {
        SimpleClass SimpleObject = new SimpleClass(); // create a new SimpleClass object
        public Form1() // Form1 constructor
        {
            InitializeComponent();
            Load += new EventHandler(Form1_Load); // add Form1's Load event handler
            // add our object's event handler
            SimpleObject.SimpleEvent += new OnSimpleEvent(SimpleEventOccurred);
        }
        void Form1_Load(object sender, EventArgs e)
        {
            SimpleObject.SimpleMethod(); // call the SimpleObject's method
        }
        private void SimpleEventOccurred() // method is called when the event is raised
        {
            listBox1.Items.Add("SimpleEvent was fired at " + DateTime.Now.ToString());
        }
    }
    public delegate void OnSimpleEvent(); // delegate
    public class SimpleClass
    {
        public event OnSimpleEvent SimpleEvent; // event
        public void SimpleMethod()
        {
            SimpleEvent(); // raise the event
        }
    }
}
 

There are two classes here. The standard windows generated Form1 and SimpleClass. SimpleClass is our own class with one event and one method.

Inside Form1 we've created a new instance of SimpleClass called SimpleObject.

In Form1's constructor, we've added an event handler (this makes it 'listen' for the specified event and call the specified method) for loading of Form1, and another for our SimpleObject's event. This calls the SimpleEventOccurred method in Form1 when the event is raised.

In Form1's load method we call SimpleObject's SimpleMethod, which is where the event gets raised. This method could be called from anywhere but I've placed it in the Load so it happens immediately when you run the project.

How easy was that?

Experiment Suggestions

Passing parameters: You will often see something similar to this in the signatures of methods called by events:

(object sender, EventArgs e)

If you want to do this or anything similar you will also need to give your delegate the same signature and pass valid paramaters when raising the event i.e.

public delegate void OnSimpleEvent(object sender, EventArgs e);

......

SimpleEvent(this, EventArgs.Empty); // raise the event

 

Custom EventArgs: You can create your own class that inherits from System.EventArgs

public class SimpleEventArgs : EventArgs { }

and pass an instance of this class in your parameters. This class can obviously have its own propeties/methods/constructors etc that can be manipulated and/or made accessible to the receiving method.


Return type: The method that gets called by the event handler (private void SimpleEventOccurred() in our case) can return a value type. To do this you will need to specify the same type in your delegate declaration. The call to SimpleEvent() will then be returned a value of type you specified.

Source

more info

Another simple example

Friday, January 4, 2008

Backup auto complete URLs in Internet Explorer

To get to the auto complete data, you will need to open regedit. Drill down to this key:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLS

Source

How to run an external program within VB Script

When VB Script executes a command line program it opens a new window. This can be especially inconvenient when you want to incorporate an external application into your script.

Console Windows

There is a way to have your script keep the console application within the same window, and wait for it to complete.
What we will do is launch the process, and then forward all of the console output of the script. When the process has terminated we exit the loop.
Here is a function that you can drop into your script (Click here to download)

Function ExecuteShellProgram(ByVal sFileName)
Dim poShell
Dim poProcess
Dim iStatus
Set poShell = CreateObject("WScript.Shell")
Set poProcess = poShell.Exec(sFileName)
'Check to see if we started the process without error
if ((poProcess.ProcessID=0) and (poProcess.Status=1)) then
Err.Raise vbObjectError,,"Failed executing process"
end if
'Now loop until the process has terminated, and pull out
'any console output
Do
'Get current state of the process
iStatus = poProcess.Status
'Forward console output from launched process
'to ours
WScript.StdOut.Write poProcess.StdOut.ReadAll()
WScript.StdErr.Write poProcess.StdErr.ReadAll()
'Did the process terminate?
if (iStatus <> 0) then
Exit Do
end if
Loop
'Return the exit code
ExecuteShellProgram = poProcess.ExitCode
End Function

Here is a simple example. I am going to call the command interpreter, and do listing of the windows folder:

ExecuteShellProgram "%COMSPEC% /c dir c:\windows"

(%COMSPEC% is a system variable that is set to the full path and file name of the command interpreter cmd.exe)

Now you can execute your console helper applications - and use the output in your script.

Source

Saturday, December 8, 2007

Create Rich Web Apps with AJAX

Microsoft's ASP.NET AJAX Extensions provide a simple and productive way to AJAX-enable a Web site without writing a lot of JavaScript code. Adding AJAX functionality to a Web site allows users to experience a richer user interface that reduces or eliminates the need to reload the entire page every time users click on a button or select an item from a drop-down list. Adding AJAX functionality to a Web site also enables users to access the data they need more quickly and efficiently (see "Why Use AJAX?"). There's a simple way to add AJAX to your Web pages, and it's instructive to understand how that works, but that approach isn't robust enough for many real-world commercial development scenarios, such as the one this article discusses. The simplest way to add AJAX functionality to your site is to wrap page content in an UpdatePanel control's ContentTemplate. This approach requires only minimal effort (see Listing 1, for an example of using the UpdatePanel control and the Timer control). It's also an effective approach, but it sends ViewState back and forth between the client and server when asynchronous postback operations occur within the page. This can potentially lead to larger than expected request and response messages being exchanged. You can use tools such as Fiddler to view messages sent by UpdatePanel controls and monitor their content and size. For many developers, the UpdatePanel is all they need to AJAX-enable their Web applications. However, other developers might need to minimize request and response messages as much as possible, suggest values to users as they type data into a textbox, or load and format data directly in the browser rather than building it on the server. In these situations, Web services provide a good alternative that you can use in concert with UpdatePanel controls on a page. Using Web services, you can pull data from the client directly, which makes the initial page load faster in the browser. In this article, I'll show you how to create Web services and consume them using ASP.NET AJAX and explain how you can use Web services with the ASP.NET AJAX Toolkit. I'll also introduce you to the real-world Amazon.com e-Commerce Service to demonstrate how the ASP.NET AJAX Extensions can enhance your overall productivity and allow you to integrate external data into your Web site with ease. Web services have been supported in the .NET framework since its initial release in 2002. ASP.NET AJAX supports calling standard .NET Web services, but adds a slight wrinkle to the equation. Instead of sending standard Simple Object Access Protocol (SOAP) request and response messages, ASP.NET AJAX applications send JavaScript Object Notation (JSON) messages to services. JSON is a compact way to send data to and from a Web service and is supported in all major browsers (unlike XML and SOAP). Developers don't have to know JSON to utilize Web services because ASP.NET AJAX handles the serialization and de-serialization of message data into, and out of, JSON messages. Several ASP.NET AJAX Extensions classes are used behind the scenes to allow ASP.NET AJAX applications to talk to Web services. First, an HttpModule named ScriptModule ensures that messages are routed to service methods properly using a technique referred to as Representational State Transfer (REST). Second, an HttpHandler named ScriptHandlerFactory plays a key role in handling calls made to back-end services, as well as calls made to profile and authentication services. Finally, an attribute named ScriptServiceAttribute marks a Web service as being AJAX capable. All Web services consumed by ASP.NET AJAX applications must contain the ScriptServiceAttribute reference. Create a Web Service
Assume you want to create a Web service named MathService that exposes a Web Method named Add():
[ScriptService]
[WebService(Namespace = 
   "http://www.interfacett.com/")]
[WebServiceBinding(ConformsTo = 
   WsiProfiles.BasicProfile1_1)]
public class MathService : WebService
{
   [WebMethod]
   public int Add(int x, int y)
   {
      return x + y;
   }
}
You AJAX-enable the Web service's class by applying the ScriptSer­viceAttr­ibute class directly to it as shown. No other changes are required at the Web service level for AJAX-enabled applications to call it. Other classes such as ScriptMethodAttribute and Gener­ateTy­peAttribute can also be used in a Web service although they're not required. More information about these attributes can be found here. Web services called by ASP.NET AJAX-enabled pages must be in the same domain as the page where the call originates from. This is due to security restrictions built into the XmlHttpRequest object used to make Web service requests. Although you can't call external Web services directly using ASP.NET AJAX, you can still make calls to external Web services by creating a local Web service that acts as the middleman. For example, assume you want to create a Web service that calls an Amazon.com service to retrieve book information (see Listing 2). This Web service relies on a class named AmazonSearch to call the Amazon.com service through a Web service proxy object and retrieve the desired data. You can find the Web Service Description Language (WSDL) document that describes the Amazon.com Web service here, and you can sign up for a free access account here. Amazon.com provides a free Web service called Amazon e-Commerce Service that you can use to retrieve information about books, DVDs, albums, and many other items sold on the Amazon.com Web site. By using the service, you can display Amazon.com products on your Web site and even receive a portion of sale proceeds for items purchased from your site. The service can be accessed for free once you've registered (registration is also free) and received an access key. The Amazon.com e-Commerce Service supports the latest standards and the team supporting the service provides samples that demonstrate calling the service in multiple languages, as well as a forum for posting questions about the service. You might wonder why I chose to use a Web service from a commercial vendor, such as Amazon, because this goes against the grain of VSM's usual approach. The reason: I wanted to show you a real-world implementation in action, as opposed to an example more theoretical than practical, and few non-commercial examples exist that have the robustness of Amazon's approach. Plus, it's free, and the terms of use are reasonable. ASP.NET AJAX provides a simple and efficient mechanism for calling Web services that have been marked with the ScriptServiceAttribute class. You can't right-click on your Web site project in Visual Studio .NET 2005 and add a Web Reference to create a Web service proxy, but you can use ASP.NET AJAX's ScriptManager control to create a client-side proxy that handles calling the service and passing JSON messages. You accomplish this using the ScriptManager's Services property and the ServiceReference control:
<asp:ScriptManager ID="smp" runat="server">
   <Services>
      <asp:ServiceReference 
         Path="AmazonService.asmx" />
   </Services>    
   <Scripts>
      <asp:ScriptReference 
         Path="Scripts/Amazon.js" />
   </Scripts>
</asp:ScriptManager>
Defining a service reference on the ScriptManager control causes a client-side proxy class to be generated and added to the page at runtime. This proxy code looks something like this:
<script src="AmazonService.asmx/js" 
      type="text/javascript"></script>
Note that the ASMX file is called directly and that "js" is added to the end of the path. The service is marked with the ScriptService attribute, so the ASP.NET AJAX runtime generates the JavaScript proxy code needed to call the service automatically. To call a Web service using a client-side proxy object, you reference the service's namespace, class, and method name using JavaScript. Parameter data required by the Web service's Web Method is passed to the method along with the name of the callback method. All calls to Web services are made asynchronously, and the callback method is invoked when a Web service call returns data to the browser. When the page containing the client-side Web service proxy first loads, it calls the SearchBooks() method (see Listing 3). This method locates a div tag with an ID of divAmazon and assigns a value of "Loading Books" to its innerHTML property. It then calls the local AmazonService.asmx service by referencing the service's namespace (GolfClubShack), class (AmazonService), and Web Method name (GetBooks). The GetBooks() method accepts three parameters, including the book text to search, the data results page to grab, and the name of the callback method. In this example a callback named OnWSCallback() is defined. Data returned from the Web service is routed automatically to the OnWSCallback() method, which processes the data (see Figure 1). The method iterates through all of the books returned and accesses different properties of each book, such as ImageUrl, Title, and Price. Note that you access each property in a strongly typed manner, much as you would when writing server-side code using C# or VB.NET. This strongly typed access to object property data is made possible by the proxy code generated by the ScriptManager. In addition to shipping the ASP.NET AJAX Extensions, Microsoft has also released a separate download called the ASP.NET AJAX Toolkit (also available here). This toolkit contains more than 30 AJAX-enabled controls for performing a variety of tasks. One of the controls that ties in nicely to Web services is the AutoCompleteExtender control. You've probably seen such a control if you've visited the Google suggest site or have the Google search box embedded in your browser. You can use this control to provide suggestions to end users as they type into a textbox. The control works by reading characters typed into a textbox and passing them to a Web service. The Web service performs a lookup against a data source to find data items that match with the initial characters typed and passes the matching items back to the AutoCompleteExtender control. The control then shows the matching data items directly below the textbox so that users can select them (see Figure 2). Using the AutoCompleteExtender requires that you copy the AjaxControlToolkit.dll assembly into your Web site's bin directory. This assembly is available in the ASP.NET AJAX Toolkit. You need to reference the AjaxControlToolkit.dll assembly once the assembly is available to use. Do this in web.config or in the page where you want to use the AutoCompleteExtender control. Add this code to the web.config file's <system.web> begin and end tags to reference the assembly in web.config and make it available for all pages on a Web site:
<pages>
   <controls>
      <add tagPrefix="toolkit" 
         namespace="AjaxControlToolkit" 
         assembly="AjaxControlToolkit" />
   </controls>
</pages>
Add this code to the top of a page to reference the assembly in a specific page:
<%@ Register
   TagPrefix="toolkit" 
   Namespace="AjaxControlToolkit" 
   Assembly="AjaxControlToolkit"
%>
After you reference the assembly, you can define the AutoCompleteEx­tender in the target page. The control boasts several key properties, including the target control ID to extend the textbox with auto-complete behavior, the minimum number of characters to accept in the target control before calling the Web service, and the name of the Web service and Web Method that will be called to look up data items. This code defines an AutoCompleteEx­tender control that extends a TextBox with an ID of txtSearch:
<toolkit:AutoCompleteExtender id="ac" runat="server"
   ServicePath="~/AutoCompleteService.asmx"
   ServiceMethod="GetSearchItems"
   TargetControlID="txtSearch"
   EnableCaching="true"
   MinimumPrefixLength="2"
/>
Once the number of characters to watch for has been reached (as defined using the AutoCompleteExtender's MinimumPrefixLength property), the Web service defined on the control is called to look for matching data items. For example, this Web service handles searching for matching data items and returning them to the AutoCompleteExtender control to display on the page (see Listing 4). The GetSearchItems() Web Method accepts two parameters: prefixText and count. The prefixText parameter contains the characters typed by the end user, while the count parameter contains the number of matching items to return back to the AutoCompleteExtender control. Data items that start with the value supplied by the prefixText parameter are returned from the Web Method in a string array. The ASP.NET AJAX Extensions provide several different ways to retrieve data from a back-end server using AJAX technologies. Although the UpdatePanel control will be all that's needed in many situations, integrating Web services into your Web applications can result in smaller request and response messages, which can lead to faster load times. By leveraging Web services you can also process and format data directly on the client rather than on the server. Web services can also be used to aid users as they type into textboxes by using controls such as the AutoCompleteExtender control found in the ASP.NET AJAX Toolkit.
Source

ASP.NET - Storing Images to Database and Retrieving to GridView

Link

ASP.NET C# - Enter Key

ASP.NET 2.0 makes this problems easier and introduce a concept of a "default button". New defaultbutton attribute can be used with <form> or <asp:panel> control. What button will be "clicked" depends of where acutally cursor is and what button is choosen as a default button for form or a panel.

Here is sample HTML code that contains one form and one panel control:

<form defaultbutton="button1" runat="server">
    <asp:textbox id="textbox1" runat="server"/>
    <asp:textbox id="textbox2" runat="server"/>
    <asp:button id="button1" text="Button1" runat="server"/>
    <asp:panel defaultbutton="button2" runat="server">
        <asp:textbox id="textbox3" runat="server"/>
        <asp:button id="button2" runat="server"/>
    </asp:panel>
</form>

Saturday, December 1, 2007

Linux: Israel Forums

Tapuz Forum Linux-Israel

Linux: Tips for new Ubuntu installation

35 Cool Applications to install on Ubuntu Google Desktop on Ubuntu 13 Must Do things on new Ubuntu installation A Casual guide to some commonly used Linux Commands Essential house keeping in Ubuntu

Installing libdvdcss2 and w32 video codecs in Ubuntu Gutsy Gibbon

Support for WMV, RealMedia and other formats has been bundled into the w32codecs package. This package is not available from the Ubuntu repositories due to licensing and legal restrictions.

For Ubuntu Gutsy Gibbon Users run the following command

sudo wget http://www.medibuntu.org/sources.list.d/gutsy.list -O /etc/apt/sources.list.d/medibuntu.list

Now you need to copy the key using the following command

wget -q http://packages.medibuntu.org/medibuntu-key.gpg -O-¦ sudo apt-key add -

Update the source list using the following command

sudo apt-get update

Install Codecs using the following command

sudo apt-get install w32codecs libdvdcss2

Using above download locations you can install most of the mutimedia codecs for ubuntu.

sudo apt-get update

Mplayer Plugin for Firefox

If you want to install Mplayer with plug-in for Mozilla Firefox run the following command

sudo apt-get install mozilla-mplayer

Tuesday, November 20, 2007

Linux: Find files on your computer with find

A standard Linux system has an incredible amount of files installed. Looking for a file location can be a painful task to do though a file browser.

Fortunately, there is a nifty command line available by default on any Linux distribution: find.

find can virtually find anything on your computer and comes with a lot of options. This tutorial will introduce a basic use of it and show how you can search your filesystem for file names matching a name pattern.

On Debian based distros, find is part of the package findutils. find allow one to search for files on a filesystem based on different condition, creation date, modified date, file size, file type, permissions, name ....

In this tutorial, I will be focused on finding files/directories based on their name, in order to explain in more depth the syntax of find, I will also show how you can narrow down your search by adding condition on size and file modification time.

This will suit most searches, if you need more details, I would recommend looking at the find's manpage.

1. Find basis

The default syntax of find is as such:

find [path] [expression]

where path is the path used as root for searching pattern and expression the expression we want the file to match.

2. Finding a file based on filename

Let say for instance you want to find all .avi files in users home directories. Search files can be found with the following command:

# find /home -name '*.avi'

If you want to search for *.mpg and *.avi files, you will use the following:

find /home -name '*.mpg' -o -name '*.avi'

Case insensitive searches can be achieved by using the -iname switch:

find /home -iname '*.mpg' -o -iname '*.avi'

3. Adding some more criterias

Those kind of searches might returns far too many results, making it hard to find waht you were looking for in the first place.

Fortunately, you can narrow down the search by adding criteria such as the file size and the file modification date.

Let'search for .avi files bigger than 700M. This can be done with:

find /home/ -name '*.avi' -a -size +700M

Now, let's find the same subset of files that were modified less than 15 days ago:

find /home/ -name '*.avi' -a -size +700M -mtime -15

4. Adding some actions

Grand, we can now find files based on a subset of criteria. What would be even better is to apply some actions on those files. Action can be done with the use of -exec switch.
We can now find .avi file that are newer that 15 days, in this example, we are going to move those file to another location: /my/new/movies . I consider that this directory already exist on your system.
Moving .avi files bigger than 700M and younger than 15 days to /my/new/movies can be done with:

find /home/ -name '*.avi' -a -size +700M -mtime -15 -exec mv '{}' /my/new/movies/ \;

Mind the use of '{}' and \; (there is a space before \;).
'{}' matches the file that was found, while \; terminate the exec statement.

5. Conclusion

find is a powerful tool with an extensive set of statement. This article only covered a small subset of available features. For more information on the find command I recommend checking out its man page.



Powered by ScribeFire.

Saturday, November 10, 2007

Single Instance Application

Making an application single instance, can be achieved by using a mutex (Mutual Exclusion Semaphore). A Windows application loads the main form through the Application.Run( ) method. In the Main method, create a new mutex. If a new mutex is created the application is allowed to run. If the mutex has already been created, the application cannot start. This will ensure that only one instance will be running at any time.

// Used to check if we can create a new mutex
bool newMutexCreated = false;
// The name of the mutex is to be prefixed with Local\ to make
// sure that its is created in the per-session namespace,
// not in the global namespace.
string mutexName = "Local\\" +
 System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

Mutex mutex = null;
try
{
   // Create a new mutex object with a unique name
   mutex = new Mutex(false, mutexName, out newMutexCreated);
}
catch(Exception ex)
{
   MessageBox.Show (ex.Message+"\n\n"+ex.StackTrace+
        "\n\n"+"Application Exiting...","Exception thrown");
   Application.Exit ();
}

// When the mutex is created for the first time
// we run the program since it is the first instance.
if(newMutexCreated)
{
   Application.Run(new AnimatedWindowForm());
}

When a new mutex is created the mutex name can be prefixed with either Global\ or Local\. Prefixing with Global\ means the mutex is effective in the global namespace.

Prefixing with Local\ means the mutex is effective in the user's session namespace only.

Windows XP and Windows 2003 allow fast user switching through Terminal Services Sessions. So if a mutex is created with a Global\ prefix, the application can have only one instance system wide. So if one user launches the application, other users cannot create a second instance in their sessions. If the mutex is not prefixed with Local\ it is effective per session only.

Placing Your C# Application in the System Tray

  1. To get started, open an existing C# Windows form (or create a new one).
  2. Open the Visual Studio Toolbox.
  3. Drag a NotifyIcon control onto the form. The control will named notifyIcon1 by default and placed below the form because it has no visual representation on the form itself.
  4. Set the NotifyIcon control's Text property to the name you want to appear when the user pauses the mouse over the application's icon. For example, this value could be "KillerApp 1.0".
  5. Set the control's Icon property to the icon that you want to appear in the System Tray
  6. Add an event handler for the form's Resize event that will hide the application when it's minimized. That way, it won't appear on the task bar.
  7. private void Form1_Resize(object sender, System.EventArgs e)
    {
      if (FormWindowState.Minimized == WindowState)
         Hide();
    }
    
  8. Add an event handler for the NotifyIcon.DoubleClick event and code it as follows so that the application will be restored when the icon is double-clicked.
  9. private void notifyIcon1_DoubleClick(object sender,
                                        System.EventArgs e)
    {
       Show();
       WindowState = FormWindowState.Normal;
    }
    

At this point, your application will fuction perfectly in terms of an icon appearing in the System Tray when the application is run (see Figure 1), the application not appearing on the task bar when minimized and the application restoring itself when the Tray icon is double-clicked.

Figure 1

Now, let's see the steps involved with adding a context menu to the icon.

  1. From the Visual Studio Toolbox, drag a ContextMenu control onto the form.
  2. Right-click the ContextMenu control and select the Edit Menu.option.
  3. Type in the options that you want to appear in your context menu. For example, you can add options such as Restore and Close Application.
  4. As with any menu, double-click the menu item to create and code each item's handler. As an example, you could copy the code from the form's DoubleClick handler into the context menu's Restore handler and for the Close Application menu item; simply call the form's Close method.
  5. Finally, set the NotifyIcon control's ContextMenu property to the new context menu you just created by selecting the menu from the drop-down list. Figure 2 shows a simple Tray context menu.

Visual Studio Setup and Deployment

Video: Delayed Startup Setup Project CodeProjec Example