Wednesday, November 09, 2005

Full and Partial Assembly Names

Preface

Recently my wife encountered weird problem with PropertyGrid control. As you know this control displays object properties and gives the posibility to edit them. If object has properties that return CollectionBase types, property grid displays nice dialog that allows editing collection items.

Type of the edit dialog is specified by the Editor attribute. ( see MSDN for details ).

The Problem

Property called Items returns CollectionBase type. Namely StringCollection.
The snippet below illustrates the situation:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing")]
public StringCollection Items
{
//common stuff goes here
}

Everything looks fine, however when the object with this property is given to PropertyGrid, collection edit
dialog doesn't recognize its true string nature. Instead of StringCollectionEditor we observer common editor dialog,
where collection items have type System.Object. Somehow PropertyGrid didn't recognized the attribute, or attribute
contents...

Stephen Toub in his blog directly addresses
this problem. Yes the problem was with partial names. So the solution is very simple if you're the owner of the
code, where that attribute is specified, and you can easily chage it.
So, the working version will look like:

[Editor(
"System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=1.0.5000.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public StringCollection Items
{
//common stuff goes here
}

For those who use 3-d party classes and have no access to source code, there are 2 solutions:
1) modify the DEVENV environment variable
2) put System.Design.dll assembly to the folder, where your app resides

First way isn't good as it may affect other applications that rely on that variable and it is not safe.

My wife chose second way, she just added System.Design.dll to the references list and set "Copy local" property to true.

Monday, September 26, 2005

Server side: ETag VS Cache-Control max-age=xxxx or Expiration VS Validation

I will not cover here the whole topic of the web caching, but there things, which I'd
like to mention. They are the two caching mechanism:
1) is configured in the server ( in IIS we can set expiration date or expiration timeout ( e.g. max-age ) and on Apache we even can set cache policy for different content types )
2) no configuration in the server ( client uses "ETags" for cache validation ) - the default one.

Now lets consider 1st way, we configure web-server and set expire time as 1 hour ( max-age = 3600 ). What will now happen? Client will download the resource with the header - Cache-Control: max-age = 3600, store this value and will also store the date, when that resource was downloaded. Then every time during 1 hour when client browser
receives reference to the resource he will check download date & max-age value of it, and if the content is up-to-date, browser will not send request to the server, and it will use cached resource.

On the other hand ( 2nd way ) server has no configuration settings. Every resource downloaded from the server has it own "ETag". Next time, when browser accesses the resource it sends request to the server, and server sends response, containing error - 304 ( not modified ). This code signals client to use cached version of the resource.

While analyzing these two techniques we can come to the conclusion:
1) when using 1st way - we reduce the number of server roundtrips, thus have better network performance.
2) when using 2nd way - we have greater number of roundtrips to check the resource ETag.

The pros and cons are the following here:
1st way, greater network performance but cache will be invalidated only after period of time 2nd way, lower network performance but cache will be invalidated correctly, when resource will be changed.

The above said in the HTTP spec it is stated as
"The former reduces the number of network round-trips required for many operations; we use an “expiration” mechanism for this purpose (see section 13.2). The latter reduces network bandwidth requirements; we use a “validation” mechanism for this purpose (see section 13.3)."

From the HTTP spec:
"Caching would be useless if it did not significantly improve performance. The goal of caching in HTTP/1.1 is to eliminate the need to send requests in many cases, and to eliminate the need to send full responses in many other cases."

Update: actually 1-st and 2-nd methods can also be used togther. Using them combined can reduce not only the number of requests but also response size.
For instance if two methods are used together: the resource will at first expire and after that it will be checked (validated) for change.

Wednesday, September 21, 2005

neural networks

In the place where I study, we started new course - Neural Networks. The teacher gives us only mathematical basis, however, there is huge load of materials on the Net, with the applicable samples and source code...

http://www.csharphelp.com/archives2/archive407.html


http://www.kdkeys.net/forums/ShowPost.aspx?PostID=3069


http://franck.fleurey.free.fr/NeuralNetwork/

Monday, July 25, 2005

Writing .NET proxy/tunnel engine for the HTTP

In my home network I have 2 computers: one of them is connected to the internet via dial-up connection. My pc has no modem, that is why to access the Internet I have to work on the other PC. I know that there is a bunch of gateway/proxy software that has the required functionality for tunneling http requests, but they aren’t open source and cannot be extended.

My goal is write extensible proxy engine, with default http tunneling implementation. And in the future other protocols may be added to it.

So, for now I’m studying RFC 2617 (Hypertext Transfer Protocol)…

Wednesday, May 18, 2005

interconnecting asp and asp.net sessions

Recently I came across an interesting situation, I needed to synchronize asp and asp.net sessions(our application is a combination of old asp and new asp.net code).

The asp.net session timeout can be configured in web.config file, and after the specified timeout period elapses, session is being terminated - asp.net session not asp. In order to access the asp session variables, when asp.net session is terminated - I crafted web request that was sent to special asp file. In this file script cleans up session variables and the whole asp app thinks that its session is terminated.

The trick here was that all the cookies, that were created in the session, had to be present in the http request header. Asp page discovers its state using these cookies.

P.S. in the asp script to which the request will be sent it is necessary to compare the host that issued the request and local address - they must be the same. If not performing this check, this will leave security breach in the web app

Wednesday, May 11, 2005

Пошук витоків пам"яті у веб-програмах

Досить недавно проводили пошук витоків пам"яті ( memory leaks ) у нашій веб-програмі. Проблема була описана досить туманно: казали, що сервер використав багато пам"яті, при цьому не згадували, ні, що за програма була такої ненажерливою, ні умов при яких таке відбувалося. Сказали тільки, що після 3-ьох днів роботи програми, сервер потрібно було перезавантажувати.

Це була передісторія. Тепер розкажу, як це все тестувалося... Є така прорама, як Microsoft Application Test Center, вона дозволяє проводити стрес тести для веб-програм. Принцип дії дуже простий - програміст створює проект, потім записує всі свої дії у броузері. Далі генерується код на VB, що відповідає діям користувача. Ось і все - тест готовий, можна починати тестування.

Так як наша програма була спочатку написана індусами, тому перш за все ми подивилися на код. Якість останнього залишала бажати кращого: код досить путаний, до того багато місць у яких пам"ять може "тікти". Наприклад на сервері створюється об"єкт ADODB.Connection, котрий потім не знищується. Таких місць у коді було досить багато. Іншим інструментом, яким ми користувалися був AdoMonitor 1.0 ( http://www.troxo.com/products/adomonitor/ ) - дозволяє трасувати все, що відбувається з ADO.

Цікавий факт, якщо залишити asp код таким, яким він був, тобто з витоками пам"яті,то - після 4-ох хвилин роботи веб-сервер "підвисав" і починав працювати тільки після того, як його перевантажать. Інший цікавий факт, був пов"язаний з ADO, виходить, що на стабільність нижче наведений код ніяк не впливає, так само, як і на витоки пам"яті:

Set cn = server.CreateObject("ADODB.Connection")
cn.ConnectionString = someConnectionString
cn.Open
'cn.Close можна навіть не викликати, об"єкт буде знищено все одно, а з"єднання 'повернеться у пул
cn = Nothing

Thursday, January 06, 2005

Думки спричинені появою нової машини...

Сьогодні отримав нову машину Celeron 2400MHz, 512Mb RAM, 80 HDD. Чесно кажучи, я чекав оновлення вже давненько і от сьогодні це сталося. Знаки давно вже говорили про заміну "заліза", ну не тільки знаки, начальство також про це висловлювалося :8-).

Новий комп"ютер я "юзаю" вже години так зо 2, мушу визнати - відчуття тільки приємні. Вінчестер на 80Gb з 8Mb кешу, працює дуже добре: практично не відчувається, що він участує в процесі роботи операційної системи. Але найбільше мені сподобалося те, що USB виходи знаходяться не тільки позаду системного блоку, а й спереду. Це дуже зручно, якщо користуєшся Flash Drive'ом, чи якимось іншим USB-пристроєм.

Цікавий факт з оновленнями - спочатку сприймаєш все по-новому: програми стали працювати швидше, наче продуктивність праці також зростає, нервова система під час роботи спокійна; а потім, через деякий час, коли все входить у норму, починаються ті ж самі проблеми, що були до оновлення. Тобто, потроху забувається, те що було тоді ( коли була стара машина ), а можливості нової, вже не є такими помітними, так як увійшли в норму. Ще проходить трохи часу і цього вже також замало - хочеться знову оновлення...

Отже, маємо нескінченне коло :8-) А для того, щоб з нього вийти, просто потрібно зайнятися порівняннями, бо все у світі відносне...

Wednesday, January 05, 2005

Різноманітні підходи до одного й того ж

В теперішній час мало нас оточує багато предметів побуту та різноманітної, в тому числі електронної, техніки. Виробники надають технічну документацію до своїх виробів, вона описує їх функціонал та принципи використання. А саме, як "добратися" до тієї чи іншою функції. Це може стосуватися не тільки виробів, а й програмного забезпечення.

І от тепер по суті. Коли виріб попадає до клієнта, він може: а) покладаючись на свою інтуіцію почати розбиратися, як даний виріб функціонує; б) спочатку прочитати всю інструкцію, а потім вже перейти до практики; в) читаючи інструкцію, перевіряти відразу на практиці ( дуже сильно залежить від формування інструкції ).

Я знаю людей, яким "прикольно" розбиратися без документації, вони втрачають більше часу для того, щоб розібратися з функціями. Свої дії вони пояснють тим, що їм цікаво у чомусь розбиратися, навіть якщо в принципі речі тривіальні, або стають такими, після прочитання інструкції.

Сам же відношуся до тих, хто читаючи інструкцію - перевіряю одразу й функціонал. Але досить часто зустрічається суперечлива або невпорядкована документація, і тоді можна втратити більше часу, ніж якщо розбиратися самому...

Зі всього вищесказанного можна робити такі висновки:
- терпимо ставитися, до людей, які методом проб і помилок здобувають знання(хоч і тривіальні). Для них подібний спосіб - є задоволенням.
- якщо займаєшся документацією, зважай на тих, хто спочатку читає, а потім робить. Якісна документація говорить про якісний продукт...

Tuesday, January 04, 2005

Good article about Moore's Law

http://www.gotw.ca/publications/concurrency-ddj.htm

First post on the blog

Heh, it is the first post of Ukrainian dev, who decided to write to blog :8-)