Friday, February 6, 2009

Running a .bat file using C# Process

Process.Start(@"C:\
Program Files\Adobe\After Effects 6.5\Support Files\afterfx.exe", "-r " + path2);


Mod funtion in c#?

//Mode Function in C#.net
if(n%3==0)
{
//do this
}
else
{
//do that
}

Sorting 2 dimensional array/arraylist

See code snippet for an example. Let me know if you have a question.

Fernando
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;


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

private void button1_Click(object sender, EventArgs e)
{
// Holds the list from the file
List<String> dataSorted = new List<string>();
// Read the lines from the file
StreamReader sr = new StreamReader("Data.txt");
while (!sr.EndOfStream)
{
// insert line into list
dataSorted
.Add(sr.ReadLine());
}
// Sort the list with a custom compare
dataSorted
.Sort(AddressCompare);

// Display the list to the console window or write to file
foreach( String data in dataSorted )
{
Console.WriteLine(data);
}
}

int AddressCompare(object x, object y)
{
// Two null objects are equal
if (x == null && y == null) return 0;
//Any object that is not null is greater then an object that is null
if (x == null) return -1;
if (y == null) return 1;

// CheckBox to see that both objects are Strings
if (!(x.GetType() == typeof(String) && y.GetType() == typeof(String)))
{
throw new ArgumentException("Can't compare " + x.GetType().ToString() +
"/" + y.GetType().ToString());
}

// Parse the string to get the address
String[] addr = new String[2];
String[] type = new String[2];
type
[0] = x.ToString().Substring(0, 2);
type
[1] = y.ToString().Substring(0, 2);
for (int idx = 0; idx < 2; idx++)
{
// Not sure how long the address field is so I added all the types given in the
// you will need to modify the length of the address for each type element 0 is
// the x string and element 1 is the y string.
switch (type[idx])
{
case "S0":
if (idx == 0)
{
addr
[0] = x.ToString().Substring(4, 6);
}
else
{
addr
[1] = y.ToString().Substring(4, 6);
}
break;
case "S3":
if (idx == 0)
{
addr
[0] = x.ToString().Substring(4, 6);
}
else
{
addr
[1] = y.ToString().Substring(4, 6);
}
break;
case "S5":
if (idx == 0)
{
addr
[0] = x.ToString().Substring(4, 6);
}
else
{
addr
[1] = y.ToString().Substring(4, 6);
}
break;
case "S7":
if (idx == 0)
{
addr
[0] = x.ToString().Substring(4, 6);
}
else
{
addr
[1] = y.ToString().Substring(4, 6);
}
break;
}
}
// Convert hex string to integer
int[] key = new int[2];
key
[0] = int.Parse(addr[0], System.Globalization.NumberStyles.HexNumber);
key
[1] = int.Parse(addr[1], System.Globalization.NumberStyles.HexNumber);

// compare integer values
if (key[0] == key[1]) return 0;
if (key[0] < key[1]) return -1;
return 1;
}
}
}

Using C# how do get image size (bytes) from a image obtained from a URL

Hi,
You should download the image first and then check the image size. I dont think there is any other option

Here is the c# code for Image/File download
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
private int DownloadImage(string link)
{
try
{
Uri uri = new Uri(link);
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest
.Method = "GET";

webrequest
.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, */*";

webrequest
.KeepAlive = false;
HttpWebResponse responce = (HttpWebResponse)webrequest.GetResponse();
Stream S = responce.GetResponseStream();
FileStream writeStream = new FileStream(<<FilePath>, FileMode.Create, FileAccess.Write); //Filepath to save
ReadWriteStream(S, writeStream);
responce
.Close();
return 1;
}
catch (Exception)
{
return 0;
}
}

// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream
.Write(buffer, 0, bytesRead);
bytesRead
= readStream.Read(buffer, 0, Length);
}
readStream
.Close();
writeStream
.Close();
}

Capture mouse click before control in VB.net

Copy the following code snippet your form. I got this code from the thread above and just added a public variable to store the control that the mouse is currently over.

Public Class Form2

Public myCtrlOver As String
Private WithEvents mf As New MyFilter

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Application.AddMessageFilter(mf)
End Sub

Private Sub mf_MouseMove() Handles mf.MouseMove
If Form.ActiveForm Is Me Then
Dim clientPT As Point
Dim formPT As Point = Me.PointToClient(Cursor.Position)
Dim ctlName As String
Dim ctl As Control = FindControl(Me)
If Not IsNothing(ctl) Then
ctlName
= ctl.Name
clientPT
= ctl.PointToClient(Cursor.Position)
Else
ctlName
= Me.Name
clientPT
= Me.PointToClient(Cursor.Position)
End If
' Debug.Print(ctlName & ": " & clientPT.ToString & " Form: " & formPT.ToString)

myCtrlOver = ctlName

Me.Label1.Text = ctlName
Me.Label1.Refresh()
Else
'
...WM_MOUSEMOVE is targeting a form other than this one...
End If
End Sub

Private Function FindControl(ByVal cont As Control) As Control
Dim ctl As Control = cont.GetChildAtPoint(cont.PointToClient(Cursor.Position))
If Not IsNothing(ctl) Then
If ctl.HasChildren Then
Dim subCtl As Control = FindControl(ctl)
If Not IsNothing(subCtl) Then
Return subCtl
Else
Return ctl
End If
Else
Return ctl
End If
Else
Return Nothing
End If
End Function

Private Class MyFilter
Implements IMessageFilter

Public Event MouseMove()
Private Const WM_MOUSEMOVE As Integer = &H200

Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage
Select Case m.Msg
Case WM_MOUSEMOVE
RaiseEvent MouseMove()

End Select
End Function

End Class

Private Sub Form2_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown

If myCtrlOver <> "YourMenuPanelName" Then

' Put your code here to close the menu

End If

End Sub
End Class

c# textbox validation

Question:

I have a form that contain several textboxes that are bound to a database.row that has int32 as datatype and allows dbNull value. When a user starts up the form, the code inserts three values (this is because the user needs to know these values before filling in the rest), and fills the tableadapter with data so many textboxes is bound to dbNull value.

The form has many textboxes bound to a SQL-database and the form functions very well if you put correct data into the form. I also have checks on the textboxes that must have int as datatyp that the text is possible to parse as an int (so all checks is ok).

My problem is as follows:
1. If a user "tabs" his way throug the form and accidentally puts a character into a textbox that must have an int they get a warning saying the textbox can only contain integers.
2. If they delete the character the textbox.validate() locks the control and I cannot get the form to do anything until the user puts in an int into the box. If the user puts in an int the validatoin works and form is unlocked again. I want it also to validate=true when textbox is empty, but I cannot seem to get this to work.
3. I want to set the textbox back to its previous state whenever the textbox.text.length == 0, because then it is the same as when you open the form and this validates fine (because it contains no data).
4. Attached code that I have to check the textboxes, but the only thing that happens is textboxSjekk.clear() and then the form locks itself because an empty textbox does not validate to int (but an empty textbox on startup does).

Hope this was understandable.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
private void feilMldTall(TextBox textBoxSjekk, string feilKontroll)
{
if (textBoxSjekk.Text.Length > 0)
{
try
{ Int32.Parse(textBoxSjekk.Text); }
catch (Exception)
{
MessageBox.Show("Can only contain int");

}
}
else
{
textBoxSjekk
.Clear();
}

}
ANSWER:
implement the validating event of textboxes:

private void textBoxSjekk_Validating(ob
ject sender, CancelEventArgs e)
{
if (textBoxSjekk.Text.Length > 0)
{
try
{ Int32.Parse(textBoxSjekk.Text); }
catch (Exception)
{
MessageBox.Show("Can only contain int");
textBoxSjekk.Clear();
textBoxSjekk.Focus();
}
}
}

If you want to restore to the previous valid state of the textbox:

public partial class Form1 : Form
{
string _previousValidTextBoxSjekk;
public Form1()
{
InitializeComponent();
textBoxSjekk.Text = "2";
_previousValidTextBoxSjekk = textBoxSjekk.Text; //initialize
}

private void textBoxSjekk_Validating(object sender, CancelEventArgs e)
{
if (textBoxSjekk.Text.Length > 0)
{
int i;
if(!Int32.TryParse(textBoxSjekk.Text,out i))
{

MessageBox.Show("Can only contain int");
textBoxSjekk.Text = _previousValidTextBoxSjekk;
textBoxSjekk.Focus();
return;
}
_previousValidTextBoxSjekk = textBoxSjekk.Text; // here if you only want to restore to a populated state of the textbox once it was populated at some point in time
}
// _previousValidTextBoxSjekk = textBoxSjekk.Text ; //here if you want to add also empty as a previous valid state
}
}

Get processor id using c#.net

Try this (add
reference to System.Management):

public string GetCPUId()
{
string cpuInfo = String.Empty;
string temp = String.Empty;
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (cpuInfo == String.Empty)
{// only return cpuInfo from first CPU
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
}
}
return cpuInfo;
}