- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
public class TDebug
{
public static void Assert(bool condition)
{
System.Diagnostics.Debug.Assert(condition);
#if DEBUG
if(!condition)
throw new Exception();
#endif
}
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+128
public class TDebug
{
public static void Assert(bool condition)
{
System.Diagnostics.Debug.Assert(condition);
#if DEBUG
if(!condition)
throw new Exception();
#endif
}
}
+127
class TStopThreadWaiter
{
public static void Wait(Thread threadWaitededForStop)
{
var threadName = threadWaitededForStop.GetType().Name;
if (!threadWaitededForStop.Join(1000))
{
TErrorShower.ShowOnceIfAgree("Неудаёться остановить " + threadName + " поток. Будут предприняты попытки внештатной остановки.");
if (!threadWaitededForStop.Join(200))
threadWaitededForStop.Interrupt();
if (!threadWaitededForStop.Join(200))
{
TErrorShower.ShowOnceIfAgree(threadName + " поток не удалость остановить принудительно через Interrupt. Предпринимаю попытку принудительной остановки через Abort.");
threadWaitededForStop.Abort();
if (!threadWaitededForStop.Join(200))
{
TErrorShower.ShowOnceIfAgree(threadName + " поток не удалость остановить принудительно через Abort. Завершаем приложение.");
Application.Exit();
}
};
};
}
}
+136
while (f != null && !string.IsNullOrEmpty(f.FileName) && f.ContentLength != 0)
{
if (f != null && !string.IsNullOrEmpty(f.FileName) && f.ContentLength != 0)
{
// ...
}
}
Проверка на всякий случай
+128
//Hint: We have added one more overload to the method Load/LoadBinary/LoadSoap to achieve your requirement. Please refer the below code snippet.
Exception ex = null;
diagram1.LoadBinary(@"..\\..\\Basic Shapes.edp",out ex);
if (ex != null)
{
//Do your customization here
}
индусский обработчик исключений.
поддержка исключений в их компонент была добавлена по нашей просьбе.
+121
public static T FirstOrDefault<T>(IEnumerable<T> it)
{
foreach (T v in it)
return v;
return default(T);
}
Самодельный FirstOrDefault.
Боюсь даже представить, как у автора будет выглядеть Single
+118
public static void Clear(string[] array)
{
int n = default(int);
Array.ForEach(array, element => array[n++] = String.Empty);
}
Смешались в кучу кони, люди...
+121
public SqlTransaction GetSqlTransaction(string pMd5)
{
if (_connection.State == ConnectionState.Closed)
{
try
{
_connection.Open();
}
catch (SqlException ex)
{
throw new ApplicationException("Unable to connect to database (" + _connection.DataSource + "/" + _connection.Database + "). Please contact your local IT administrator.", ex);
}
}
else
{
try
{
throw new ApplicationException("COUCOU");
}
catch (ApplicationException ex)
{
System.Diagnostics.Trace.WriteLine(ex.StackTrace);
}
sqlTransaction = _connection.BeginTransaction();
}
return sqlTransaction;
}
Код из очередного проекта. А надежда то на коннект все-равно остается! :)
+145
if (!'8'=='=')
{
//код
}
+146
//Мега-изобретательный, сцуко, флаг!
public static bool DONT_UPDATE_INPUTMANAGER = FACEPALM;
...
//Флаг выпилил, быстра блджад!!1
if (DONT_UPDATE_INPUTMANAGER) DONT_UPDATE_INPUTMANAGER = false;
Достаточно недавний мой высер, сделанный на обезумевшую от непоняток голову. Трабла была в том, что при перехода из одного в меню в другое второе меню так же воспринимало эту кнопку и шагало дальше, хотя цикл вроде прошёл и InputManager уже сбросился. Пришлось сделать вот таким вот флагом (правда до сих пор не могу понять КАК я умудрился такой if написать...).
P.S: Похожая фигня и у MS, см. CurveEditor (create.msdn.com -> education catalog -> tools -> CurveEditor -> переменная disableUIEvents (причём int!!!)).
+116
var sEmailRecipient = string.Empty;
string m_sPhysicalPath = "";
if (SaveType == "both" || SaveType == "email")
{
List<User> recipients = null;
if (RecipentSelectMode == "auto")
{
if (!string.IsNullOrEmpty(AutoRecipient))
recipients = Notification.ConvertToUsers(AutoRecipient, MethodologyId, CurrentObjectId, CurrentUserId, CurrentEntityName);
}
if(RecipentSelectMode == "manual"){
if (Recipient != null)
sEmailRecipient = EvaluateExpression(CurrentUserId, MethodologyId, MainEntityName, MainObjectId, Recipient);
}
m_sPhysicalPath = Document.AbsoluteApplicationPath + "/" + p_sReportPath.Substring(p_sReportPath.LastIndexOf("storage"));
if (RecipentSelectMode == "auto")
{
foreach (User user in recipients)
{
if (Regex.IsMatch(user.Email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.None))
{
SendReportByEmail(m_sPhysicalPath, user);
}
}
}
if (RecipentSelectMode == "manual")
{
if (Regex.IsMatch(Recipient, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.None))
{
SendReportByEmail(m_sPhysicalPath, new User { Email = sEmailRecipient });
}
else
{
return CreateResult(GetClientData(), "Email message sending failed - incorrect email address - " + Recipient, (int)ReportRenderingFailType.Success);
}
}
}
if (SaveType == "email")
{
FileInfo file = new FileInfo(m_sPhysicalPath);
if (file.Exists)
file.Delete();
}
Отправляет отчет по email