Feb 25 2010

String in Byte Array und zurück wandeln

Tag: .NETMichael @ 8:54
private byte[] StringToByteArray(string sourceString)
{
    System.Text.ASCIIEncoding sourceEncoding = new System.Text.ASCIIEncoding();
    return sourceEncoding.GetBytes(sourceString);
}

private string ByteArrayToString(byte[] sourceArray)
{
    System.Text.ASCIIEncoding sourceEncoding = new System.Text.ASCIIEncoding();
    return sourceEncoding.GetString(sourceArray);
}

Feb 01 2010

ASP.NET FormsAuthentication – Persistant Ticket/Cookie

Tag: .NETMichael @ 12:19

Ich hatte einen recht eigenartigen Effekt bei FormsAuthentication in Zusammenhang mit einem persistant Authentickation Ticket.

Ein mit der Methode “FormsAuthentication.GetAuthCookie” erzeugtes Ticket war nur 30 Minuten gültig, obwohl ich überall gelesen habe, das ein so erzeugtes Ticket 50 Jahre gültig sein sollte.

Daher erstelle ich das Ticket jetzt von “Hand”, verschlüssele es und schreibe es in ein Cookie:

protected void Login_LoggedIn(object sender, EventArgs e)
{
	var ctrLogin = (Login) sender;
	var persistCheckBox = ctrLogin.FindControl("PersistCheckBox") as CheckBox;
	var isPersistent = persistCheckBox != null ? persistCheckBox.Checked : false;

	var authTicket = new FormsAuthenticationTicket(1, ctrLogin.UserName, DateTime.Now, isPersistent ? DateTime.Now.AddYears(2) : DateTime.Now.AddHours(1), isPersistent, "");
	var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)) {Expires = DateTime.Now.AddYears(2)};

	Response.Cookies.Add((authCookie));

	BayDirUser.SetUser(ctrLogin.UserName, ctrLogin.Password);

	if (_redirectUrl != null && !_redirectUrl.Equals(string.Empty))
		Response.Redirect(_redirectUrl, isPersistent);
	else
		Response.Redirect(FormsAuthentication.GetRedirectUrl(ctrLogin.UserName, isPersistent));
}

Jan 28 2010

ASP.NET FormsAuthentication – Logout

Tag: .NETMichael @ 13:00

ASP.NET FormsAuthentication – Logout

protected void LoggedOut(object sender, EventArgs e)
{
	FormsAuthentication.SignOut();
	HttpCookie authCookie = Context.Response.Cookies.Get(FormsAuthentication.FormsCookieName);

	if (authCookie != null)
		authCookie.Expires = DateTime.Now.AddYears(-1);

	Session.Abandon();

	Response.Redirect("~/default.aspx", true);
}

Jan 27 2010

Nur eine Instanz eines Programms zulassen

Tag: .NETMichael @ 12:58

Mit diesem Code wird verhindert man, das eine Applikation mehr als einmal innerhalb einer Session (Anmeldung) ausgeführt werden kann:

private const string AppGuid = "97E652FF-73A5-3ED6-A4E5-DA2AF2132C98";

[STAThread]
private static void Main()
{
	using (Mutex progMutex = new Mutex(false, AppGuid))
	{
		if (!progMutex.WaitOne(0, false))
		{
			MessageBox.Show("Dieses Programm ist bereits geöffnet");
			return;
		}

		Application.Run(new Form1());

	}
}

Soll die Anwendung in allen Sessions nur einmal ausgeführt werden können, muss man den Mutex in den global Namespace schreiben:

private const string AppGuid = "97E652FF-73A5-3ED6-A4E5-DA2AF2132C98";

[STAThread]
private static void Main()
{
	using (Mutex progMutex = new Mutex(false, @"Global\" + AppGuid))
	{
		if (!progMutex.WaitOne(0, false))
		{
			MessageBox.Show("Dieses Programm ist bereits geöffnet");
			return;
		}

		Application.Run(new Form1());

	}
}

Nov 16 2009

C# Internetverbindung testen

Tag: .NETMichael @ 14:17
[DllImport("WININET", CharSet = CharSet.Auto)]
static extern bool InternetGetConnectedState(int lpdwFlags, int dwReserved);

public bool CheckInternetConnection()
{
	return InternetGetConnectedState(0, 0);
}

Nov 06 2009

Enumeration in einem WCF Service

Tag: .NETMichael @ 14:31

Um eine Enumeration in einem WCF Sefvice an den Client zu übertragen, muss das [ServiceKnownType(typeof(Enum))] Attribute in den Service Contract eingefügt werden:

namespace TestService.Interfaces
{
    [ServiceContract]
    [ServiceKnownType(typeof(MyEnum))]
    public interface ITestService
    {
        [OperationContract]
        ....
    }
}

Die Enumeration sieht dann so aus:

namespace TestService.Classes
{
 	[DataContract]
	public enum MyEnum
	{
		[EnumMember]
		Undefined = 0,

		[EnumMember]
		 Okay = 1,

		[EnumMember]
		Error = 2
	}

    [DataContract]
	public class MyClass
    {
		...
	}
}

Mrz 12 2009

C# Equivalent für VB’s “Left” Funktion

Tag: .NETMichael @ 13:35
public static string Left(string strText, int intLength)
{
    try
	{
		if (intLength < 0)
			throw new ArgumentOutOfRangeException("Length", intLength, "Length must be > 0");
		else if (intLength == 0 || strText.Length == 0)
			return "";
		else if (strText.Length <= intLength)
			return strText;
		else
			return strText.Substring(0, intLength);
	}
	catch {}
}

Dez 18 2008

C#: Den MD5 Hash eines Strings als String

Tag: .NETMichael @ 18:42
public string getMD5Hash(string strSource)
{
String strResult;

if ((strSource == null) || (strSource.Length == 0))
{
strResult = string.Empty;
}
else
{

System.Security.Cryptography.MD5CryptoServiceProvider objMD5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] arrTextToHash = Encoding.Default.GetBytes(strSource);
byte[] arrResult = objMD5.ComputeHash(arrTextToHash);

strResult =  System.BitConverter.ToString(arrResult);
}

return strResult;
}

Nov 06 2008

VB.Net: Schließen eines Forms verhindern

Tag: .NETMichael @ 11:46
Private Sub DoFormClosing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If MessageBox.Show("Wollen Sie das Fenster schließen?", "Fenster schließen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
            e.Cancel = False
        Else
            e.Cancel = True
        End If
End Sub

Sep 25 2008

VB.NET: Erster Buchstabe als Grossbuchstabe

Tag: .NETMichael @ 8:14
Dim strValue As String = "let's test this."

MsgBox(StrConv(strValue, VbStrConv.ProperCase))

Nächste Seite »