- 1
- 2
- 3
- 4
- 5
mainDays = 0;
for (var d = emplDoc.EventDate.AddMonths(1).AddDays(-1).Date; d <= emplDoc.DateEndWork.Date; d = d.AddMonths(1)) {
mainDays += 2;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+116
mainDays = 0;
for (var d = emplDoc.EventDate.AddMonths(1).AddDays(-1).Date; d <= emplDoc.DateEndWork.Date; d = d.AddMonths(1)) {
mainDays += 2;
}
+125
/// <summary>
/// Return a DateTime version of the given Jabber date. Example date: 20020504T20:39:42
/// </summary>
/// <param name="dt">The pseudo-ISO-8601 formatted date (no milliseconds)</param>
/// <returns>A (usually UTC) DateTime</returns>
public static DateTime JabberDate(string dt)
{
if ((dt == null) || (dt == ""))
return DateTime.MinValue;
try
{
return new DateTime(int.Parse(dt.Substring(0, 4)),
int.Parse(dt.Substring(4, 2)),
int.Parse(dt.Substring(6, 2)),
int.Parse(dt.Substring(9,2)),
int.Parse(dt.Substring(12,2)),
int.Parse(dt.Substring(15,2)));
}
catch
{
return DateTime.MinValue;
}
}
/// <summary>
/// Get a jabber-formated date for the DateTime. Example date: 20020504T20:39:42
/// </summary>
/// <param name="dt">The (usually UTC) DateTime to format</param>
/// <returns>The pseudo-ISO-8601 formatted date (no milliseconds)</returns>
public static string JabberDate(DateTime dt)
{
return string.Format("{0:yyyy}{0:MM}{0:dd}T{0:HH}:{0:mm}:{0:ss}", dt);
}
Перевод DateTime в строку вида "20020504T20:39:42" и обратно. Из исходников библиотеки Jabber-net.
TryParseExact и ToString с форматом "yyyyMMddTHH:mm:ss" - это пусть лентяи используют.
+119
public static Bitmap DrawBarsChart(ChartType t, Size s)
{
double[] values = DataValues;
string[] names = DataNames;
Bitmap bmp = new Bitmap(s.Width, s.Height);
if (t != ChartType.bars || names.Length != values.Length || names.Length < 2)
return bmp;
else
{
Graphics g = Graphics.FromImage(bmp as Image);
g.Clear(Color.White);
g.DrawLines(new Pen(Brushes.Black), new Point[] { new Point(20, 20), new Point(20, s.Height - 20), new Point(s.Width - 200, s.Height - 20) });
int Columnwidth = (s.Width - 240) / values.Length;
if (Columnwidth > 150) Columnwidth = 150;
double maxvalue = values.Max();
int counter = 1;
int rangefirst;
int rangesecond;
while (true)
{
if (maxvalue / Math.Pow(10, counter) < 10)
{
rangefirst = (int)Math.Floor(maxvalue / Math.Pow(10, counter));
rangesecond = (int)(maxvalue - rangefirst * Math.Pow(10, counter));
break;
}
else
{
counter++;
}
}
int rangepix = (s.Height - 60) / (rangefirst + 1);
for (int i = 0; i < rangefirst + 1; i++)
{
g.DrawString((i * Math.Pow(10, counter)).ToString(), new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular),
Brushes.Black, new PointF(0, s.Height - 30 - rangepix * i));
g.DrawLine(new Pen(Brushes.Black), new Point(17, s.Height - 20 - rangepix * i), new Point(20, s.Height - 20 - rangepix * i));
}
Colors colors = new Colors(); //класс-контейнер цветов (99 штук)
int startcolor = new Random(DateTime.Now.Millisecond).Next(99);
int j = startcolor;
int startx = 21;
int ColumnNumber = 1;
foreach (var value in values)
{
int curfirstrange = (int)Math.Floor(value / Math.Pow(10, counter));
int cursecondrange = (int)(value - curfirstrange * Math.Pow(10, counter));
int rangesmallpix = (int)(cursecondrange * rangepix / Math.Pow(10, counter));
g.FillRectangle(new SolidBrush(colors.GetNextColor(j)), startx,
s.Height - 20 - curfirstrange * rangepix - rangesmallpix, Columnwidth, curfirstrange * rangepix + rangesmallpix);
g.DrawString(value.ToString(), new Font(FontFamily.GenericSerif, 10, FontStyle.Regular), new SolidBrush(Color.Black), new PointF(startx + Columnwidth / 2 - 10,
s.Height - 20 - curfirstrange * rangepix - rangesmallpix - 20));
g.DrawString(ColumnNumber.ToString(), new Font(FontFamily.GenericSerif, 10, FontStyle.Regular), new SolidBrush(Color.Black), new PointF(startx + Columnwidth / 2 - 10,
s.Height - 10));
ColumnNumber++;
j++; if (j > 99) j = 0;
startx += Columnwidth;
}
j = startcolor;
int TopMargin = 20;
foreach (string str in names)
{
string tmp = str;
if (str.Length > 15)
tmp = str.Substring(0, 15);
g.FillRectangle(new SolidBrush(colors.GetNextColor(j)), s.Width - 200, TopMargin, 10, 10); //pucyeM LIBeTHbIe kBagpaTuku
g.DrawString(tmp, new Font(FontFamily.GenericSerif, 12, FontStyle.Italic), Brushes.Black, new PointF(s.Width - 180, TopMargin - 6)); //pucyeM Hagnucu
TopMargin += 20;
j++; if (j > 99) j = 0;
}
return bmp;
}
}
+127
private void bbbut_Click(object sender, EventArgs e)
{
if (this.plugDescr.SelectedText.Length > 0)
{
ToolStripButton button = (ToolStripButton) sender;
if (button.Name == "bbB")
{
this.plugDescr.SelectedText = BB_HTMLwork.WriteBBToString(this.plugDescr.SelectedText, "", "b");
}
if (button.Name == "bbI")
{
this.plugDescr.SelectedText = BB_HTMLwork.WriteBBToString(this.plugDescr.SelectedText, "", "i");
}
if (button.Name == "bbU")
{
this.plugDescr.SelectedText = BB_HTMLwork.WriteBBToString(this.plugDescr.SelectedText, "", "u");
}
if (button.Name == "bbS")
{
this.plugDescr.SelectedText = BB_HTMLwork.WriteBBToString(this.plugDescr.SelectedText, "", "s");
}
if (button.Name == "bbURL")
{
this.plugDescr.SelectedText = BB_HTMLwork.WriteBBToString(this.plugDescr.SelectedText, this.bbAddInfoContent.Text, "url");
}
}
}
Обработчик кнопок ббкода в утилите для генерации ридми. Весь ее код выполнем в таком духе.
Утилита: http://fullrest.ru/forum/topic/34114-generator-readme/
Сорцы: http://depositfiles.com/files/kvi4gsajy
+124
litFreeMinets.Text = FreeMinutes.Count;
+122
switch (item.Value.ModuleConfiguration.SystemModule) // у свойства SystemModule тип bool, а не bool?
{
case true:
{
CreateModuleDomain<ISystemModuleProxy>(moduleContainer);
(moduleContainer.ModuleProxy as ISystemModuleProxy).Init(moduleContainer.ModuleConfiguration, this as ISystemCoreProvider);
break;
}
case false:
{
CreateModuleDomain<IBusinessModuleProxy>(moduleContainer);
(moduleContainer.ModuleProxy as IBusinessModuleProxy).Init(moduleContainer.ModuleConfiguration, this as ICoreProvider);
break;
}
default:
break;
}
Фрагмент кода официального Senior Developer. Пример абсолютно надежного кода, который умеет обрабатывать даже будущие состояния булевого типа (default: break;) Будет надежен даже, если Microsoft неожиданно расширит тип состояниями, например MayBeTrue, OfCourseFalse, DontUnderstand и т.п. :)
+124
if (command == "help") ShowHelp();
else if (command == "") Error(1);
else
{
string[] pcmd = command.Split(' ');
string[] args = { "0,0", "0,0" };
string argv = "Black";
if (pcmd[0] != "setColor" &&
pcmd[0] != "save" &&
pcmd[0] != "fill" &&
pcmd[0] != "saveCMD" &&
pcmd[0] != "close" &&
pcmd[0] != "if" &&
pcmd[0] != "from" &&
pcmd[0] != "setVar" &&
pcmd[0] != "getVar" &&
pcmd[0] != "setRGB" &&
pcmd[0] != "fillFRGB" &&
pcmd[0] != "fillRGB" &&
pcmd[0] != "setPenSize" &&
pcmd[0] != "fillF" &&
pcmd[1] != "#?") args = pcmd[1].Split('|');
else if (pcmd[0] == "setVar") argv = pcmd[1] + " " + pcmd[3];
else if (pcmd[1] == "#?")
{
Help4command(pcmd[0]);
return;
}
else argv = pcmd[1];
switch (pcmd[0])
{
case "save":
try { bmp.Save(argv + "\\" + Name + ".png",ImageFormat.Png); }
catch { Error(2); }
break;
case "line":
{
string[] xy0 = args[0].Split(',');
string[] xy1 = args[1].Split(',');
int x0 = 0, y0 = 0, x1 = 0, y1 = 0;
if (xy0[0] == "w" || xy0[0] == "W") x0 = W;
if (xy0[1] == "h" || xy0[1] == "H") y0 = H;
if (xy1[0] == "w" || xy1[0] == "W") x1 = W;
if (xy1[1] == "h" || xy1[1] == "H") y1 = H;
if (VL.isExistVar(xy0[0])) x0 = int.Parse(VL.Get(xy0[0]));
if (VL.isExistVar(xy0[1])) y0 = int.Parse(VL.Get(xy0[1]));
if (VL.isExistVar(xy1[0])) x1 = int.Parse(VL.Get(xy1[0]));
if (VL.isExistVar(xy1[1])) y1 = int.Parse(VL.Get(xy1[1]));
try
{
x0 = int.Parse(xy0[0]);
y0 = int.Parse(xy0[1]);
x1 = int.Parse(xy1[0]);
y1 = int.Parse(xy1[1]);
}
finally { }
graph.DrawLine(new Pen(usesCol, penSize), new Point(x0, y0), new Point(x1, y1));
}
break;
case "rect":
{
if (fiilF == false)
{
string[] xy0 = args[0].Split(',');
string[] xy1 = args[1].Split(',');
int x0 = 0, y0 = 0, x1 = 0, y1 = 0;
if (xy0[0] == "w" || xy0[0] == "W") x0 = W;
if (xy0[1] == "h" || xy0[1] == "H") y0 = H;
if (xy1[0] == "w" || xy1[0] == "W") x1 = W;
if (xy1[1] == "h" || xy1[1] == "H") y1 = H;
if (VL.isExistVar(xy0[0])) x0 = int.Parse(VL.Get(xy0[0]));
if (VL.isExistVar(xy0[1])) y0 = int.Parse(VL.Get(xy0[1]));
if (VL.isExistVar(xy1[0])) x1 = int.Parse(VL.Get(xy1[0]));
if (VL.isExistVar(xy1[1])) y1 = int.Parse(VL.Get(xy1[1]));
//еще +100500 строк говнокода
Только что копался в старых проектах и наткнулся на это. Это была попытка сделать что-то вреде ЯП для рисования, своево рода черепашья графика, но со своими свистелками и сами знаете чем.
+133
public bool SelectUserGroup(string UserName,string GroupName)
{
try
{
return true;
}
catch
{
return false;
}
}
public KUser GetUserByKey(Guid Key)
{
try
{
return new KUser();
}
catch
{
return new KUser();
}
}
Особая защита от исключительных ситуаций. Взято из реального проекта.
+122
private bool validDir(DirectoryInfo dir)
{
return dir.Attributes == FileAttributes.Directory &&
dir.Attributes != FileAttributes.Hidden &&
dir.Attributes != FileAttributes.NotContentIndexed &&
dir.Name != "Windows";
}
+112
foreach (int i in new int[] {1, 2, 3, 4, 5})
{
//Какие-то действия
}
Правильный for в C#
http://2lx.ru/2010/03/pravilnyj-for-v-c/