К основному контенту

Сообщения

Сообщения за 2012

Query optimization in Oracle DB

Short article to help newbies (like me) find a way where to go for optimizing SQL queries in Oracle. First of all, before you started "dance with optimization" you need to know about "short-circuit" run. When you make a SELECT with many conditions Oracle handles this with short-circuit execution, so order of parameters is really matters. You should use optimal parameters order first of all: if Oracle will need to check only one condition from three, this is good way of optimization! Let's think about example of selecting records in a dates range and filter out these records by NULL-field: SELECT * FROM Table t WHERE t.SomeField not null AND t.StartDate between SomeDate1 and SomeDate1+0.999999 This query could be more effective if you set Dates Condition first, because Oracle will filter out MOST part of data and it will be more easy to check last one. Depending on the count of data, this could be very helpful. Second base knowing is Query Plan. Such application

Оптимизация запросов Oracle DB

Коротенький пост, который может начинающим помочь в том, куда копать для оптимизации SQL запросов Oracle. Итак первое, прежде чем изучать трюки или ещё как-то извращаться с SQL, нужно знать, а для знающих не забывать, что при обычном SELECT с множественным условием, Oracle работает по схеме short-circuit. Это означает, что порядок условий должен быть наиболее оптимальным, так как Oracle при отсутствии необходимости выполнять следующие условия, может отработать только на первых - то есть какую-то часть сравнений вовсе опустить, если они не нужны. К примеру, вы хотите выбрать из таблицы записи в промежутке между датами и при этом отфильтровать их по нулевому полю: SELECT * FROM Table t WHERE t.SomeField not null             AND t.StartDate between SomeDate1 and SomeDate1+0.999999 Данный запрос нужно выполнить и посмотреть не будет ли он эффективнее, если сначала поставить условие выбора даты . Таким образом, Oracle сразу отфильтрует эти записи (причем часто, большую часть), и второе

XML serialization of derived classes

Sometimes you need to serialize objects of derived classes in the XML. You may find a lot of blogs about how to do this on C#. But the most of them will give a simple answer to add an XmlInclude attribute on base class. In some cases this is not enough because of tricky logic inside of standard XML Serializer. Some people solved this problem by overriding the XML Serializer with more tricky one. This article will give an answer to solve one particle task about the serialization of derived classes, but probably this may help to find out ways to do this with less pain. I had to create an XML file which presents the full structure of maps database entities (i.e. with indeces, parents and childs ids, etc.). I've got specifications from the client describing how the XML file should look like. Every tag in the XML should present the real entity in their database. But the main problem is that our database looks differently from the their ones. So I had to create a lot of wrappers s

What should be the comments in the code...

Hi there, I've read a cool code review of the game Doom for iPhone ported recently by John Carmack. During the reading of this beautiful article I thought 'what a nice commenting of the bottlenecks'. I think such a comments should be in the every part of the code, where you should think more than 30 seconds to understand. Example: // JDC: E3M8 has a map error that has a couple lines that should // be part of sector 1 instead orphaned off in sector 2. I could // let the non-closed sector carving routine handle this, but it // would result in some pixel cracks. Instead, I merge the lines // to where they should have been. // This is probably not the right solution, because there are // probably a bunch of other cases in the >100 Id maps. extern int gameepisode, gamemap; if ( gameepisode == 3 && gamemap == 8 ) { void IR_MergeSectors( int fromSector, int intoSector ); IR_MergeSectors( 2, 1 ); } Here is link:  Doom Iphone code review Have a nice reading!

C++ core

At the morning I've read the beautiful article about the storage layout of Polymorphic Objects in C++. Here is . It describes how objects of a classes with virtual functions are placed in the memory, by simple pictures. I've some links to read more about the C++, tables of virtual functions, memory and etc. Here is (sorry, most of them is on russian language): Lessons on development of 64-bit C/C++ applications . 100 bugs in Open Source C/C++ projects . COM C++ in deep . Yes, old technology, but it describes really interesting things. Blog Alena C++ .

Solved problems with cooperating of Visual Studio 2012 and SQL Server 2008

Hi guys,   Today I've solved a problem of absense of SQL Server on mine machine after I had installed new Visual Studio 2012. So, a lil'bit of story...   Recently I was needed to reinstall Windows 7 on mine machine and clearly install all the software for my work, like IDE's, SQL server, etc. So, after I've installed Visual Studio 2010 I decided to install trial version of newely available Visual Studio 2012 to look at it. VS 2010 installed some SQL Server 2008 developer tools and components and VS 2012 did the same for the SQL Server 2012. And I thought that all is gonna be OK with installing of SQL Server 2008 Express for working with databases from ASP.NET MVC... and I've installed it.   I have ASP.NET MVC3 application with using of Entity Framework Code First as the ORM. As you probably now it lazily generates the database depending on the rules you have created for it (Inherit yours DBContext from the DropCreateDatabaseAlways or DropCreateDatabaseIfModelCh

Problems with Oracle SYS_CONTEXT function

Hey there,   Today I've solved an interesting bug in the existent database procedures. Actually, it's not the bug right now, but it definitely will after a couple of years.   We have an ASP.NET web site which works with the Oracle based database. There're no any entity model (it's old system with just a support for now) and all the queries are native SQL or calling SQL procedures from the database itself. Database generates new "unique" oid for every newly created entity with well-known procedure like this: CREATE OR REPLACE FUNCTION new_uuid RETURN VARCHAR2 AS   l_seed        BINARY_INTEGER;   l_random_num  NUMBER(5);   l_date        VARCHAR2(25);   l_random      VARCHAR2(4);   l_ip_address  VARCHAR2(12); BEGIN   l_seed       := TO_NUMBER(TO_CHAR(SYSDATE,'YYYYDDMMSS')); DBMS_RANDOM.initialize (val => l_seed);   l_random_num := TRUNC(DBMS_RANDOM.value(low => 1, high => 65535)); DBMS_RANDOM.terminate;   l_date       := conversion_api.to_hex(   

How to write a UTF-8 encoded string to a file in windows, in C++

Recently I solved a problem of reading and writing UTF8 text for multiple cultures (like Japan, China, France, etc.) in C++. And I've posted this example on stackoverflow ( original link ). Here is just a copy of my elder link. It is easy if you use C++11 standard. But if you want to create multiplatform code with elder standards, you can use this method (like I used): - Read the following article: Code Project - Reading UTF-8 with C++ streams - Add `stxutif.h` to your project from sources above - Open file in ANSI mode and add BOM to the start of a file first of all, like this:    std::ofstream fs;    fs.open(filepath, std::ios::out|std::ios::binary);    unsigned char smarker[3];    smarker[0] = 0xEF;    smarker[1] = 0xBB;    smarker[2] = 0xBF;    fs<    fs.close(); - Then open file as UTF and write your content there:    std::wofstream fs;    fs.open(filepath, std::ios::out|std::ios::app);    std::lo

PR: Сделал Windows Phone приложение для конкурса Вконтакте

Учавствовал в конкурсе ВКонтакте на написание клиента под Windows Phone. 5 недель разработки после full-time работы по вечерам и по выходным конечно давались нелегко, хотя очень и очень интересно! Трудно разрабатывать под платформу, в описании функций которой много ошибок, и некоторые из них вовсе периодически "отваливаются". С другой стороны, Windows Phone как платформа для разработки для меня нова - это было по сути первое моё приложение. "С места и в карьер", как говорится. Никаких "Hello world" и т.п. я не писал. Книжки листал поверхностно по мере появления вопросов. С одной стороны, честь и хвала Microsoft за создание такой платформы, под которую можно начать что-то писать не изучая вдоль и поперёк эту платформу. У меня был подобный опыт с платформой Android на Java. Там я тоже довольно быстро "въехал", и начал писать. Однако, Eclipse мне очень не понравился, ну и, конечно же, отсутствие опыта разработки на Java меня сильно тормозили. Не хо

Моё знакомство с ASP.NET MVC3 и Entity Framework Code First...

Пишу этот пост, потому что сам при изучении объявленных фреймворков наткнулся на неожиданности. Где-то сбили с толку форумы, где-то читаемые книжки, что в итоге перешло в: первое - неоценимый опыт, второе - кучу потраченного времени =). Этот пост: просто набор ссылок и заметок (я и сам, возможно, буду его использовать в качестве напоминания =)). Хотя я и писал кое-что на php и javascript (в том числе мой сайт), однако до сей поры профессионально занимался разработкой только клиент-серверных и десктопных приложений на C++ (MFC, COM) и C# (WPF, WinForms), и в веб не совался. Но прогресс и мой интерес к технологиям не остановить, поэтому занимался и сторонними вещами, типа XNA Game Engine, Java Script, и т.д. Ни php ни ASP.NET мне не нравились. Php из-за самого языка и какой-то "немного левой" поддержки ООП, а ASP.NET - из-за code-behind'ов и, главным образом, отсутствия положительных комментариев вообще об этой технологии. Когда же появился Asp.Net MVC - перспективная т

Домбай 2012

Нас высадили из автобуса рано утром, только начинало светать. Домбай, небольшое поселение, в котором дома можно пересчитать по пальцам, был завален снегом, что называется, "по уши". Дороги были кое-как почищены, но заваленные снегом крыши домов и автомобилей, нависающие с заборов сугробы и суровый туман над горными пиками, напоминали о недавно прошедшей метели. Гостиница "Солнечная долина" вполне дружелюбна, хотя и до забавного простая. Вся полностью построенная из дерева, она придаёт особой остроты ощущению того, что ты в горах, в лесу, на природе... Конечно, гостиница запущена, как нам и обещали, когда мы покупали путевки. Но мы решили, что в первый раз поедем сами и всё посмотрим. Комнаты гостиницы отапливаются только переносными обогревателями: у кого масляными, у кого спиральными. Причем нагнетательные спиральные обогреватели лучше и быстрее делают свое дело, поэтому мы один обогреватель носили между 3мя комнатами, дабы согреть всех =).