ShareThis

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, August 4, 2013

[C#] WinForms - How to add your own methods to Control functions [with anonymous methods]

Adding your own methods to event handlers on controls is super easy.


Example 1
txtDataReceived.Click += delegate { foo(localVariable1,localVariable2); };
Example 2
imgbtn.Click += delegate { lbl.Visible = false; DoPostBack(); }; 

Wednesday, December 19, 2012

[C#] Get ONLY filename and extension from OpenDialog in C# WinForms

All you need to do in order to get the filename from an OpenDialog in C# is to use this method:

OpenFileDialog.SafeFileName

Example of an OpenFileDialog's FileName attribute: C://fakepath//item.txt
Example of an OpenFileDialog's SafeFileName attribute: item.txt

Tuesday, December 18, 2012

[C#][FIX] Cross-thread operation not valid in Winforms with threads.

A common problem using WinForms in Visual Studio is syncing between logic threads and UI threads. Most winform applications should use a method to sync between both; otherwise, you will see the Form freeze while waiting for the logic to complete.

The following shows an example of calling a function that creates a delegate to do cross-thread operations.

Code:

private void ThreadSafeFunction(int intVal, bool boolVal)
{
    if (this.InvokeRequired)
    {
        this.Invoke(
            new MethodInvoker(
            delegate() { yourMethod(intVal, boolVal); }));
    }
    else
    {
        //use intval and boolval
    }
}   

To use this method of cross-thread operations, call the ThreadSafeFunction in your logic thread.

In the curly brackets if the new delegate (), place any UI logic that needs to be done (i.e. yourTextbox.Text = intVal)

After you have updated the code to work with your WinForm, try it out and let us know how it goes!

Thursday, July 19, 2012

[C#] Split string into array and trim (one line!)

This is a badass solution to a common problem:


emails.Split(',').Select(email => email.Trim()).ToArray()

WinForms - Open Dialog *.xls | *.xlsx Filter example

To set your open dialog so only excel files can seen, use the following code on the Filter property:

(*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*

Monday, July 16, 2012

[C#] Click Cursor programmatically

Here is some awesome code to click the cursor programmatically!

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

public class Form1 : Form
{
   [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
   public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

   private const int MOUSEEVENTF_LEFTDOWN = 0x02;
   private const int MOUSEEVENTF_LEFTUP = 0x04;
   private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
   private const int MOUSEEVENTF_RIGHTUP = 0x10;

   public Form1()
   {
   }

   public void DoMouseClick()
   {
      //Call the imported function with the cursor's current position
      int X = Cursor.Position.X;
      int Y = Cursor.Position.Y;
      mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
   }

   //...other code needed for the application
}

[C#] Get current project / working directory

All you need to use is Environment.CurrentDirectory

Example:
String dir = Environment.CurrentDirectory;

Tuesday, July 3, 2012

[C#] Populate XMLNode for Testing Purposes

XMLNode can be a nuisance because you cannot directly initialize it. If you need to have some populated XMLNode in your data, here is what you can do to populate it:


XmlDocument doc = new XmlDocument();
doc.LoadXml("<start><lap1></lap1><lap2></lap2><lap3></lap3></start>");
XmlNode node = doc.DocumentElement;

Friday, June 29, 2012

[C#] How to compare two HashSets

Example Data:


HashSet<int> set1 = new HashSet<int>();
set1.Add(1);
set1.Add(2);
set1.Add(3);
HashSet<int> set2 = new HashSet<int>();
set2.Add(1);
set2.Add(2);
set2.Add(3);



How you can compare one against the other:

if(set1.SetEquals(set2)){...}

Thursday, June 28, 2012

[C#] DateTime get the last day of the month

Here is a simple way to get the last day of the month we are in, in C#.

DateTime.DaysInMonth(DateTime.UtcNow.Year, DateTime.UtcNow.Month);

Tuesday, June 26, 2012

[C#] Foreach loop remove comma at the end C#

A common problem in programming is listing off elements in a for, foreach, or while loop using commas or another character to delimit them for a string display. However, using the simple logic:

string += nextItem.toString() + ", ";


will always lead to having an extra ',' at the end, like this:

A, B, C, D,

The trick , for NET 3.0 and higher, can be done in just TWO lines of code!

1. Set up your enumerable list of items.
List<string> namesList = myList.Select(id=> getName(id).Name).ToList();


2. Join your list into a string!
myString = String.Join(", ", namesList );


Monday, June 25, 2012

[C#] Count instances of a string in string with LINQ


// This will count the number of occurrences of 'X' in your string.
// You can look for strings and characters!
int total = yourString.Count(x => x == 'X'); 



Thursday, June 21, 2012

[ASP] Get enum int value from aspx markup in javascript

This stumbled me as casting to an (int) in the markup like this did not work:
case <%= (int) MyEnumType.USA %>:
case <%= Int32.Parse(MyEnumType.USA) %>:
The correct usage is with Convert.ChangeType(...) method:

<%= Convert.ChangeType(MyEnum.USA, MyEnum.USA.GetTypeCode()) %>

Monday, June 18, 2012

C# - Iterate over a HashSet

You can use a HashSet<T>.Enumerator, but that is unnecessary. The same can be accomplished using a foreach loop as it hides the complexity of the enumerator.

Example:


HashSet<int> valueSet = new HashSet<int>();
foreach (int value in valueSet)
{
 // use your hash set values here!   
}

Related StackOverflow Questions: 

What is the fastest/safest method to iterate over a HashSet?

Monday, June 4, 2012

C# Cast string to a long

long MyLong = Int64.Parse( MyString );

or

long MyLong = Convert.ToInt64(MyString);

Sunday, March 11, 2012

How to Stop Resharper use var implicitly suggestions


Go into Resharper-->Options and scroll down and turn the settings off. Saves you from having to deal with the annoying underlines on good code!!!



Wednesday, February 8, 2012

[C#] Get Extension part of Url


You can split it on .:
string url = "www.abc.com/files.zip";
string lastPart = url.Split(new char[] {'.'}).Last()
lastPart == "zip"

Wednesday, February 1, 2012

C# Website Image Downloader is here! ImageGrabber


After a couple weeks of work… Im proud to pronounce ImageGrabber Free!
Why use it? - It will scour a page for any images and download them for you to the requested filefolder.
- You’ll never have to manually save every image again.
- The ImageGrabber uses an advanced crawler that can crawl an entire domain, or the whole internet!! THE WHOLE INTERNET~~~
How to use it: You select a file folder, then paste your site URL, and select the crawler depth. Then crawl! Watch as your folder populates or the log refreshes with progress!
What is the catch? No catch. ImageGrabber Free will be offered with reduced capability. A pro version will be released later this year that gives users the most customizable experience.
Features that will be in pro: - Crawl ALL –> Every link given in will be processed.
-
File size restrictions. (Set lower / upper bound limits on file sizes to keep)
- FolderSort –> Sort images based on similar names
- StraightToZip –> Sort images based on similar names, then send to Zip files.

Monday, January 2, 2012

C# Escape Characters - New Line, Tab, etc


Table 4.1. Escape Sequences (Special Characters in C# Strings)

SEQUENCE
PURPOSE
\n
New line
\r
Carriage return
\r\n
Carriage return—new line
\"
Quotation marks
\\
Backslash character
\t
Tab

C# copy to clipboard : how to Copy-Paste to and from clipboard using c#


To make the operations such as copy paste using c#,we have to use the Clipboard Class which provides methods to place data on and retrieve data from the system Clipboard.
Example :-
Copy the text from txtCopy to clipboard
 System.Windows.Forms.Clipboard.SetDataObject(txtCopy.Text, true);
Paste the text from clipboard to txtPaste
IDataObject clipData = Clipboard.GetDataObject();
if (clipData.GetDataPresent(DataFormats.Text))
{
txtPaste.Text = clipData.GetData(DataFormats.Text).ToString();
}
else
{
txtPaste.Text = "Could not retrieve data from the clipboard.";
}