среда, 24 сентября 2008 г.

Unknown problems with Dataset in .NET

DataSet object generated by Wizard started to show Exception while opening it in Designer:
key cannot be used in specified...


Also it is impossible to create new Dataset with TableAdapters..

The only solution found:

remove folders Visual Studio in these folders:
1. c:\Documents and Settings\%CurrentUser%\Application Data\Microsoft\
2. c:\Documents and Settings\%CurrentUser%\Local Settings\Application Data\Microsoft\

суббота, 20 сентября 2008 г.

Что из себя представляет корпоративная социальная сеть?

// http://www.intranetno.ru/faq/social-structure/

Корпоративное социальное ПО может иметь различные наборы функций, включая инструменты для коммуникаций, совместной работы и управления контентом. Однако, практически во всех системах есть 2 основных элемента: профайл и домашняя страница.

Профайл - это публичная страничка о сотруднике, на которой обычно размещена его фотография, информация о его должности, функциональных обязанностях, контактная информация, личные данные (интересы), опубликованный им контент (блог, фото, видео), а также его "друзья" - коллеги, с которыми он работает и/или дружит. Профайлы позволяют узнавать больше о людях, которые работают в компании и находить друзей с общими интересами.



Персонализированная домашняя страничка - это персональная страничка, которая доступна только хозяину и которую он настраивает под себя. Подразумевается, что это стартовая страничка, с которой сотрудник начинает свой рабочий день. Поэтому на нее он обычно выводит обновляемую информацию, например, актуальные задачи, запланированные на сегодня мероприятия, новости компании, RSS-обновления по проектам. Эта страничка, как правило, состоит из блоков - виджетов, которые можно как угодно комбинировать и настраивать.



Кроме этих основных элементов, корпоративные социальные сети обычно включают в себя:
- форумы
- блоги
- вики
- социальные закладки
- хостинги файлов, фото, аудио, видео
- рейтинги, голосования, опросы
- внутреннюю почту
- поиск людей и контента

Что собой представляют Корпоративные порталы?

// http://www.intranetno.ru/faq/portals/

Корпоративные порталы настолько многофункциональны и разнообразны, что под термином "корпоративный портал" могут понимать совершенно разные вещи. От сайта на котором выкладываются новости компании и файлы до платформы, интегрирующей корпоративные данные и приложения.

Итак, в самом навороченном варианте:

Корпоративный портал (EIP = enterprise information portal) - это вэб-интерфейс для каждого сотрудника компании ко всему хозяйству, которое он использует по работе.


Как правило, корпоративные порталы внедряются в сравнительно крупных компаниях, в которых используется несколько бизнес-приложений и большое количество корпоративного контента, который хранится в разных местах.

Чтобы мозг сотрудника не взорвался в такой обстановке, для него создается персонализованный удобный сайт, с помощью которого он может взаимодействовать со всеми корпоративными приложениями, данными и другими сотрудниками.

Например, человек приходит на работу, открывает такой сайт. Один раз вводит логин и пароль. И сразу видит свою почту, сегодняшние задачи, отчет по продажам из CRM, неоплаченные счета из ERP, корпоративные новости и у кого из коллег сегодня день рожденья.

Если раньше порталы фокусировались на контенте, то сейчас преобладает тенденция ориентации на людей. Порталы становятся похожими на социальные сети - с профайлами сотрудников, тэгами, RSS-подписками, закладками, блогами, форумами и другими социальными инструментами.

Порталы часто используются и для взаимодействия с внешними контрагентами - партнерами и клиентами, которые с помощью портала могут не только почитать новости компании, но и, например, сделать заказ или поучаствовать в обсуждении проекта. Портал может включать в себя внешний сайт компании или интегрироваться с ним.

Портал, как правило, устанавливается на собственный вэб-сервер компании, но появляются уже и SaaS решения. Основными технологиями, которые позволяют порталам делать свое дело являются XML и Портлеты.

Какие функции выполняют корпоративные порталы?

// http://www.intranetno.ru/faq/portal-functions/

Вот основные функции корпоративных порталов:

1. Безопасный, персонализированный доступ к данным
(в т.ч. с рабочего места, удаленно, и с мобильных устройств)

2. Поиск, систематизация и разметка корпоративных данных из разных источников (внутренних и внешних)

3. Хранение данных
(в БД портала могут храниться документы, данные из заполненных форм, файлы ...)

4. Управление RSS-потоками
(Чтение ленты новостей или оповещений о действиях сотрудников)

5. Управление документами и файлами
(например контроль версий документов, контроль доступа к файлам)

6. Управление бизнес процессами
(например, портал подсказывает сотруднику порядок действий для утверждения документов)

7. Публикация контента самими сотрудниками

8. Создание сайтов
(например сайта подразделения или сайта какого-то проекта)

9. Управление знаниями = knowledge management
(порталы часто содержат базу взаимосвязанных страничек, создаваемых самими пользователями, на которых можно найти решение для своей задачи, не отвлекая при этом коллег. Для это часто используется технология Вики)

10. Совместная работа
(портал может как предоставлять интерфейс к корпоративному органайзеру, так и содержать свои инструменты для совместной работы)

11. Корпоративные коммуникации
(мессенджер, форумы, блоги, комментарии)

12. Создание корпоративных сообществ
(т.е. построение дружеских связей между сотрудниками)

13. Интеграция бизнес-приложений
(в паре с серверами приложений порталы служат для создания единой интеграционной платформы предприятия)

14. Единая точка аутентификации пользователя
(Вместо того, чтобы логиниться в каждое приложение отдельно, пользователь вводит логин и пароль только для входа в портал)

Что такое Социальное ПО и зачем оно нужно?

// http://www.intranetno.ru/faq/social/

Идея Социального ПО (которое иногда называют Enterprise 2.0) - это использование технологий обычных социальных сетей для бизнеса.

Социальное ПО может быть как надстройкой для корпоративной системы, так и самостоятельной системой, включающей функции для управления контентом и совместной работы.

Какие функции выполняют корпоративные социальные сети?

1. Знакомят сотрудников друг с другом.
Особенно в больших компаниях сотрудники часто не знают кого как зовут, кто чем занимается и к кому обратиться по определенному вопросу. В корпоративной социальной сети у каждого сотрудника есть профайл с его именем, должностью, функциональными обязанностями. По этим профайлам можно искать и находить нужного человека.

2. Разрушают иерархические границы
Обычно высокопоставленные руководители не светят свой email и ICQ, и их телефон постоянно занят. Поэтому связь между отдаленными ступеньками иерархической лестницы практически отсутствует. Из-за этого верхи и низы живут, как-бы, в разных мирах. Социальная сеть дает возможность легко обратиться напрямую к любому вышестоящему сотруднику. А для начальства - это удобный способ получить обратную связь и взглянуть на мир более реально.

3. Создают сообщество (команду)
Чем больше компания, тем меньше сотрудник к ней привязан. Он не знает, какие цели у компании и кто с ним рядом работает. Социальные сети поощряют сотрудников публиковать информацию о себе, о своих интересах для того, чтобы люди со схожими интересами внутри компании сходились и устанавливали связи. Неформальные связи привязывают сотрудников друг к другу (а значит и к компании) и дают причину "ради чего я здесь работаю?", что способствует созданию единой команды с общей целью.

4. Предоставляют социальные инструменты для совместной работы
Что это за инструменты?

- Инструменты для публикации контента
(блоги, файлохранилища, wiki, галлереи, видеосервисы)
Социальное ПО позволяет легко публиковать текст, документы, файлы, мультимедиа, которые используются для совместной работы. В традиционных системах возможность публикации контента обычными пользователями очень ограничена. Следует заметить, что большое внимание в социальных системах уделяется Авторству. Т.е. очень важным аттрибутом любого контента является его автор.

- Инструменты для обсуждения
(форумы, блоги, комментарии, отзывы)
Практически любой элемент контента в социальном ПО может быть откомментирован. Это позволяет собирать полезнейшую информацию по всей компании. Например, традиционная CRM система в основном сфокусирована на том, чтобы сотрудник саппорта не имел лишнего доступа к карточке клиента, за которую отвечает продажник. А социальная система, наоборот, поощряет сотрудников саппорта дополнять (комментировать) информацию по клиенту, что может быть очень полезно для продаж.

- Инструменты для организации контента
(тэги, закладки, рейтинги)
Социальное ПО дает возможность каждому сотруднику присваивать тэги, рейтинговать любые элементы контента. В результате при поиске или мониторинге определенного вопроса, сотрудники получают более релевантную и важную информацию.

- Инструменты для контроля и мониторинга
(Персональные RSS-потоки)
Подписавшись на персональную RSS ленту по какому-либо сотруднику, в которой появляются оповещения о всех активностях сотрудника, его руководитель или коллега по проекту может контролировать, что происходит.

Articles about Microsoft Office SharePoint

http://www.intranetno.ru/news/4551/

Корпоративные Порталы

// http://www.intranetno.ru/portal/

39
Microsoft Office SharePoint
Microsoft Office SharePointСистема управления корпоративным контентом и совместной работы, которую можно использовать в качестве корпоративного портала. Имеет множество расширений и интегрированных систем. Тесно интегрирована с MS Office и MS Exchange. Может поставляться как вэб сервис [edit]


33
IBM WebSphere Portal
IBM WebSphere PortalРешение для построения корпоративного портала, бизнес-мэшапов и SOA-платформы. Предоставляет избыточную функциональность для совместной работы и управления контентом для организации любого размера. Отлично интегрируется с другими системами IBM [edit]


26
Oracle WebCenter Suite
Oracle WebCenter SuiteПортальная платформа для совместной работы, управления контентом, управления бизнес-процессами, интеграции бизнес данных и приложений. Включает Enterprise 2.0 фичи, такие как вики, блоги, форумы, RSS. [edit]


23
QSOFT: Корпоративный портал
QSOFT: Корпоративный порталРешение для создания корпоративного портала на движке 1С-Битрикс:Управление сайтом. Содержит новости, справочники, базу знаний, календарь, форумы, блоги, подписки, профайлы... Поставляется с набором готовых дизайнов и не требует от пользователя специальных навыков и знаний. [edit]


23
SAP NetWeaver Portal
SAP NetWeaver PortalПортал для интеграции приложений SAP, приложений других производителей, баз данных, источников корпоративного контента (структурированного и нет), внешнего вэб-контента. Основан на открытых стандартах и вэб-сервисах, поддерживает технологии J2EE и .NET [edit]


22
RedDot CMS
RedDot CMSПортальное решение для корпоративных коммуникаций, интеграции ИТ инфраструктуры и управления корпоративным контентом. Отличается интерактивным интерфейсом [edit]


20
PayDox
PayDoxВэб-система документооборота с функциями для корпоративного портала. Содержит файловый архив, форумы, инструменты для управления документами и совместной работы. Хорошо интегрирована с MS Office. Отечественная разработка [edit]


20
Drupal
DrupalПопулярнейшая open-source CMS система для создания порталов и сообществ. Отличается богатой функциональностью, высокой безопасностью, большой библиотекой расширений, системой совместной публикации, поддержкой Open ID [edit]


19
Salesforce Content
Salesforce ContentSaaS сервис для управления корпоративным контентом интегрированный с Salesforce CRM. Основан на социальных инструментах, таких как тэги, rss-подписки, рекомендации, рейтингование. Предназначен для взаимодействия как внутри компании, так и с партнерами и клиентами. [edit]


19
JBoss Portal
JBoss PortalБезопасный и производительный open-source корпоративный портал. Предоставляет платформу для интеграции контента и приложений. Содержит инструменты для совместной работы и управления бизнес-процессами [edit]

Resources - полезный софт для ИТ компаний

http://www.livebusiness.ru

Виртуальный офис
Управление проектами
CRM и HelpDesk
Редакторы документов
Календари и Органайзеры
Бизнес Email
Wiki и Порталы
Файлохранилища
Вэб конференции
Вэб презентации
Мессенджеры и VoIP
wimax
WiMax интернет

Корпоративные порталы
Wiki системы
Социальное ПО

Wiki на корпоративной службе

Wiki на корпоративной службе

// http://www.pcweek.ru/themes/detail.php?ID=112325


Технология Wiki открывает отличные возможности по использованию контента, совместной работе над ним и его редактированию через Интернет. Организации берут ее на вооружение, чтобы повысить производительность труда, улучшить взаимодействие между сотрудниками и сократить объем электронной почты.

Вот только торопиться с развертыванием Wiki в корпоративной сети не стоит. Сначала необходимо предпринять ряд мер, чтобы упростить процесс реализации и свести к минимуму риск ошибок. Для успешного завершения такого проекта следует выполнить три действия.
Шаг 1. Убедитесь, что ИТ-инфраструктура может справиться с Wiki

Когда принципиальное решение об использовании Wiki принято, в первую очередь следует удостовериться, что развернутая на предприятии система пригодна для этой технологии. Если предполагается применение Web-платформы, данный шаг обязательно должен предусматривать проверку сетевой безопасности и политики блокирования Web-сайтов и программ, включая AOL, Instant Messenger, Skype и социальные сети. Некоторые организации запрещают своим сотрудникам пользоваться такими приложениями, и эти ограничения могут помешать применению в корпоративной сети систем наподобие Wiki. Необходимо также убедиться, что на сервере имеется достаточно места для хранения информации. Если же его не хватает, можно воспользоваться средствами хостинга Wiki на других серверах.

Кроме того, ИТ-отделу следует тщательно изучить два важнейших вопроса -- защиты данных и мобильности. С учетом множества попыток взлома данных, которые были зарегистрированы за прошедший год, крайне важно следить, чтобы любое вновь устанавливаемое приложение -- и Wiki здесь не исключение -- было не менее защищенным, чем все другие ресурсы организации. В каждом подразделении наверняка есть собственная конфиденциальная информация, которую нужно закрывать паролем от несанкционированного доступа сотрудников.

При выборе технологии Wiki и ее развертывании не стоит забывать и о мобильности пользователей. Для получения информации сегодня сплошь и рядом применяются сотовые телефоны или карманные компьютеры, так что сотрудникам наверняка захочется пользоваться такими устройствами и для извлечения сведений из корпоративной Wiki.
Шаг 2. Пересмотрите внутренние корпоративные правила с прицелом на использование Wiki

Реагируя на стремительное распространение блогов в Интернете, многие организации уже выработали правила ведения таких электронных дневников. То же самое следует предпринять и в отношении Wiki. Выбрав технологию Wiki, которая лучше всего соответствует потребностям организации, первым делом следует четко определить политику работы с ней и довести до сведения всех пользователей, что информация здесь носит сугубо конфиденциальный характер. Поэтому хотя Wiki и упрощает общение, правила остаются неизменными. Ведь новая система является корпоративной, и содержащийся в ней контент ни в коем случае не должен выноситься за пределы рабочей среды. И, наконец, политика использования Wiki не должна ограничиваться тем, какие области сайта доступны конкретному сотруднику или подразделению. В дополнение к этому необходимо определить, какие разделы Wiki открыты внешним пользователям, а какие видны только внутренним.
Шаг 3. Стимулируйте участие сотрудников в системе Wiki

Как только технология Wiki будет выбрана и внутренняя корпоративная политика выработана, настанет черед последнего шага -- убедить сотрудников пользоваться новой системой для общения. Здесь очень важно учесть, что разные возрастные группы подходят к этому вопросу неодинаково. Поколение Y имеет довольно солидные навыки обращения с современными технологиями и склонно быстро воспринимать все происходящие в них изменения. А вот поколения Х и дети бэби-бума вряд ли сразу ухватятся за Wiki -- здесь не обойтись без дополнительного стимулирования и обучения. Так что ИТ-отделу придется разрабатывать план приобщения к новинке колеблющихся сотрудников.

Во-первых, классы изучения Wiki дадут пользователям шанс познакомиться с новой системой, что называется, из первых рук и задать вопросы. Во-вторых, ИТ-сотрудники вполне могут обучить премудростям Wiki начальников различного ранга, чтобы затем они смогли руководить внедрением системы в своих подразделениях и следить за соблюдением правил работы в ней. В результате у ИТ-отдела появятся “свои люди” в подразделениях, помогающие разбираться с Wiki на месте и тем самым снизить нагрузку на ИТ-специалистов.

Хотя первые шаги на этом пути и могут занять массу времени, они вполне себя окупят, так как помогут сотрудникам органично вписать технологию Wiki в свой рабочий процесс. Да и в ИТ-отдел будет поступать меньше вопросов по новой системе. А если всё сделать правильно, внедрение корпоративной Wiki-системы позволит сэкономить время, снизить потоки корпоративной электронной почты и воспрепятствовать снижению производительности труда, если такоовая угроза у вас возникнет.

Tools - управление проектами

По оценкам компании Gartner, рынок ПО управления проектами и систем Enterprise 2.0 для маленьких команд и компаний сейчас бурно развивается, и лидера на нем нет. Есть много игроков, которые предлагают отличные решения:

1. Basecamp
лидер в task management, управлении только задачами, только онлайн

2. OpenText
и другие корпоративные вики-системы для корпоративного знания

3. Jira+Confluence
для программистов, нет онлайн решения

4. Zoho Projects - как SaaS/PaaS платформа для небольших команд

5. Google Sites / Google Apps как решение для некоммерческих проектов

6. MS Sharepoint - может стать лидером ПО для сотрудничества и управления проектами, но пока что цена внедрения очень высока: нужно серьезное дотачивание продукта в каждом случае.

7. Новые проекты и продукты: Central Desktop, LongJump, 5PMWeb и другие - судить о которых лучше по их развитию, нежели по функциональным возможностям.

-- comindwork
http://www.comindwork.ru

References
http://webplanet.ru/knowhow/soft/postnikov/2008/08/27/comindwork.html

Microsoft Live Labs

// http://internetno.net/2007/10/25/ms-live-labs-review/

для придумывания всего нового у Microsoft есть т.н. лаборатория, которая так и называется Windows Live Labs.

Logo_Listas_Thumbnail
Listas — это сервис для создания, управления и шаринга списков, заметок и избранных ссылок. Подразумевается, что при помощи сервиса удобно формировать списки покупок, собираться на различные мероприятия и т.д. К созданию списков можно подключать большое число участников, а специальная система оповещения не даст вам пропустить свежие изменения в созданных вами списках. Для более удобной работы со списками и закладками установите тулбар (только для IE) — с его помощью особенно удобно добавлять в ваши списки данные с открытых страниц.

Logo_Deepfish_ThumbnailDeepdish — это мобильный браузер от Microsoft, который работает под Windows Mobile. Основной фишкой браузера создатели считают новый для браузеров MS принцип рендеринга страниц. Сначала загружается уменьшенная копия сайта, привью, а потом в фоновом режиме увеличивается детализация элементов. Максимальная детализация выводится при выборе пользователем какой-либо части страницы. Именно такая технология рендеринга уже реализована в мультиплатформенном браузере Opera Mini, однако, если точно такое решение будет установлена на каждом новом Windoqws Mobile устройстве, то наступит золотой век мобильного браузинга.

2007-10-24_220439

Photosynth — технология автоматического анализа множества фотографий для воссоздания искусственной 3D-модели мира:

Суть технологии заключается в том, что берутся все возможные фотографии мира, анализируются, и затем сопоставляются похожие и на основе всех этих данных строится полная и трёхмерная модель мира. По-крайней мере, той его части, которая была когда-либо сфотографирована. То есть, вы можете посмотреть на Лувр со всех сторон. Увеличить любой его участок - потому что он сфотографирован с любым возможным зумом тысячи раз, а сопоставление уже сделано. И т.п. И все это - автоматически. Никаких тегов и человеческого вмешательства.


Seadragon — проект компании Microsoft, который призван изменить саму концепцию представления многочисленных пользовательских данных на одном экране вне зависимости от того, огромная ли это плазма на всю стену или 3’’ экран мобильного телефона.

Нам же, простым пользователям остается только набраться терпения и немного подождать пока эти головокружительные разработки станут частью нашей жизни, проникнут в игровые приставки, телевизоры и мобильные телефоны.

Truncate Log in SQL Server

to truncate log using command 'backup log .. with truncate_only' is not enough.

to truncate log you need:
1. execute command
backup log YOUR_DB_NAME with TRUNCATE_ONLY

this command removes the inactive part of the log without making a backup copy of it and truncates the log. This option frees space.
NO_LOG and TRUNCATE_ONLY are synonyms.


2. execute command
dbcc shrinkfile (YOUR_DB_NAME, 2, NOTRUNCATE)


where '2' defines that we need log file to have size 2Mb

NOTRUNCATE - Causes the freed file space to be retained in the files.
When NOTRUNCATE is specified along with target_size, the space freed is not released to the operating system. The only effect of the DBCC SHRINKFILE is to relocate used pages from above the target_size line to the front of the file. When NOTRUNCATE is not specified, all freed file space is returned to the operating system.


3. execute command
dbcc shrinkfile (YOUR_DB_NAME, 2, truncateonly)


TRUNCATEONLY - Causes any unused space in the files to be released to the operating system and shrinks the file to the last allocated extent, reducing the file size without moving any data. No attempt is made to relocate rows to unallocated pages. target_size is ignored when TRUNCATEONLY is used.



DBCC commands are perfomed not-immediately and you may not see the changes at once.

if that commands do not help - repeat steps 1,2,3 again.

References:
Books Online SQL Server 2000

пятница, 19 сентября 2008 г.

Shell execute .NET

Shell execute

System.Diagnostics.Process.Start(strpath)


Read more:
Launch and monitor external programs from .NET
Launching an external program.
Start a process and wait until it exits.
Start an invisible process.
Determine when a process exits.
Controlling process input/output.


Launch and monitor external programs from .NET

VB6 let you launch external programs using the Shell command and you could control the launched program's window style with the windowstyle parameter.

lngPID = Shell("c:\...\MyTextFile.txt", vbNormalFocus)

To wait for the external program to terminate you could use the WaitForSingleObject API (view the VB6 sample). In VB.NET you can use the Microsoft.VisualBasic.Compatibility namespace and still call the Shell command but there's a better way.

Launching an external program.

The System.Diagnostics namespace has a Process class you can launch external programs with. You pass in the name of an executable file or a filename with an extension associated with an executable application.

System.Diagnostics.Process.Start("c:\...\MyTextFile.txt")

This code returns a Process object:

Dim myProcess As Process = System.Diagnostics.Process.Start("c:\...\MyTextFile.txt")
MessageBox.Show(myProcess.ProcessName)

An overloaded Process.Start method takes a ProcessStartInfo parameter that let's you set process initialization values such as the WindowStyle.

Dim psInfo As New System.Diagnostics.ProcessStartInfo ("c:\...\MyTextFile.txt")
psInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
Dim myProcess As Process = System.Diagnostics.Process.Start(psInfo)

Or,

Dim myProcess As System.Diagnostics.Process = new System.Diagnostics.Process()
myProcess.StartInfo.FileName = "c:\...\MyTextFile.txt"
myProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
myProcess.Start

You can also do all of this through the IDE by dragging a Process component unto your form from the Components area of the Toolbar.

Start a process and wait until it exits.

To wait for a launched process to end, call the Process.WaitForExit method. Your application will stop executing until the launched process exits. However, this will cause your application to stop responding to system events, such as the Paint event.

'
' Start a new process (Notepad).
'
Dim myProcess As Process = System.Diagnostics.Process.Start("MyTextFile.txt")
'
' Wait until it ends.
'
myProcess.WaitForExit()

MessageBox.Show("Notepad ended: " & myProcess.ExitTime & "." & _
System.Environment.NewLine & "Exit Code: " & myProcess.ExitCode)
'
' Close the process to free resources.
'
myProcess.Close()

Start an invisible process.

You can start a process and get its output without a visible window. This shows how to changes to the System folder, run the DOS Dir "*.exe" command and send the output to the Output.txt file. The Windows XP command shell interpreter recognizes "&&" as a command separator, thus, you can put multiple commands on a single line. The ">>" operator redirects output into a file.

Dim myProcess As Process = New Process()
Dim s As String
Dim outfile As String = Application.StartupPath & "\Output.txt"
'
' Get the System path.
'
Dim sysFolder As String =
System.Environment.GetFolderPath(Environment.SpecialFolder.System)
'
' Createe the command line.
'
myProcess.StartInfo.FileName = "cmd.exe"
myProcess.StartInfo.Arguments = "/C cd " & sysFolder & _
" && dir *.com >> " & Chr(34) & outfile & Chr(34) & " && exit"
'
' Start the process in a hidden window.
'
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
'
' Kill the process if it doesn't finish in one minute.
'
myProcess.WaitForExit(1000)
If Not myProcess.HasExited Then
myProcess.Kill()
End If
'
' Show the results.
'
MessageBox.Show("The 'dir' command window was " & _
"closed at: " & myProcess.ExitTime & "." & System.Environment.NewLine & _
"Exit Code: " & myProcess.ExitCode)

myProcess.Close()

Determine when a process exits.

The Process class can raise an Exited event when a process ends. You must set the Process.EnableRaisingEvents property True and create an event handler.

myProcess.EnableRaisingEvents = True
'
' Add an event handler.
'
AddHandler myProcess.Exited, AddressOf Me.ProcessExited

myProcess.Start()

'
' Event handler.
'
Friend Sub ProcessExited(ByVal sender As Object, _
ByVal e As System.EventArgs)

Dim myProcess As Process = DirectCast(sender, Process)

MessageBox.Show("The process exited, raising " & _
"the Exited event at: " & myProcess.ExitTime & _
"." & System.Environment.NewLine & "Exit Code: " & myProcess.ExitCode)

myProcess.Close()
End Sub

Note, if the launched process hangs your application will too.

Controlling process input/output.

You may need to send input directly to a launched process and send the output directly back to your program. For programs that use StdIn, StdOut, and StdErr, such as console applications, you can override the defaults and provide a StreamWriter to write input and StreamReaders to read the StdOut and StdErr outputs.

.NET uses the Win32 ShellExecute function to launch processes so when you want to reassign I/O streams, you must set the ProcessStartInfo.UseShellExecute property False before starting the process. Also, you must either specify the full path to the file, or the file location must be in the environment path string or in one of the places Windows searches for files.

Dim myProcess As Process = New Process()
Dim s As String myProcess.StartInfo.FileName = "cmd.exe"

myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.CreateNoWindow = True
myProcess.StartInfo.RedirectStandardInput = True
myProcess.StartInfo.RedirectStandardOutput = True
myProcess.StartInfo.RedirectStandardError = True
myProcess.Start()

Dim sIn As StreamWriter = myProcess.StandardInput
Dim sOut As StreamReader = myProcess.StandardOutput
Dim sErr As StreamReader = myProcess.StandardError

sIn.AutoFlush = True
sIn.Write("dir c:\windows\system32\*.com" & System.Environment.NewLine)
sIn.Write("exit" & System.Environment.NewLine)
s = sOut.ReadToEnd()

If Not myProcess.HasExited Then
myProcess.Kill()
End If

MessageBox.Show("The 'dir' command window was " & _
closed at: " & myProcess.ExitTime & "." & _
System.Environment.NewLine & "Exit Code: " & myProcess.ExitCode)

sIn.Close()
sOut.Close()
sErr.Close()
myProcess.Close()
MessageBox.Show(s)

For programs that don't use StdIn, you can use the SendKeys method to input keystrokes.

Dim myProcess As Process = New Process()

myProcess.StartInfo.FileName = "notepad"
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
myProcess.EnableRaisingEvents = True

AddHandler myProcess.Exited, AddressOf Me.SendKeysTestExited
myProcess.Start()
'
' Wait until the program is ready for input.
'
myProcess.WaitForInputIdle(1000)

If myProcess.Responding Then
System.Windows.Forms.SendKeys.SendWait( _
"This text was entered using SendKeys.")
Else
myProcess.Kill()
End If

среда, 17 сентября 2008 г.

Send keyboard messages to the program automatically

use SendKeys.SendWait and SendKeys.Send methods

example:

class SendKeysDemo{
static void Main()
{
// run program - notepad
Process process = Process.Start("notepad.exe");
// wait while the program ends initialization
process.WaitForInputIdle();
// find window of Notepad just run.

IntPtr hWndNotepad = FindWindow("Notepad", null);
// make found window active
SetForegroundWindow(hWndNotepad);
// send string
SendKeys.SendWait("Hello from GotDotNet.ru !!!");
}

// Export Win32 functions
[DllImport("User32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr hWnd);

}

суббота, 13 сентября 2008 г.

References - Blocking - SQL Server optimization

Microsoft KB, TechNet:
-- How to resolve blocking problems that are caused by lock escalation in SQL Server
http://support.microsoft.com/kb/323630/en-us
-- Lock Escalation (Database Engine)
http://msdn.microsoft.com/en-us/library/ms184286.aspx

-- Minimize Blocking in SQL Server
http://technet.microsoft.com/en-us/magazine/cc434694.aspx


Other sites:

-- Troubleshoot SQL Server Locking
http://www.nwsummit.com/tech/mssql.html

Understanding and Resolving SQL Server 7.0 or 2000 Blocking Problems

// from http://support.microsoft.com/kb/224453/

SUMMARY
This article is an update for SQL Server 7.0 of the following article, which applies to SQL Server 6.x, in the Microsoft Knowledge Base:
162361 (http://support.microsoft.com/kb/162361/EN-US/) INF: Understanding and Resolving SQL Server Blocking Problems
Much of the information contained in the above article has already been updated and included in SQL Server 7.0 Books Online in the "Understanding and Avoiding Blocking" topic. Carefully review this information before proceeding with this article; it will not be repeated here. This article focuses on how to monitor SQL Server to capture pertinent system information and how to analyze that information to successfully resolve blocking issues.

This article uses the same standard terminology as defined in the above information. In this discussion, the term "connection" refers to a single logged-on session of the database. Each connection appears as a system process ID (SPID). Each of these SPIDs is often referred to as a process, although it is not a separate process context in the usual sense. Rather, each SPID consists of the server resources and data structures necessary to service the requests of a single connection from a given client. A single client application may have one or more connections. From the perspective of SQL Server, there is no difference between multiple connections from a single client application on a single client computer and multiple connections from multiple client applications or multiple client computers. One connection can block another connection, regardless of whether they emanate from the same application or separate applications on two different client computers.

How to resolve blocking problems that are caused by lock escalation in SQL Server

// from http://support.microsoft.com/kb/323630


SUMMARY
Lock escalation is the process of converting many fine-grained locks (such as row or page locks) into table locks. Microsoft SQL Server dynamically determines when to perform lock escalation. When making this decision, SQL Server takes into account the number of locks that are held on a particular scan, the number of locks that are held by the whole transaction, and the memory that is being used for locks in the system as a whole. Typically, SQL Server's default behavior results in lock escalation occurring only at those points where it would improve performance or when you must reduce excessive system lock memory to a more reasonable level. However, some application or query designs may trigger lock escalation at a time when it is not desirable, and the escalated table lock may block other users. This article discusses how to determine whether lock escalation is causing blocking and how to deal with undesirable lock escalation.


MORE INFORMATION

How to Determine Whether Lock Escalation Is Causing Blocking

Lock escalation does not cause most blocking problems. To determine whether lock escalation is occurring around the time when you experience blocking issues, start a SQL Profiler trace that includes the Lock:Escalation event. If you do not see any Lock:Escalation events, lock escalation is not occurring on your server and the information in this article does not apply to your situation.

If lock escalation is occurring, verify that the escalated table lock is blocking other users.

For more information about how to identify the head blocker and how to identify the lock resource held by the head blocker that is blocking other server process IDs (SPIDs), click the following article number to view the article in the Microsoft Knowledge Base:
224453 (http://support.microsoft.com/kb/224453/) Understanding and resolving SQL Server 7.0 or 2000 blocking problems
If the lock that is blocking other users is anything other than a TAB (table-level) lock with a lock mode of S (shared), or X (exclusive), lock escalation is not the issue. In particular, if the TAB lock is an intent lock (such as a lock mode of IS, IU, or IX), this is not the result of lock escalation. If your blocking problems are not being caused by lock escalation, see the article Q224453 for troubleshooting steps.


How to Prevent Lock Escalation
The simplest and safest way to prevent lock escalation is to keep transactions short and to reduce the lock footprint of expensive queries so that the lock escalation thresholds are not exceeded. There are several ways to obtain this goal, many of which are listed:
• Break up large batch operations into several smaller operations. For example, suppose you ran the following query to remove several hundred thousand old records from an audit table, and then you found that it caused a lock escalation that blocked other users:

DELETE FROM LogMessages WHERE LogDate < '2/1/2002'

By removing these records a few hundred at a time, you can dramatically reduce the number of locks that accumulate per transaction and prevent lock escalation. For example:

SET ROWCOUNT 500
delete_more:
DELETE FROM LogMessages WHERE LogDate < '2/1/2002'
IF @@ROWCOUNT > 0 GOTO delete_more
SET ROWCOUNT 0

• Reduce the query's lock footprint by making the query as efficient as possible. Large scans or large numbers of Bookmark Lookups may increase the chance of lock escalation; additionally, it increases the chance of deadlocks, and generally adversely affects concurrency and performance. After you find the query that causes lock escalation, look for opportunities to create new indexes or to add columns to an existing index to remove index or table scans and to maximize the efficiency of index seeks. Consider pasting the query into a Query Analyzer query window to perform an automatic index analysis on it. To do so, on the Query menu, click Index Tuning Wizard in SQL Server 2000, or click Perform Index Analysis in SQL Server 7.0.

One goal of this optimization is to make index seeks return as few rows as possible to minimize the cost of Bookmark Lookups (maximize the selectivity of the index for the particular query). If SQL Server estimates that a Bookmark Lookup logical operator may return many rows, it may use a PREFETCH to perform the bookmark lookup. If SQL Server does use PREFETCH for a bookmark lookup, it must increase the transaction isolation level of a portion of the query to repeatable read for a portion of the query. This means that what may look similar to a SELECT statement at a read-committed isolation level may acquire many thousands of key locks (on both the clustered index and one nonclustered index), which can cause such a query to exceed the lock escalation thresholds. This is especially important if you find that the escalated lock is a shared table lock, which, however, is not commonly seen at the default read-committed isolation level. If a Bookmark Lookup WITH PREFETCH clause is causing the escalation, consider adding additional columns to the nonclustered index that appears in the Index Seek or the Index Scan logical operator below the Bookmark Lookup logical operator in the query plan. It may be possible to create a covering index (an index that includes all columns in a table that were used in the query), or at least an index that covers the columns that were used for join criteria or in the WHERE clause if including everything in the select column list is impractical.

A Nested Loop join may also use PREFETCH, and this causes the same locking behavior.

For more information, click the following article number to view the article in the Microsoft Knowledge Base:
260652 (http://support.microsoft.com/kb/260652/) Nested loop join that uses a "BOOKMARK LOOKUP ...WITH PREFETCH" may hold locks longer
• Lock escalation cannot occur if a different SPID is currently holding an incompatible table lock. Lock escalation always escalates to a table lock, and never to page locks. Additionally, if a lock escalation attempt fails because another SPID holds an incompatible TAB lock, the query that attempted escalation does not block while waiting for a TAB lock. Instead, it continues to acquire locks at its original, more granular level (row, key, or page), periodically making additional escalation attempts. Therefore, one method to prevent lock escalation on a particular table is to acquire and to hold a lock on a different connection that is not compatible with the escalated lock type. An IX (intent exclusive) lock at the table level does not lock any rows or pages, but it is still not compatible with an escalated S (shared) or X (exclusive) TAB lock. For example, assume that you must run a batch job that modifies a large number of rows in the mytable table and that has caused blocking that occurs because of lock escalation. If this job always completes in less than an hour, you might create a Transact-SQL job that contains the following code, and schedule the new job to start several minutes before the batch job's start time:

BEGIN TRAN
SELECT * FROM mytable (UPDLOCK, HOLDLOCK) WHERE 1=0
WAITFOR DELAY '1:00:00'
COMMIT TRAN

This query acquires and holds an IX lock on mytable for one hour, which prevents lock escalation on the table during that time. This batch does not modify any data or block other queries (unless the other query forces a table lock with the TABLOCK hint or if an administrator has disabled page or row locks by using an sp_indexoption stored procedure).
Additionally, you can disable lock escalation by enabling trace flag 1211. However, this trace flag disables all lock escalation globally in the instance of SQL Server. Lock escalation serves a very useful purpose in SQL Server by maximizing the efficiency of queries that are otherwise slowed down by the overhead of acquiring and releasing several thousands of locks. Lock escalation also helps to minimize the required memory to keep track of locks. The memory that SQL Server can dynamically allocate for lock structures is finite, so if you disable lock escalation and the lock memory grows large enough, attempts to allocate additional locks for any query may fail and the following error occurs:

Error: 1204, Severity: 19, State: 1
The SQL Server cannot obtain a LOCK resource at this time. Rerun your statement when there are fewer active users or ask the system administrator to check the SQL Server lock and memory configuration.
Note When a "1204" error occurs, it stops the processing of the current statement and causes a rollback of the active transaction. The rollback itself may block users or lead to a long database recovery time if you restart the SQL Server service.

Using a lock hint such as ROWLOCK only alters the initial lock plan. Lock hints do not prevent lock escalation.

The other methods of preventing lock escalation that are discussed earlier in this article are better options than enabling the trace flag. Additionally, the other methods generally result in better performance for the query than disabling lock escalation for the whole instance. Microsoft recommends enabling this trace flag only to mitigate severe blocking that is caused by lock escalation while other options, such as those discussed earlier in this article, are being investigated. To enable a trace flag so that it is turned on whenever SQL Server is started, add it as a server startup parameter.

To add a server startup parameter, right-click the server in SQL Enterprise Manager, click Properties, and then on the General tab, click Startup Parameters, and then add the following parameter (exactly as shown):
-T1211
You must cycle the SQL Server service for a new startup parameter to take effect. If you run the following query in Query Analyzer the trace flag takes effect immediately:

DBCC TRACEON (1211, -1)

However, if you do not add the -T1211 startup parameter, the effect of a traceon command is lost when the SQL Server service is cycled. Turning on the trace flag prevents any future lock escalations, but it does not reverse any lock escalations that have already occurred in an active transaction.

пятница, 12 сентября 2008 г.

Hit Counters and Statistics

There are a number of sites that offer free services to help you track visits to your site.

* Google Analytics
* Site Meter
* Bravenet Hit Counter
* FreeStats
* Easy Hit Counters
* StatCounter

четверг, 4 сентября 2008 г.

SQL Server Optimization - References

http://blogs.msdn.com/queryoptteam/

-- Improving Performance with SQL Server 2005 Indexed Views
Published: May 1, 2005
By Author: Eric Hanson and Contributors: Gail Erickson, Lubor Kollar, Jason Ward

SQL Server 2000 Optimization Tips - 2

// from http://www.mssqlcity.com/Tips/tipSQL2000.htm


SQL Server 2000 Optimization Tips

*****

* For the very large databases, use distributed partitioned views to partition tables horizontally across multiple servers.
This is a new SQL Server 2000 feature, which is available when using SQL Server 2000 Enterprise Edition only. Due to distributed partitioned views, SQL Server 2000 now on the first place in the TPC-C tests.


*****

* Use indexed views to increase the speed of your queries.
The result set of the indexed view is persist in the database and indexed for fast access. Because indexed views depend on base tables, you should create indexed views with SCHEMABINDING option to prevent the table or column modification that would invalidate the view. Furthermore, using views instead of heavy-duty queries can reduce network traffic and can be used to facilitate permission management.


*****

* Consider using the WITH SORT_IN_TEMPDB option when you create an index and when tempdb is on a different set of disks than the user database.
Using this option can reduce the time it takes to create an index, but increases the amount of disk space used to create an index.


*****

* You can specify whether the index keys are stored in ascending or descending order.
For example, using the CREATE INDEX statement with the DESC option (descending order) can increase the speed of queries, which return rows in the descending order. By default, the ascending order is used.


*****

* Consider creating index on computed columns.
In SQL Server 2000, you can create indexes on computed columns. To create index on computed column, the computed column must be deterministic, precise, and cannot has text, ntext, or image data type.


*****

* Consider setting the 'text in row' table option.
The text, ntext, and image values are stored on the Text/Image pages, by default. This option specifies that small text, ntext, and image values will be placed on the Data pages with other data values in a data row. This can increase the speed of read and write operations and reduce the amount of space used to store small text, ntext, and image data values. You can set the 'text in row' table option by using the sp_tableoption stored procedure.


*****

* Use table variables instead of temporary tables.
The table variable is a new SQL Server 2000 feature. The table variables require less locking and logging resources than temporary tables, so table variables should be used whenever possible.


*****

* Use cascading referential integrity constraints instead of triggers, whenever possible.
For example, if you need to make cascading deletes or updates, you can specify ON DELETE or ON UPDATE clause in the REFERENCES clause of the CREATE TABLE and ALTER TABLE statements. The cascading referential integrity constraints are much more efficient than triggers and can boost performance.


*****

* If you work with SQL Server 2000 Enterprise Edition use SAN (System Area Network) protocols instead of LAN (Local Area Network) or WAN (Wide Area Network).
SANs are more reliable than LANs or WANs and support high levels of messaging traffic by lowering CPU loads and message latency.


*****

* Use user-defined functions to encapsulate code for reuse.
The user-defined functions (UDFs) contain one or more Transact-SQL statements that can be used to encapsulate code for reuse. Using UDFs can reduce network traffic.


*****

* Set the 'awe enabled' server configuration option to 1 if you work with SQL Server 2000 Enterprise or Developer edition and have more than 4 gigabytes (GB) of physical memory.
Because SQL Server 2000 can support up to a maximum of 64 gigabytes (GB) of physical memory, you can purchase the appropriate server box and get all advantages of it hardware platform.


*****

* Use the DBCC CHECKCONSTRAINTS statement if you need to check the integrity of a specified constraint or all constraints on a specified table.


*****

* Use the DBCC INDEXDEFRAG statement to defragment clustered and secondary indexes of the specified table or view.
DBCC INDEXDEFRAG statement is an online operation. Unlike DBCC DBREINDEX, DBCC INDEXDEFRAG does not hold locks long term and thus will not block running queries or updates. So, try to use the DBCC INDEXDEFRAG command instead of DBCC DBREINDEX, whenever possible.


*****

* You can use INSTEAD OF triggers to perform enhance integrity checks on the data values.
The INSTEAD OF trigger is a new SQL Server 2000 feature. These triggers can be used to enforce business rules when constraints cannot be used.

Note. Because triggers are more resource expensive, use constrains instead of triggers, whenever possible.

SEO: Google links exchange

I read many articles saying about Google would change its algorythms for evaluating Page Rank and links exchange will not work so weel as now.
the main idea that Google will ignore or ban the links to my site if the link is not inapriate .
i just think about simple example:
i have 2 sites which are far from each other about topics.
One site sells aquariums and another site is site of web studio.
and Web studio site has link to Aquarium site as part of its portfolio.
The site about aquariums has inbound link from web studio site but the whole site of web studio says nothing about aquariums.
is it considered as a bad link?

I guess how they will distinct bad and good inbound links ?
or it is another tricks from google, when they say something about improvement and big ideas but it works as usual..

SQL Server 2000 Optimization Tips

Original:

January 20, 2001
SQL Server 2000 Optimization Tips
By Sergey Vartanyan

http://www.databasejournal.com/features/mssql/article.php/1442691


Introduction

There are not so many differences in the internal architecture between SQL Server 7.0 and SQL Server 2000, as between SQL Server 6.5 and SQL Server 7.0. SQL Server 2000 has the same features as SQL Server 7.0: autogrow features, new storage engine, complete row level locking and so on. So, you can use all optimization tips from my previous article for SQL Server 7.0 (see this article): Some tips about database optimization for SQL Server 7.0

But there are some new features in SQL Server 2000, which you can use to increase performance of your databases.

In this article, I want to tell you, how you can increase performance of your databases by setting some options and configuring some parameters.

Distributed partitioned views

Distributed partitioned views allows you to partition tables horizontally across multiple servers. So, you can scale out one database server to a group of database servers that cooperate to provide the same performance levels as a cluster of database servers.

Due to distributed partitioned views, SQL Server 2000 now on the first place in the tpc-c tests.

For more information about tpc-c tests, see: TPC-C tests


Indexed Views

The new SQL Server 2000 feature are indexed views. You can create index on the view, and the result set of the view will be stored in the database. So, you can significantly improve the performance of an application where queries frequently perform certain joins or aggregations. Wnen you will modify the base table, the modifications will be automatically reflected in the view.

You should specify the SCHEMABINDING option for a CREATE VIEW statement, if you want to have a indexed view.

For more information, see: SQL Views


Using Tempdb for CREATE INDEX statement

When you create an index, you can specify WITH SORT_IN_TEMPDB option of the CREATE INDEX statement, which directs the database engine to use tempdb as a work area for the sorts required to build an index. This option reduces the index creation time when tempdb is on a different set of disks than the user database, but increases the amount of disk space used to create an index.

For more information, see: tempdb and Index Creation


Setting index order with CREATE INDEX statement

You can specify ascending or descending order with CREATE INDEX statement. The default is ascending order.

For more information, see: Table Indexes


Creating index defined on computed columns

In SQL Server 2000, you can create indexes on computed columns. The computed column must be deterministic, precise, and must not contain text, ntext, or image columns. The UNIQUE or PRIMARY KEY can also contain a computed column.

For more information, see: CREATE INDEX


Text in Row Data

SQL Server 2000 has eight types of pages in the data files. There are:

* Data pages
* Index pages
* Text/Image pages
* Global Allocation Map, Secondary Global Allocation Map pages
* Pages Free Space
* Index Allocation Map pages
* Bulk Changed Map pages
* Differential Changed Map pages

So, text and image values are stored on the Text/Image pages separately from the other data, stored on the Data pages.

SQL Server 2000 now supports a text in row table option that specifies that small text, ntext, and image values be placed in the Data pages with other data values in the same data row instead of Text/Image pages. This increases the speed of read and write operations and reduces the amount of space used to store small text, ntext, and image data values.

You can set a text in row table option with sp_tableoption stored procedure.

The Joel Test: 12 Steps to Better Code

The Joel Test: 12 Steps to Better Code
By Joel Spolsky
Wednesday, August 09, 2000

// from http://www.joelonsoftware.com/articles/fog0000000043.html

The Joel Test

1. Do you use source control?
2. Can you make a build in one step?
3. Do you make daily builds?
4. Do you have a bug database?
5. Do you fix bugs before writing new code?
6. Do you have an up-to-date schedule?
7. Do you have a spec?
8. Do programmers have quiet working conditions?
9. Do you use the best tools money can buy?
10. Do you have testers?
11. Do new candidates write code during their interview?
12. Do you do hallway usability testing?



1. Do you use source control?
I've used commercial source control packages, and I've used CVS, which is free, and let me tell you, CVS is fine. But if you don't have source control, you're going to stress out trying to get programmers to work together. Programmers have no way to know what other people did. Mistakes can't be rolled back easily. The other neat thing about source control systems is that the source code itself is checked out on every programmer's hard drive -- I've never heard of a project using source control that lost a lot of code.

2. Can you make a build in one step?
By this I mean: how many steps does it take to make a shipping build from the latest source snapshot? On good teams, there's a single script you can run that does a full checkout from scratch, rebuilds every line of code, makes the EXEs, in all their various versions, languages, and #ifdef combinations, creates the installation package, and creates the final media -- CDROM layout, download website, whatever.

If the process takes any more than one step, it is prone to errors. And when you get closer to shipping, you want to have a very fast cycle of fixing the "last" bug, making the final EXEs, etc. If it takes 20 steps to compile the code, run the installation builder, etc., you're going to go crazy and you're going to make silly mistakes.

For this very reason, the last company I worked at switched from WISE to InstallShield: we required that the installation process be able to run, from a script, automatically, overnight, using the NT scheduler, and WISE couldn't run from the scheduler overnight, so we threw it out. (The kind folks at WISE assure me that their latest version does support nightly builds.)

3. Do you make daily builds?
When you're using source control, sometimes one programmer accidentally checks in something that breaks the build. For example, they've added a new source file, and everything compiles fine on their machine, but they forgot to add the source file to the code repository. So they lock their machine and go home, oblivious and happy. But nobody else can work, so they have to go home too, unhappy.

Breaking the build is so bad (and so common) that it helps to make daily builds, to insure that no breakage goes unnoticed. On large teams, one good way to insure that breakages are fixed right away is to do the daily build every afternoon at, say, lunchtime. Everyone does as many checkins as possible before lunch. When they come back, the build is done. If it worked, great! Everybody checks out the latest version of the source and goes on working. If the build failed, you fix it, but everybody can keep on working with the pre-build, unbroken version of the source.




4. Do you have a bug database?
I don't care what you say. If you are developing code, even on a team of one, without an organized database listing all known bugs in the code, you are going to ship low quality code. Lots of programmers think they can hold the bug list in their heads. Nonsense. I can't remember more than two or three bugs at a time, and the next morning, or in the rush of shipping, they are forgotten. You absolutely have to keep track of bugs formally.

Bug databases can be complicated or simple. A minimal useful bug database must include the following data for every bug:

* complete steps to reproduce the bug
* expected behavior
* observed (buggy) behavior
* who it's assigned to
* whether it has been fixed or not

If the complexity of bug tracking software is the only thing stopping you from tracking your bugs, just make a simple 5 column table with these crucial fields and start using it.

For more on bug tracking, read Painless Bug Tracking.

5. Do you fix bugs before writing new code?
The very first version of Microsoft Word for Windows was considered a "death march" project. It took forever. It kept slipping. The whole team was working ridiculous hours, the project was delayed again, and again, and again, and the stress was incredible. When the dang thing finally shipped, years late, Microsoft sent the whole team off to Cancun for a vacation, then sat down for some serious soul-searching.

What they realized was that the project managers had been so insistent on keeping to the "schedule" that programmers simply rushed through the coding process, writing extremely bad code, because the bug fixing phase was not a part of the formal schedule. There was no attempt to keep the bug-count down. Quite the opposite. The story goes that one programmer, who had to write the code to calculate the height of a line of text, simply wrote "return 12;" and waited for the bug report to come in about how his function is not always correct. The schedule was merely a checklist of features waiting to be turned into bugs. In the post-mortem, this was referred to as "infinite defects methodology".

To correct the problem, Microsoft universally adopted something called a "zero defects methodology". Many of the programmers in the company giggled, since it sounded like management thought they could reduce the bug count by executive fiat. Actually, "zero defects" meant that at any given time, the highest priority is to eliminate bugs before writing any new code. Here's why.

In general, the longer you wait before fixing a bug, the costlier (in time and money) it is to fix.

For example, when you make a typo or syntax error that the compiler catches, fixing it is basically trivial.

When you have a bug in your code that you see the first time you try to run it, you will be able to fix it in no time at all, because all the code is still fresh in your mind.

If you find a bug in some code that you wrote a few days ago, it will take you a while to hunt it down, but when you reread the code you wrote, you'll remember everything and you'll be able to fix the bug in a reasonable amount of time.

But if you find a bug in code that you wrote a few months ago, you'll probably have forgotten a lot of things about that code, and it's much harder to fix. By that time you may be fixing somebody else's code, and they may be in Aruba on vacation, in which case, fixing the bug is like science: you have to be slow, methodical, and meticulous, and you can't be sure how long it will take to discover the cure.

And if you find a bug in code that has already shipped, you're going to incur incredible expense getting it fixed.

That's one reason to fix bugs right away: because it takes less time. There's another reason, which relates to the fact that it's easier to predict how long it will take to write new code than to fix an existing bug. For example, if I asked you to predict how long it would take to write the code to sort a list, you could give me a pretty good estimate. But if I asked you how to predict how long it would take to fix that bug where your code doesn't work if Internet Explorer 5.5 is installed, you can't even guess, because you don't know (by definition) what's causing the bug. It could take 3 days to track it down, or it could take 2 minutes.

What this means is that if you have a schedule with a lot of bugs remaining to be fixed, the schedule is unreliable. But if you've fixed all the known bugs, and all that's left is new code, then your schedule will be stunningly more accurate.

Another great thing about keeping the bug count at zero is that you can respond much faster to competition. Some programmers think of this as keeping the product ready to ship at all times. Then if your competitor introduces a killer new feature that is stealing your customers, you can implement just that feature and ship on the spot, without having to fix a large number of accumulated bugs.

6. Do you have an up-to-date schedule?
Which brings us to schedules. If your code is at all important to the business, there are lots of reasons why it's important to the business to know when the code is going to be done. Programmers are notoriously crabby about making schedules. "It will be done when it's done!" they scream at the business people.

Unfortunately, that just doesn't cut it. There are too many planning decisions that the business needs to make well in advance of shipping the code: demos, trade shows, advertising, etc. And the only way to do this is to have a schedule, and to keep it up to date.

The other crucial thing about having a schedule is that it forces you to decide what features you are going to do, and then it forces you to pick the least important features and cut them rather than slipping into featuritis (a.k.a. scope creep).

Keeping schedules does not have to be hard. Read my article Painless Software Schedules, which describes a simple way to make great schedules.

7. Do you have a spec?
Writing specs is like flossing: everybody agrees that it's a good thing, but nobody does it.

I'm not sure why this is, but it's probably because most programmers hate writing documents. As a result, when teams consisting solely of programmers attack a problem, they prefer to express their solution in code, rather than in documents. They would much rather dive in and write code than produce a spec first.

At the design stage, when you discover problems, you can fix them easily by editing a few lines of text. Once the code is written, the cost of fixing problems is dramatically higher, both emotionally (people hate to throw away code) and in terms of time, so there's resistance to actually fixing the problems. Software that wasn't built from a spec usually winds up badly designed and the schedule gets out of control. This seems to have been the problem at Netscape, where the first four versions grew into such a mess that management stupidly decided to throw out the code and start over. And then they made this mistake all over again with Mozilla, creating a monster that spun out of control and took several years to get to alpha stage.

My pet theory is that this problem can be fixed by teaching programmers to be less reluctant writers by sending them off to take an intensive course in writing. Another solution is to hire smart program managers who produce the written spec. In either case, you should enforce the simple rule "no code without spec".

Learn all about writing specs by reading my 4-part series.

8. Do programmers have quiet working conditions?
There are extensively documented productivity gains provided by giving knowledge workers space, quiet, and privacy. The classic software management book Peopleware documents these productivity benefits extensively.

Here's the trouble. We all know that knowledge workers work best by getting into "flow", also known as being "in the zone", where they are fully concentrated on their work and fully tuned out of their environment. They lose track of time and produce great stuff through absolute concentration. This is when they get all of their productive work done. Writers, programmers, scientists, and even basketball players will tell you about being in the zone.

The trouble is, getting into "the zone" is not easy. When you try to measure it, it looks like it takes an average of 15 minutes to start working at maximum productivity. Sometimes, if you're tired or have already done a lot of creative work that day, you just can't get into the zone and you spend the rest of your work day fiddling around, reading the web, playing Tetris.

The other trouble is that it's so easy to get knocked out of the zone. Noise, phone calls, going out for lunch, having to drive 5 minutes to Starbucks for coffee, and interruptions by coworkers -- especially interruptions by coworkers -- all knock you out of the zone. If a coworker asks you a question, causing a 1 minute interruption, but this knocks you out of the zone badly enough that it takes you half an hour to get productive again, your overall productivity is in serious trouble. If you're in a noisy bullpen environment like the type that caffeinated dotcoms love to create, with marketing guys screaming on the phone next to programmers, your productivity will plunge as knowledge workers get interrupted time after time and never get into the zone.

With programmers, it's especially hard. Productivity depends on being able to juggle a lot of little details in short term memory all at once. Any kind of interruption can cause these details to come crashing down. When you resume work, you can't remember any of the details (like local variable names you were using, or where you were up to in implementing that search algorithm) and you have to keep looking these things up, which slows you down a lot until you get back up to speed.

Here's the simple algebra. Let's say (as the evidence seems to suggest) that if we interrupt a programmer, even for a minute, we're really blowing away 15 minutes of productivity. For this example, lets put two programmers, Jeff and Mutt, in open cubicles next to each other in a standard Dilbert veal-fattening farm. Mutt can't remember the name of the Unicode version of the strcpy function. He could look it up, which takes 30 seconds, or he could ask Jeff, which takes 15 seconds. Since he's sitting right next to Jeff, he asks Jeff. Jeff gets distracted and loses 15 minutes of productivity (to save Mutt 15 seconds).

Now let's move them into separate offices with walls and doors. Now when Mutt can't remember the name of that function, he could look it up, which still takes 30 seconds, or he could ask Jeff, which now takes 45 seconds and involves standing up (not an easy task given the average physical fitness of programmers!). So he looks it up. So now Mutt loses 30 seconds of productivity, but we save 15 minutes for Jeff. Ahhh!

9. Do you use the best tools money can buy?
Writing code in a compiled language is one of the last things that still can't be done instantly on a garden variety home computer. If your compilation process takes more than a few seconds, getting the latest and greatest computer is going to save you time. If compiling takes even 15 seconds, programmers will get bored while the compiler runs and switch over to reading The Onion, which will suck them in and kill hours of productivity.

Debugging GUI code with a single monitor system is painful if not impossible. If you're writing GUI code, two monitors will make things much easier.

Most programmers eventually have to manipulate bitmaps for icons or toolbars, and most programmers don't have a good bitmap editor available. Trying to use Microsoft Paint to manipulate bitmaps is a joke, but that's what most programmers have to do.

At my last job, the system administrator kept sending me automated spam complaining that I was using more than ... get this ... 220 megabytes of hard drive space on the server. I pointed out that given the price of hard drives these days, the cost of this space was significantly less than the cost of the toilet paper I used. Spending even 10 minutes cleaning up my directory would be a fabulous waste of productivity.

Top notch development teams don't torture their programmers. Even minor frustrations caused by using underpowered tools add up, making programmers grumpy and unhappy. And a grumpy programmer is an unproductive programmer.

To add to all this... programmers are easily bribed by giving them the coolest, latest stuff. This is a far cheaper way to get them to work for you than actually paying competitive salaries!

10. Do you have testers?

If your team doesn't have dedicated testers, at least one for every two or three programmers, you are either shipping buggy products, or you're wasting money by having $100/hour programmers do work that can be done by $30/hour testers. Skimping on testers is such an outrageous false economy that I'm simply blown away that more people don't recognize it.

Read Top Five (Wrong) Reasons You Don't Have Testers, an article I wrote about this subject.

11. Do new candidates write code during their interview?
Would you hire a magician without asking them to show you some magic tricks? Of course not.

Would you hire a caterer for your wedding without tasting their food? I doubt it. (Unless it's Aunt Marge, and she would hate you forever if you didn't let her make her "famous" chopped liver cake).

Yet, every day, programmers are hired on the basis of an impressive resumé or because the interviewer enjoyed chatting with them. Or they are asked trivia questions ("what's the difference between CreateDialog() and DialogBox()?") which could be answered by looking at the documentation. You don't care if they have memorized thousands of trivia about programming, you care if they are able to produce code. Or, even worse, they are asked "AHA!" questions: the kind of questions that seem easy when you know the answer, but if you don't know the answer, they are impossible.

Please, just stop doing this. Do whatever you want during interviews, but make the candidate write some code. (For more advice, read my Guerrilla Guide to Interviewing.)

12. Do you do hallway usability testing?
A hallway usability test is where you grab the next person that passes by in the hallway and force them to try to use the code you just wrote. If you do this to five people, you will learn 95% of what there is to learn about usability problems in your code.

Good user interface design is not as hard as you would think, and it's crucial if you want customers to love and buy your product. You can read my free online book on UI design, a short primer for programmers.

But the most important thing about user interfaces is that if you show your program to a handful of people, (in fact, five or six is enough) you will quickly discover the biggest problems people are having. Read Jakob Nielsen's article explaining why. Even if your UI design skills are lacking, as long as you force yourself to do hallway usability tests, which cost nothing, your UI will be much, much better.

Four Ways To Use The Joel Test

1. Rate your own software organization, and tell me how it rates, so I can gossip.
2. If you're the manager of a programming team, use this as a checklist to make sure your team is working as well as possible. When you start rating a 12, you can leave your programmers alone and focus full time on keeping the business people from bothering them.
3. If you're trying to decide whether to take a programming job, ask your prospective employer how they rate on this test. If it's too low, make sure that you'll have the authority to fix these things. Otherwise you're going to be frustrated and unproductive.
4. If you're an investor doing due diligence to judge the value of a programming team, or if your software company is considering merging with another, this test can provide a quick rule of thumb.

среда, 3 сентября 2008 г.

GEO Distance function in MySQL

Returns distance in meters between two geo points defined by their latitude and longitude.


DELIMITER $$;
DROP FUNCTION IF EXISTS Dist$$

CREATE FUNCTION Dist (lat1 float, lon1 float, lat2 float, lon2 float)
RETURNS float
BEGIN
RETURN 6370.695763 * acos(sin(lat1/57.2958) * sin(lat2/57.2958) + cos(lat1/57.2958) *
cos(lat2/57.2958) * cos(lon2/57.2958 -lon1/57.2958))

END $$
DELIMITER ;$$


in miles:
the formula is
3958.5668 * acos(sin(lat1/57.2958) * sin(lat2/57.2958) + cos(lat1/57.2958) *
cos(lat2/57.2958) * cos(lon2/57.2958 -lon1/57.2958))



References:


- Mathematical Functions in MySQL
http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html
http://dev.mysql.com/doc/refman/4.1/en/mathematical-functions.html

- CREATE FUNCTION in MySQL - syntax
http://dev.mysql.com/doc/refman/5.0/en/create-function-udf.html

вторник, 2 сентября 2008 г.

ASP Net - Run Application (EXE) from ASP.Net C#

Task: run application from ASP.NET

for example,
you have a button on ASP.NET page, when press this button - one application is invoked.


the code to run application (for example, notepad) is (on C#)

System.Diagnostics.Process.Start("notepad");

but the problem is that the application doesn't run, i.e. no window is opened.

Note that ASP.NET code is executed on the SERVER.

Solution:

ASPNET user under which application is run should have appropriate security settings.

1. change local policies for APSNET user:
in WinXP: run secpol.msc

go to Local Policies->User Rights Assignment

find "Deny logon locally" and remove ASPNET user from it.
also find "Deny logon .. terminal" and remove ASPNET user from it.



2. Security for files.
if your application needs also to work with files (open, save, etc) you have to change security settings for the folders to allow user ASPNET modify nedeed files.

to do this:
- In Explorer right button mouse click the folder and select "Properties"
- In Security tab, add "ASPNET" in and give desired permissions (Read, Write, Execute, etc).


To test how it works without starting ASP.NET site you can try run in Windows command line:

runas /user:ASPNET "notepad.exe"

it asks you for the password of ASPNET user. enter the password.
if everything is done correct you will see opened application (notepad in our example) in new window.


I've tried this on my Windows XP Professsional and it worked fine.


Read more

- Unable to Start a Process from ASP.NET
http://support.microsoft.com/kb/555134


- ASP.NET Impersonation
http://msdn.microsoft.com/en-us/library/aa719560.aspx

- How to configure the process identity for the ASPNET account in ASP.NET 1.1 when you use IIS 5 Isolation mode in IIS 6.0 on Windows Server 2003