using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Net;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Globalization;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Management;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
namespace De.Lambertz.Essentials
{
public class EssentialTools
{
//private static String smtpServer = "MAIL01AC"; //StandortIndex 1
private static String smtpServer = "mail.intra.lambertz.de"; //StandortIndex 1
private static String smtpServerPolen = "mail.intra.lambertz.de"; //StandortIndex 2
private static int standortIndex = 0;
private static CultureInfo germanCultureInfo = new CultureInfo("de-DE");
private static bool isDeveleoperPC = false;
private static bool isDeveleoperPCGeprüft = false;
private const string ERLAUBTE_SUBNETZE = "|20|21|22|23|24|25|1|4|14|8|33|0|9|44|5|111|115|116|118|112|119|114|117|22|24|10|11|12|199|";
//private const int ERROR_LOGON_FAILURE = 0x31;
public static bool ValidatePassword(string password)
{
String usernameWithDomain = WindowsIdentity.GetCurrent().Name;
return ValidateCredentials(usernameWithDomain, password);
}
public static string MaximalLängePrüfen(String text, int maximalLänge, bool istDateiname = false)
{
string result = text;
if(result.Length>maximalLänge)
{
if(istDateiname)
{
String endung = Path.GetExtension(result);
result = result.Substring(0, maximalLänge-endung.Length);
result = result + endung;
}
else
{
result = result.Substring(0, maximalLänge);
}
}
return result;
}
public static bool IsFileReady(string filePath, int retryCount, int delay)
{
for (int i = 0; i < retryCount; i++)
{
try
{
// Versuche die Datei exklusiv zu öffnen
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (stream.Length > 0)
{
// Datei konnte exklusiv geöffnet werden
return true;
}
}
}
catch (IOException)
{
// Warte, falls Datei noch in Benutzung ist
Thread.Sleep(delay);
}
}
return false;
}
public static bool IsDeveloperPC()
{
if (!isDeveleoperPCGeprüft)
{
if ((Environment.MachineName == "NAC666" && EssentialTools.GetCpuID() == "BFEBFBFF000A0652") || (Environment.MachineName == "NAC521" && EssentialTools.GetCpuID() == "BFEBFBFF000806EC"))
{
isDeveleoperPC = true;
}
isDeveleoperPCGeprüft = true;
}
return isDeveleoperPC;
}
public static string GetCpuID()
{
string cpuid = string.Empty;
ManagementClass man = new ManagementClass("win32_processor");
ManagementObjectCollection moc = man.GetInstances();
foreach (ManagementObject mob in moc)
{
if (cpuid == "")
{
// Nimmt vom ersten CPU die ID und bricht dann ab.
cpuid = mob.Properties["processorID"].Value.ToString();
break;
}
}
return cpuid;
}
public static int CountWeekdays(DateTime startTime, DateTime endTime)
{
TimeSpan timeSpan = endTime - startTime;
DateTime dateTime;
int weekdays = 0;
for (int i = 0; i < timeSpan.Days; i++)
{
dateTime = startTime.AddDays(i);
if (IsWeekDay(dateTime))
weekdays++;
}
return weekdays;
}
public static bool IsWeekDay(DateTime dateTime)
{
return ((dateTime.DayOfWeek != DayOfWeek.Saturday) && (dateTime.DayOfWeek != DayOfWeek.Sunday));
}
public static IPAddress LokaleIPAdresse(bool bereichPrüfen = true)
{
IPAddress result = null;
try
{
string[] adressen = null;
ManagementObjectSearcher NetworkInfo = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection MOC = NetworkInfo.Get();
foreach (ManagementObject mo in MOC)
{
adressen = (string[])mo["IPAddress"];
}
if (adressen != null)
{
foreach (String adresse in adressen)
{
if (adresse.Contains("."))
{
try
{
String[] x = adresse.ToString().Split(".".ToCharArray());
if (!bereichPrüfen || ERLAUBTE_SUBNETZE.Contains("|" + x[2] + "|"))
{
result = new IPAddress(ipToByteArray(adresse));
break;
}
}
catch (Exception)
{
}
}
}
}
}
catch (Exception)
{
System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry("");
//System.Net.IPAddress myIP = null;
foreach (System.Net.IPAddress a in host.AddressList)
{
if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
String[] x = a.ToString().Split(".".ToCharArray());
if (!bereichPrüfen || ERLAUBTE_SUBNETZE.Contains("|" + x[2] + "|"))
{
result = a;
break;
}
}
}
}
return result;
}
private static byte[] ipToByteArray(string Value)
{
string[] Temp = Value.Split('.');
int Length = Temp.Length;
byte[] Rueckgabe = new byte[Length];
for (int i = 0; i < Length; i++)
{
Rueckgabe[i] = Convert.ToByte(Convert.ToInt32(Temp[i]));
}
return Rueckgabe;
}
public static bool ValidateCredentials(string usernameWithDomain, string password)
{
String username = usernameWithDomain.Substring(usernameWithDomain.IndexOf("\\") + 1);
String domain = usernameWithDomain.Substring(0, usernameWithDomain.IndexOf("\\"));
return ValidateCredentials(username, password, domain);
}
public static bool ValidateCredentials(string username, string password, string domain)
{
if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password) && !String.IsNullOrEmpty(domain))
{
NetworkCredential credentials = new NetworkCredential(username, password, domain);
LdapDirectoryIdentifier id = new LdapDirectoryIdentifier(domain);
using (LdapConnection connection = new LdapConnection(id, credentials, AuthType.Kerberos))
{
connection.SessionOptions.Sealing = true;
connection.SessionOptions.Signing = true;
try
{
connection.Bind();
}
catch (LdapException)
{
//if (ERROR_LOGON_FAILURE == lEx.ErrorCode)
//{
return false;
//}
}
}
return true;
}
else
{
return false;
}
}
public static CultureInfo GermanCultureInfo
{
get { return EssentialTools.germanCultureInfo; }
}
//public static void SetFont(Form f)
//{
// // f.Font = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
//}
public static float Scalefont(float originalSize, IntPtr handle)
{
float result = originalSize;
Graphics g = Graphics.FromHwnd(handle);
float dx = g.DpiX;
if (dx > 110)
{
result = result * 110 / dx;
}
return result;
}
public static DateTime TagAnfang(DateTime datum)
{
return new DateTime(datum.Year, datum.Month, datum.Day, 0, 0, 0);
}
public static DateTime TagEnde(DateTime datum)
{
return new DateTime(datum.Year, datum.Month, datum.Day, 23, 59, 59);
}
///
/// Prüft ob eine Date mit selben Namen schon vorhanden ist
/// und hängt ggfs. eine laufende Nummer an
///
///
///
public static string CheckFileName(string name)
{
name = cleanFilename(name);
bool nameOK = false;
int i = 0;
while (!nameOK)
{
nameOK = true;
FileInfo fi = new FileInfo(name);
if (fi.Exists)
{
//Datei vorhanden. Name muss verändert werden...
i++;
string part2 = name.Substring(name.LastIndexOf("."));
string part1 = name.Substring(0, name.Length - part2.Length);
int c = extractCounter(name);
if (c > 0)
{
string temp = part1.Substring(0, part1.Length - c.ToString().Length);
if (temp.EndsWith("_"))
{
part1 = part1.Substring(0, part1.LastIndexOf("_"));
i = c + 1;
}
}
StringBuilder neuerName = new StringBuilder();
neuerName.Append(part1);
neuerName.Append("_");
neuerName.Append(i.ToString());
neuerName.Append(part2);
//
name = neuerName.ToString();
nameOK = false;
}
}
return name;
}
private static int extractCounter(string filename)
{
string pattern = @"_(\d+)\.[a-zA-Z0-9]+$";
Match match = Regex.Match(filename, pattern);
if (match.Success)
{
// Extrahiere die gefundene Zahl und gib sie als Integer zurück
return int.Parse(match.Groups[1].Value);
}
else
{
return 0;
}
}
private static string cleanFilename(string filename)
{
string result;
String pfad = Path.GetDirectoryName(filename);
String datei = Path.GetFileName(filename);
// Definiere das Muster für ungültige Zeichen
string pattern = @"[\\/:*?""<>|]";
//Ersetze ungültige Zeichen durch einen Unterstrich
datei = Regex.Replace(datei, pattern, " ");
result = Path.Combine(pfad, datei);
return result;
}
public static bool IsNumeric(object expression)
{
bool isNum = false;
if (expression != null)
{
double retNum;
isNum = double.TryParse(Convert.ToString(expression), out retNum);
}
return isNum;
}
public static bool IsNumericInteger(object expression)
{
bool isNum = false;
if (expression != null)
{
int retNum;
isNum = int.TryParse(Convert.ToString(expression), out retNum);
}
return isNum;
}
public static string ZeilenUmbrücheEntfernen(String text, String token = " ")
{
String result = text.Replace("\r\n", token);
result = result.Replace("\n\n", token);
result = result.Replace("\n\n\n", token);
result = result.Replace("\r", "");
result = result.Replace("\n", token);
return result;
}
public static string AbweichungBerechnen(double aktuell, double vorjahr)
{
string result = null;
if (aktuell != 0 && vorjahr != 0)
{
double e;
if (vorjahr == 0)
{
e = 0;
}
else
{
e = (aktuell - vorjahr) / vorjahr * 100;
}
if (e > 500)
{
result = "-";
}
else if (e < -100)
{
result = "-";
}
else
{
result = e.ToString("0.0");
}
}
else
{
result = "0";
}
return result;
}
public static string GetBaseTempPath()
{
return GetBaseTempPath(null);
}
public static string GetBaseTempPath(string add)
{
string userBasePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
userBasePath = Path.Combine(userBasePath, "LambertzPortal");
//MessageBox.Show(userBasePath);
if (!String.IsNullOrEmpty(add))
{
userBasePath = Path.Combine(userBasePath, add);
}
DirectoryInfo di = new DirectoryInfo(userBasePath);
if (!di.Exists)
{
di.Create();
}
return userBasePath;
}
//public static DataGridViewCellStyle FormatiereZeile(System.Drawing.Color hintergrundfarbe, System.Drawing.Color schriftfarbe, bool fett)
//{
// DataGridViewCellStyle result = new DataGridViewCellStyle();
// result.BackColor = hintergrundfarbe;
// result.ForeColor = schriftfarbe;
// if (fett)
// {
// System.Drawing.Font f = new System.Drawing.Font("Arial", 8.25f, FontStyle.Bold);
// result.Font = f;
// }
// else
// {
// System.Drawing.Font f = new System.Drawing.Font("Arial", 8.25f, FontStyle.Regular);
// result.Font = f;
// }
// return result;
//}
public static bool IsEmail(string inputEmail)
{
bool result = false;
if (!String.IsNullOrEmpty(inputEmail))
{
string strRegex = @"^([a-zA-Z0-9|ü|ä|ö|Ü|Ä|Ö_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
{
result = true;
}
//Zusatz für ExchangeMails...
if (!result)
{
inputEmail = inputEmail.ToLower();
if (inputEmail.Contains(@"/cn=") && inputEmail.Contains(@"/ou=") && inputEmail.Substring(0, 3) == "/o=")
{
result = true;
}
}
}
return result;
}
[DllImport("User32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
public static extern int AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, bool fAttach);
[DllImport("User32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("User32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hwnd, IntPtr lpdwProcessId);
[DllImport("user32.dll")]
static extern bool AllowSetForegroundWindow(int procID);
//public static void SetForegroundWindowEx(Form window)
//{
// IntPtr hndl = window.Handle;
// IntPtr threadID1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
// IntPtr threadID2 = GetWindowThreadProcessId(hndl, IntPtr.Zero);
// window.TopMost = true;
// if (threadID1 == threadID2)
// {
// SetForegroundWindow(hndl);
// }
// else
// {
// AttachThreadInput(threadID2, threadID1, true);
// SetForegroundWindow(hndl); ;
// AttachThreadInput(threadID2, threadID1, false);
// }
//}
public static void SetForegroundWindowEx(IntPtr hndl)
{
IntPtr threadID1 = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
IntPtr threadID2 = GetWindowThreadProcessId(hndl, IntPtr.Zero);
if (threadID1 == threadID2)
{
SetForegroundWindow(hndl);
}
else
{
AttachThreadInput(threadID2, threadID1, true);
SetForegroundWindow(hndl); ;
AttachThreadInput(threadID2, threadID1, false);
}
}
public static String AlleIPAdressen()
{
String result = "";
String token = "";
bool weg2 = true;
try
{
string[] adressen = null;
ManagementObjectSearcher NetworkInfo = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
ManagementObjectCollection MOC = NetworkInfo.Get();
foreach (ManagementObject mo in MOC)
{
adressen = (string[])mo["IPAddress"];
}
foreach (String a in adressen)
{
if (a.Contains("."))
{
result = result + token + a;
token = ", ";
weg2 = false;
}
}
}
catch (Exception)
{
if(String.IsNullOrEmpty(result))
{
weg2 = true;
}
}
if(weg2)
{
System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry("");
foreach (System.Net.IPAddress a in host.AddressList)
{
if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
try
{
result = result + token + a.ToString();
token = ", ";
}
catch (Exception)
{
//
}
}
}
}
return result;
}
public static string WindowsLogin()
{
WindowsIdentity windowsUserIndentity = WindowsIdentity.GetCurrent();
return windowsUserIndentity.Name;
}
//public static ActiveDirectoryUser GetActiveDirectoryUserInfoFromLogin(String login)
//{
// ActiveDirectoryUser result = new ActiveDirectoryUser();
// DirectoryEntry de = new DirectoryEntry();
// DirectorySearcher ds = new DirectorySearcher(de);
// ds.Filter = "(samaccountname=" + login + ")";
// string[] requiredProperties = new string[] { "cn", "samaccountname", "displayname", "telephonenumber", "mobile", "mail", "givenname" };
// foreach (String property in requiredProperties)
// {
// ds.PropertiesToLoad.Add(property);
// }
// SearchResult sr = ds.FindOne();
// if (sr != null)
// {
// ResultPropertyCollection fields = sr.Properties;
// foreach (String ldapField in fields.PropertyNames)
// {
// foreach (Object myCollection in fields[ldapField])
// {
// switch (ldapField)
// {
// case "displayname":
// result.DisplayName = myCollection.ToString();
// break;
// case "telephonenumber":
// result.TelefonNummer = myCollection.ToString();
// break;
// case "mobile":
// result.MobilNummer = myCollection.ToString();
// break;
// case "mail":
// result.EMail = myCollection.ToString().Replace("@LAMBERTZ.DE", "@Lambertz.com");
// break;
// case "givenname":
// result.NachName = myCollection.ToString();
// break;
// case "cn":
// result.Login = myCollection.ToString();
// break;
// }
// //Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString()));
// }
// }
// }
// return result;
//}
public static string FürDateiNamenBereinigen(String name)
{
name = name.Replace("\"","");
name = name.Replace("/", "");
name = name.Replace("\\", "");
name = name.Replace(":", "");
name = name.Replace("*", "");
name = name.Replace("?", "");
name = name.Replace(">", "");
name = name.Replace("|", "");
return name;
}
public static DateTime ConvertToDate(object datum)
{
DateTime result = DateTime.MinValue;
if (datum != null)
{
result = ConvertToDate(datum.ToString());
}
return result;
}
public static DateTime ConvertToDate(String datum)
{
DateTime result = DateTime.MinValue;
if(!String.IsNullOrEmpty(datum))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("de-DE");
System.Globalization.DateTimeFormatInfo usaDateFormatInfo = culture.DateTimeFormat;
DateTime temp;
if (DateTime.TryParse(datum, usaDateFormatInfo, System.Globalization.DateTimeStyles.None, out temp))
{
result = temp;
}
else
{
if (DateTime.TryParse(datum, out temp))
{
result = temp;
}
}
}
return result;
}
//public static void ShowDgvWidths(DataGridView dataGridView)
//{
// foreach (DataGridViewColumn col in dataGridView.Columns)
// {
// System.Diagnostics.Debugger.Log(0, null, col.Width.ToString() + " ");
// }
//}
public static Process StartFile(string fileName)
{
if (!String.IsNullOrWhiteSpace(fileName))
{
return StartFile("", fileName);
}
else
{
return null;
}
}
//public static void LoadDgvLayout(String formName, DataGridView dgv)
//{
// DgvLayoutManager.Load(formName, dgv);
//}
//public static void SaveDgvLayout(String formName, DataGridView dgv)
//{
// DgvLayoutManager.Save(formName, dgv);
//}
//public static void DgvDrucker(String title, DataGridViewColumnCollection columns, DataGridViewRowCollection rows, String user, String folderName, String fileName)
//{
// DgvDrucker drucker = new DgvDrucker(title, columns, rows, user, folderName, fileName);
// drucker.PDFErstellen(false);
//}
public static Process StartFile(string option1, string fileName)
{
Process result = null;
String ext = Path.GetExtension(fileName).ToLower();
String parameter = (option1 + " " + "\"" + fileName.Trim() + "\"").Trim() ;
String pf = KernParameterSingelton.GetInstance().ProgrammVerknüpfung(ext);
if (String.IsNullOrEmpty(pf))
{
switch (ext)
{
case ".xls":
case ".xml":
result = System.Diagnostics.Process.Start("EXCEL.EXE", parameter);
break;
case ".xlsx":
case ".xlsm":
String prgPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
String prg;
if (File.Exists(Path.Combine(prgPath, @"Microsoft Office\Office12\MOC.EXE")) && !File.Exists(Path.Combine(prgPath, @"Microsoft Office\Office12\Excel.EXE")))
{
prg = Path.Combine(prgPath, @"Microsoft Office\Office12\MOC.EXE");
}
else
{
prg = "EXCEL.EXE";
}
result = System.Diagnostics.Process.Start(prg, parameter);
break;
default:
result = System.Diagnostics.Process.Start(fileName);
break;
}
}
else
{
result = System.Diagnostics.Process.Start(pf, parameter);
}
return result;
}
public static String GetSmtpServer()
{
string result = smtpServer;
if (standortIndex == 0)
{
String login = WindowsIdentity.GetCurrent().Name;
if (login.ToUpper().StartsWith("LAMBERTZPL"))
{
standortIndex = 2;
}
else
{
standortIndex = 1;
}
}
if (standortIndex == 2)
{
result = smtpServerPolen;
}
return result;
}
public static DateTime DayStartDate(DateTime date)
{
return (new DateTime(date.Year, date.Month, date.Day, 0, 0, 0));
}
public static DateTime DayEndDate(DateTime date)
{
return (new DateTime(date.Year, date.Month, date.Day, 23, 59, 59));
}
public static string KennwortVerschlüsseln(string text)
{
string result = null;
if (!String.IsNullOrEmpty(text))
{
byte[] wert;
byte[] hash;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
wert = Encoding.UTF8.GetBytes(text);
hash = md5.ComputeHash(wert);
result = Convert.ToBase64String(hash);
}
else
{
result = "";
}
return result;
}
public static string EncryptODAL(string text)
{
string result;
int zeichen;
result = "";
if (!String.IsNullOrEmpty(text))
{
for (int i = 0; i < text.Length; i++)
{
zeichen = (int)char.Parse(text.Substring(i, 1));
zeichen = zeichen - 16;
result = result + (char)zeichen;
}
}
return result;
}
///
/// Entschlüsselt ein übergebenes Kennwort
///
///
///
public static string DecryptODAL(string text)
{
string result = "";
int zeichen;
if (!String.IsNullOrEmpty(text))
{
for (int i = 0; i < text.Length; i++)
{
zeichen = (int)char.Parse(text.Substring(i, 1));
zeichen = zeichen + 16;
result = result + (char)zeichen;
}
}
return result;
}
public static object NullZuLeer(string text)
{
if (text == null)
{
text = "";
}
return text;
}
public static Version GetVersion(String text)
{
Version result = null;
int major = 0;
int minor = 0;
int built = 0;
int revision = 0;
if (!String.IsNullOrEmpty(text))
{
String[] arr = text.Split(".".ToCharArray());
if (arr.Length > 0)
{
Int32.TryParse(arr[0], out major);
}
if (arr.Length > 1)
{
Int32.TryParse(arr[1], out minor);
}
if (arr.Length > 2)
{
Int32.TryParse(arr[2], out built);
}
if (arr.Length > 3)
{
Int32.TryParse(arr[3], out revision);
}
}
result = new Version(major, minor, built, revision);
return result;
}
public static byte[] IconToBytes(Icon icon)
{
using (MemoryStream ms = new MemoryStream())
{
icon.Save(ms);
return ms.ToArray();
}
}
public static Icon BytesToIcon(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
{
return new Icon(ms);
}
}
public static String Get9400AnfrageSchlüssel(string satzArt, int appId, string userName, string server, string workstation, string select)
{
StringBuilder result = new StringBuilder(satzArt);
if (userName == null)
{
userName = "";
}
if (server == null)
{
server = "";
}
if (workstation == null)
{
workstation = "";
}
if (select == null)
{
select = "";
}
result.Append(appId.ToString("000"));
if (userName.Length <= 30)
{
result.Append(userName.ToUpper().PadRight(30));
}
else
{
result.Append(userName.Substring(0,30));
}
if (server.Length <= 30)
{
result.Append(server.PadRight(30));
}
else
{
result.Append(server.Substring(0, 30));
}
if (workstation.Length <= 30)
{
result.Append(workstation.PadRight(30));
}
else
{
result.Append(workstation.Substring(0, 30));
}
if (select.Length <= 1)
{
result.Append(select.PadRight(1));
}
else
{
result.Append(select.Substring(0, 1));
}
return result.ToString();
}
public static Version GetVersionVonFile(string pfad)
{
Version result = null;
if (File.Exists(pfad))
{
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(pfad);
if (fvi.FileVersion != null)
{
result = GetVersion(fvi.FileVersion);
}
else
{
result = new Version(0, 0, 0, 0);
}
}
else
{
result = new Version(0, 0, 0, 0);
}
return result;
}
public static String TextZuDatumsText(String text)
{
String result = text;
if (text.Length > 0)
{
if (text == "..")
{
result = DateTime.Now.ToString("d", germanCultureInfo);
}
else
{
if (text.StartsWith("..+") || text.StartsWith("..-"))
{
String text3b = text.Substring(2);
int x = 0;
if (Int32.TryParse(text3b, out x))
{
result = DateTime.Now.AddDays(x).ToString("d", germanCultureInfo); ;
}
else
{
result = DateTime.Now.ToString("d", germanCultureInfo); ;
}
}
else
{
if (text.Length == 4)
{
text = text.Substring(0, 1) + "." + text.Substring(1, 1) + "." + text.Substring(2);
}
if ((text.Length == 5 || text.Length == 7) && text.IndexOf(".") < 0)
{
text = "0" + text;
}
if ((text.Length == 6 || text.Length == 8) && text.IndexOf(".") < 0)
{
text = text.Substring(0, 2) + "." + text.Substring(2, 2) + "." + text.Substring(4);
}
DateTime temp;
if (DateTime.TryParse(text, out temp))
{
result = temp.ToString("d", germanCultureInfo); ;
}
}
}
}
return result;
}
///
/// Macht aus den lustigen negativen Zahlen der AS400 wieder
/// Vernünftige. Wenn mit der Falschen Codepage gearbeitet wird
/// hat man hier ein Problem weil -0 -> ü ist und dann nur als ?
/// geliefert wird.
///
///
///
public static String NegativeCheck(String zahl)
{
String result = zahl;
String last = null;
bool build = false;
//Nachsehen nach letzter "Ziffer"
if(!String.IsNullOrEmpty(zahl))
{
switch (zahl.Substring(zahl.Length - 1))
{
case "ü":
last = "0";
build = true;
break;
case "J":
last = "1";
build = true;
break;
case "K":
last = "2";
build = true;
break;
case "L":
last = "3";
build = true;
break;
case "M":
last = "4";
build = true;
break;
case "N":
last = "5";
build = true;
break;
case "O":
last = "6";
build = true;
break;
case "P":
last = "7";
build = true;
break;
case "Q":
last = "8";
build = true;
break;
case "R":
last = "9";
build = true;
break;
}
}
if (build)
{
result = "-" + zahl.Substring(0, zahl.Length - 1) + last;
}
return result;
}
public static string GetDatePath()
{
return GetDatePath(DateTime.Now);
}
public static string GetDatePath(DateTime datum)
{
String result = datum.Year.ToString("0000");
result = Path.Combine(result, datum.Month.ToString("00"));
result = Path.Combine(result, datum.Day.ToString("00"));
return result;
}
public static String RechnerName()
{
return Environment.MachineName;
}
public static string ExcelIndexZuSpalte(int index)
{
String prefix = "";
String result = "";
int temp = index + 65;
int counter = 0;
while (temp - 25 > 65)
{
temp = temp - 25;
counter++;
}
if (counter > 0)
{
prefix = Convert.ToChar(64 + counter).ToString();
result = prefix + result;
}
else
{
result = Convert.ToChar(temp).ToString();
}
return result;
}
public static String ToShortDateFormat(DateTime date)
{
return date.ToString("dd.MM.yyyy");
}
}
}