tag:blogger.com,1999:blog-30297146095960827082024-03-13T03:46:55.447+02:00Thoughts and TechnologyItai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.comBlogger37125tag:blogger.com,1999:blog-3029714609596082708.post-74886731971464227342013-11-09T12:06:00.001+02:002013-11-09T12:17:55.205+02:007 Weeks with Linux - ImpressionsI've been using Linux as my primary (well, only) operating system for about 7 weeks now. There are things I like and things I dislike and things that are simply annoying.<br />
<h2>
<br /></h2>
<h2>
The Good</h2>
<div>
So I figured, if today the main thing we need is a web browser, so why do we need more than a free OS? Indeed, Ubuntu comes with Firefox by default, and for me, a Chrome favorite, installing Chromium from the Ubuntu Software Center (aka the App Store) was a piece of cake.</div>
<div>
<br /></div>
<div>
Installation of the OS was real easy, and so was the upgrade (started with Ubuntu 13.04, upgraded to 13.10).</div>
<div>
<br /></div>
<div>
Linux seems to make fairly good use of the hardware and gave me accelerated OpenGL graphics, audio and network out of the box.</div>
<div>
<br /></div>
<div>
Ubuntu also comes with several extras from basic tools like a notepad (<i>gedit</i>, that is by far better than windows <i>notepad</i>, and more resembles <i>notepad++</i>), through picture, video and audio players, to advanced tools like an entire office suite (<i>libreOffice</i>, which is nice but quite heavy, so I prefer online tools), all out of the box. Most other things can easily be downloaded from the Software Center.</div>
<h2>
<br /></h2>
<h2>
The Bad</h2>
<div>
While most things can be installed from the Software Center, not everything is available, and not once I found myself searching the web for a better solution for a program I couldn't find. I'm talking about development tools, which was pretty odd to me, as I thought Linux is the cozy home of all software development. Well, maybe just home, surely not cozy. The better development tools I know are for Windows. Linux is all about hard, notepad development and command line compilation. Sure, you can find <i>MonoDevelop</i>, and <i>Eclipse</i> is Java base which makes it cross platform, but that's about it, and they are limited (PHP anyone?)</div>
<div>
<br /></div>
<div>
I could find <i>AptanaStudio</i>, an <i>Eclipse</i> based IDE for web development, and this is the main tool I use, and acutally this is the same tool I used on Windows for the same kind of development, so I guess I can't complain, except for it not being in the Software Center.</div>
<div>
<br /></div>
<div>
Coming down to the people from the development ivory tower, I couldn't find an official app for SkyDrive.</div>
<h2>
<br /></h2>
<h2>
The Ugly</h2>
<div>
There are many things that are just annoying. I thought that by the end of 2013 they'll be handled by now, but it seems Ubuntu rather put their efforts on the HUD (Heads Up Display) that gives me results I don't need for my searches rather than implement missing drivers and such. And I already wrote a post about security.</div>
<h3>
<br /></h3>
<h3>
HUD</h3>
This is were you search your computer. You type something in, and get a list of results. The results are from installed apps, files you may have, apps of the Software centers, and all over the world - Wikipedia, Foursquare, YouTube, MySpace, whatnot. I find it very annoying.<br />
Another thing that is annoying in the HUD is that when you change search criteria, say from "All" to "Software", it loses the search term.<br />
<h3>
<br /></h3>
<h3>
Local Network Connectivity</h3>
<div>
Connecting to the Internet is simple and done quickly. That's true also to connecting to Windows networks through Samba (SMB:// addresses). However, it just doesn't recognizes other Ubuntu machines on the local network.</div>
<div>
I tried sharing the folders and giving access to just about everyone in the universe and still it doesn't recognizes the other machine. Which is annoying, because the other machine is in the living room, which doesn't have the same conditions to work with as the main computer. I want to copy files, that's it. Just log in using the file manager to the other computer on the network and move files around. And I can't even get there. Annoying. I though this would come out of the box, and I can't even get it to work at all.</div>
<h3>
<br /></h3>
<h3>
Drivers</h3>
<div>
I run an Intel Core I5-4430 system. A small one. I didn't put a discrete graphic adapter in it since the one integrated in the CPU is far beyond all my (current) needs. However, when trying to run software like BOINC distributed computation (World Community Grid), or a BitCoin miner, it tells me it couldn't find any usable GPGPU (that's General Purpose GPU. It actually says things like "No usable GPUs found" or "No OpenCL devices found").</div>
<div>
Intel don't have drivers yet. Don't know if they will. After a lot of searching and attempts to get this to work with all kinds of workarounds, I just gave up.</div>
<div>
<br /></div>
<div>
These are my main impressions from Ubuntu, but all in all I still rather use it than Windows, and if only because of Windows' lengthy reactivation issues.</div>
Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com1tag:blogger.com,1999:blog-3029714609596082708.post-53143052015653136752013-09-23T19:53:00.002+03:002013-09-23T19:56:07.840+03:00Moving to Linux - Said and DoneIn one of my earlier posts <a href="http://itaibh.blogspot.co.il/2011/06/thinking-of-moving-to-linux.html">I blogged about switching to Linux</a>.<br />
That was in May 2011, today is September 2013... it took over two years, but I'm happy to say that the transition has finally happened! (two months ago)<br />
<br />
It happened when I bought my new computer about two months ago (<a href="http://itaibh.blogspot.co.il/2013/09/old-computer-died-rip.html">the old one pretty much died</a>):<br />
<br />
When I bought the new computer I wanted it to be as small as possible and yet to have an optical drive, USB 3 connectors, 8 GB of RAM and 500 GB hard drive. I knew I needed to move the data from my old hard drive, and didn't know if I'd have any way of connecting it in addition to my new hard drive, so I got an external hard drive dock.<br />
<br />
I connected the dock to the USB and power, placed the old hard drive in there, turned the power on and made sure the computer will boot from USB.<br />
Indeed, my old Windows 8 (yeah, I know, but it replaced my older Vista (again, yeah, I know, but it was state of the art when I bought it), and besides, it didn't cost me that much) came up, but since it detected my hardware configuration had changed (basically all of it), it booted directly to repair mode and suggested to automatically repair my Windows installation.<br />
<br />
Sounds great! Sure, do that!<br />
<br />
Windows was then started working its magic for about 20 minutes, just to let me know it had failed. Thank you so much!<br />
<br />
After thinking how to fix things (I even thought to re-install Vista from the original DVD I had, but the only valid key was written on a sticker on the side of my old computer, and that sticker was already half torn, so I didn't have a key), I figured I can perhaps use Linux to fix it. I don't remember now exactly what my idea was, but it very quickly changed to "Hey! I can just use Linux instead and that's it!"<br />
<br />
And that's what I did:<br />
<br />
<ul>
<li>I installed <a href="http://www.ubuntu.com/">Ubuntu</a> 13.04 64 bit using a flash drive.</li>
<li>In order to recover the important data from the older hard drive I used the external dock and copied everything I wanted to save.</li>
<li>I had a network drive I wanted to mount in a certain way. I thought this would be simple, and turned out it took a little work to get it done the way I wanted it, but now it's good.</li>
<li>I had some paid services (well, just one actually - <a href="http://www.crashplan.com/">CrashPlan</a>), so I downloaded it from the website and installed it. I had to reconfigure it to work with the new configuration, and it was a little time consuming hassle, but now I have a working automatic backup running again.</li>
<li>I also had other online services (<a href="https://www.dropbox.com/">DropBox</a>, <a href="http://www.copy.com/">Copy</a>) I wanted to use, but happily, these were just working out of the box.</li>
<li><a href="http://www.skydrive.com/">SkyDrive</a>, however, does not, and I still don't have it configured. Instead, I just moved everything I had on SkyDrive to Copy.</li>
<li>I don't know about Google Drive - I use it online, but I never had its local application installed.</li>
<li>I was using the <a href="http://itaibh.blogspot.co.il/2009/03/grid-computing-and-charity.html">BOINC Manager</a> (for grid computing, running tasks from <a href="http://www.worldcommunitygrid.org/">World Community Grid</a>), so I just installed its Linux version, and everything is the same.</li>
</ul>
<div>
Now about that Windows installation I had... I didn't want to just throw it away, and some applications still must run on Windows... OK than - let's install it on a virtual machine!</div>
<div>
I installed and launched <a href="https://www.virtualbox.org/">VirtualBox</a>, loaded some old virtual machines I had (I had the Windows 8 Developers Preview installed as a virtual machine on my old hard drive, so I just copied it and used it as a base for my new Windows 8 installation). I recovered the installation key from the purchase emails, updated the installation using it, got a new key, re-registered it by phone and now, after all that hard work, I have a Windows 8 virtual machine, ready for a rainy day.</div>
<div>
<br /></div>
<div>
So, to sum things up - transition to Linux wasn't smooth, and there are still some things I don't like (that's for another post), but I have no major problems with it, I like it a lot, and all in all I think it was a good decision. Hopefully in the next versions such transitions could be made smoother and more people will prefer to use it over paid alternatives.</div>
Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-86375637095113573482013-09-23T19:42:00.001+03:002013-09-23T19:42:21.466+03:00Old Computer Died. RIP?When I bought my computer in early 2008 I decided it should be a beast.<br />
I got a Tower casing with a quad core processor, 4 GB RAM, 250 GB hard drive and some medium level nVidia graphics adapter.<br />
I figured I could always replace some parts (like memory, hard drive, graphics adapter) but generally, it was a strong computer that was suppose to be sufficient for my needs for many years.<br />
<br />
It did survive almost 6 years, but in its last days (well months, actually) it started giving me hard time:<br />
It was shutting the screen down off all of the sudden, or rebooting just because, or having the entire screen go the same color (I remember off-white, pink and light blue as the colors it used to get stuck in) and doesn't letting me do anything anymore.<br />
<br />
I tried to understand what was happening by looking at system logs, but it quickly reminded me of an old joke: "How many programmers does it take to replace a light bulb?". None. It's a hardware problem.<br />
<br />
So I got a new computer (double the performance, half the price, quarter the size), installed a brand new operating system (moved to Linux, finally), and now the old one is standing on the side of the room, useless.<br />
<br />
Now the thing is, I think it is salvageable. A good chance it is the graphics adapter, and if I can only get a new one things will work just fine. I thought of connecting the monitor the on-board VGA output, but alas! There is no on-board VGA output!<br />
<br />
I feel sorry not to resurrect this computer, because it has a fairly good specifications even in today's (2013) standards. For one, it has a quad core processor, when most processors today are only dual core. OK, so it's the first major quad core series and much slower than the new series, but who really cares when all you want to do is use the browser? Second, it has 4 GB RAM, meaning it must run 64 bit operating system to use it all. Most cheap systems still come with a 32 bit operating systems, and some come with only 2 GB of RAM. And third, it has room for more! More memory, more hard drives, more bays that can be used...<br />
<br />
Maybe sometime soon I'll try to save it. Or maybe I'll just sell it for some low price. I thought I'd give it away as a donation for some school or something, but I figured I can't really donate something that doesn't work.Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-71620634836482466392013-09-06T12:31:00.001+03:002013-09-06T12:31:53.863+03:00Computer security when physical access is compromised<div>
Before I begin:</div>
<div>
I'm writing this post because I tried getting answers in forums, but got no real answers. Most answers referred to the user as the problem, and while I accept the user is always the weakest link, the software one uses should protect him/her from the things he/she doesn't know.</div>
<div>
I don't believe teaching users is the only way to go like some others told me in forums. Teaching comes last, not first, when all other things have been done, simply because human beings make mistakes.</div>
<div>
<br /></div>
<div>
And now for the main article:</div>
<div>
<br /></div>
Couple of friends of mine had their home broken into and their laptop computer stolen. Bad enough, you may think, as a laptop computer costs quite a lot of money. Now you may think that all the documents and photo, unless backed up, are lost, and that's a greater problem of its own. Well, it gets worst - their online accounts were broken in to and money was stolen using their PayPal account. The scariest thing about this is the thing you don't know about - Identity Theft.<br />
<br />
Today there are all these cloud services, like DropBox and Copy and Google Drive. We store all the important things there, so we won't lose them, and because it is much easier to share files between several computers that way.<br />
<br />
However, when a computer is physically stolen (and a laptop is the second easiest computer to steal after the smartphone) it compromises all of your online data.<br />
<br />
"How?" you may ask. "My account is password protected, and I even chose a very strong password!"<br />
<br />
That's great, but unfortunately will not help you if your computer was stolen. It might help you, actually if you are always signing out, but if you don't that means your data is probably lost by now.<br />
<br />
"OK, I see what you mean, and I usually signing out of most things, like my bank account, which by the way is signing out automatically if I haven't done anything for a few minutes, and my DropBox account. I try to sign out of everything I don't use regularly."<br />
<br />
What about your email account?
<br />
<br />
"I use my email regularly, no point for me to sign out, I'll get back to it in a few minutes. An hour tops."<br />
<br />
Did you check the "Remember me" or "Keep me signed in" checkbox when you last signed in?<br />
<br />
"I did, because it makes life so much easier. But I also enabled advanced verification methods. It requires me to enter a code and answer questions only I know the answers to, and even have my phone next to me, if I want to make changes to the account. So I'm safe from someone trying to change my password."<br />
<br />
The main problem is that the account is left logged in to. Even if you closed the browser, all the hacker have to do is to try some of the common providers (Google, Microsoft, Yahoo!) and one of them will respond by showing the inbox. Now your world is open to the hacker - have a DropBox account? just go to DropBox and say you forgot your password. A reset link will be sent to your email, and as you remember, the hacker can now read your email.<br />
<br />
"OK, so I'll sign out."<br />
<br />
It's a good thing to do, but you're still partially safe, because someone may always contact your account provider and say someone else hacked into it and try to answer some questions. Sometimes the hacker will get lucky and the provider will reset the password for him.<br />
Besides, that's not the main issue. The main issue is that it shouldn't be easy for someone who stole your computer to see your emails.<br />
<br />
"But it isn't, as my computer is password protected."<br />
<br />
So the hacker just need to copy the content of the disk, by rebooting the computer with a USB storage device.<br />
<br />
"So I'll encrypt the content of my disk. It's a hassle, and not everyone knows how to do it, but I do."<br />
<br />
Great, so copying will not help, but is your computer really password protected? When you open the laptop lid, does it always asks you for password?<br />
<br />
"I do know people where it's not always the case... But it is the case with my machine."<br />
<br />
Did you know it is very easy to change your password by getting administrative privileges by simply rebooting the machine on Linux, and with a little more hassle on Windows? YouTube is full of such demos.<br />
<br />
"So what is there to do?"<br />
<br />
Right now? Not much, except asking the developers of the operating systems and other software with great importance to improve the security. This is what I suggest:<br />
<br />
<br />
<ul>
<li>No need to encrypt the entire disk content. Just encrypt a specific folder that holds applications data, so when someone copies the disk content, this folder becomes useless, and so "just seeing" the online account is impossible.</li>
<li>Asking vendors to use the above folder for storing sensitive data, or encrypting such data on their own, in a way not accessible without the password for someone who copied the disk content.</li>
<li>Not allowing rebooting the machine and gaining administrative access:</li>
<ul>
<li>On Linux (well, actually it's the GRUB boot loader) gaining root access is as simple as choosing it from the menu - no questions asked. This should be changed. They will try to tell you there have been long discussions about that and this is what was decided. But you don't see it anywhere else, so why there? Request gaining root access from GRUB will be password protected by default. Not for you, the IT Professional who can always set it up the way you want, with or without password, but for those who don't know what they are doing, whether they understand it or not.</li>
<li>On Windows there's a loophole in the recovery mode - it allows you to open Notepad by clicking on a link to a log file. Notepad is then run with administrative privileges and allows access to the file system (using the File > Open menu item). There you need to find some program that you can run from the login screen, like the Sticky Keys handler, and replace it with a command prompt, and there you have a command prompt that runs as administrator.</li>
</ul>
</ul>
<div>
These three simple changes (and they are pretty simple) will greatly reduce the chances of someone hacking into your online digital life and stealing your money or worse - your identity.</div>
<div>
<br /></div>
<div>
And another thing to remember, and this is the most important of all: Security is measured by the time it takes a hacker to break into something. It can be your account, it can be a safe at your home or office. Nothing is unbreakable. The idea is to slow the hacker down enough to have time to find out about it and handle the situation. If it's a robber trying to get the content of the safe, then to have enough time to stop him physically, and if it's a hacker trying to change your passwords, than have enough time to block the accounts remotely.</div>
<div>
<br /></div>
<div>
Security can be made very harsh, but it comes to protect the things important for us, and so if it's too harsh we wouldn't use it at all. We must find the delicate point where it protects us to a sufficient level and that we accept the hassle that comes with it.</div>
<div>
<br /></div>
<div>
And last, the common person doesn't really know anything about security, so the operating system must make the best choices by default. Currently Windows is trying but failing, Linux (GRUB) isn't even trying.</div>
<div>
<br /></div>
<div>
<u>Disclaimer:</u></div>
<div>
<ul>
<li>I don't know how other operating systems handling security on those levels, and so I haven't mentioned the MacOS and some others.</li>
<li>When I write about Linux and GRUB, I refer mainly to Ubuntu. I don't know if it is done differently in other distributions.</li>
</ul>
</div>
Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-9895718100957663742012-09-18T12:53:00.000+03:002012-09-18T17:40:04.469+03:00Desiging a website for TV browsing<p>It seems to me that there is a future for TV based web browsing, as more and more TV sets are getting internet connection, more people are starting to use HTPC systems and Media Centers, and even the big companies that provide cable TV start to introduce set-top boxes with internet support.</p>
<p>Even computer and internet companies like Google and Apple create their own TV set-top-boxes Google-TV and Apple-TV.</p>
<p>The only thing left websites. Most websites today are not ready for TV browsing.
Actually, most websites today are not ready for the much wider used smartphone and tablet browsers.</p>
<p>As a website programmer I found out most small to medium size companies just don't want to invest money in such designs, that provide a much different user experience than a regular desktop website. But this is another story to discuss.</p>
<h1>So, who needs a website designed for TV, anyway?</h1>
<p>In my opinion, in the perfect world, all websites would have had a desktop version, a mobile version and a TV version.</p>
<p>Sine the world is less than perfect, and all the designs cost money, it means that only a small portion of the web can build a TV enabled website. This includes:</p>
<ul>
<li>Big companies with a lot of resources.</li>
<li>Companies that could lose potential paying customers (most online shopping platforms).</li>
<li>Websites that have TV related content.</li>
<li>Search engines.</li>
<li>Websites that provide video content.</li>
<li>Blogs and Forums.</li>
</ul>
<p>Each website should have its own unique design for TV browsing, but they all should follow some rules of thumb regarding resolution and scale, font sizes, remote-control based navigation, and text input.</p>
<p>There are some guidelines (not many) available online for the above list, but I'll give my own two cents:</p>
<h2>Resolution</h2>
<p>Most TV screens that have integrated browsers, or that are connected to an HTPC or Media Center of some kind, probably support 1920x1080 resolution, but you can also find other resolutions such as 1366x768 (second most selling TV sets resolution after Full HD) and some other more bizarre resolutions and aspect-ratios such as 1680x1050, 1280x1080, 2560x1080, 852x480, etc.</p>
<p>So there are a lot to design for, but I think designing for the two most common resolutions (1920x1080 and 1366x768) is the best idea, especially when keeping the design flexible for wider screens or more square screens.</p>
<h2>Font Size and Text</h2>
<p>Keep in mind that people are watching their TV from about 3 meters far, corresponding to somewhere between about 20-degree to 40-degree viewing angle. This means (and I'll take a 30-degree angle here for easy computations) 0.0278 degrees per pixel.</p>
<p>Screen text is readable at about 0.5 degrees view angle, which means that the smallest text should be at least 20 pixels high.</p>
<p>Use small text sparingly in the website and only where really needed (for instance - a plot of a TV episode). Prefer much bigger text with as few words as possible on headings, buttons and links, instead.</p>
<h2>Remote Control Navigation</h2>
<p>People who uses TV browsing don't want to hold a keyboard in their hand, and will use a simple remote control most of the time. Design the web site so it fits a remote control navigation. This means, easy to understand and navigate menus, with fewer clicks as possible.</p>
<p>For instance, you can use the Master-Detail approach, where there is a main menu on the left side of the screen (Master), and for each selected item the main area switches to detailed display, or a sub-menu (Detail). If you decide that there are several levels of menus, keep the last level visible and hide the previous levels. But make sure to keep "breadcrumbs" listed above, and make them navigation links.</p>
<p>Another approach, better for long icon-based lists is a grid. Again, keep breadcrumbs visible and navigational, since the grid is hidden and replaced with content whenever an icon is selected.</p>
<p>Use the "Back" button correctly - make it go back one step in the breadcrumbs list.</p>
<p>Remember that remote control navigation is slower than keyboard navigation due to IR transmission times, so make sure to keep each action with the minimum essential clicks.</p>
<h2>Text Input</h2>
<p>Most TV Remote controls don't have the option to input text, but do have the option to input digits, so design the website so if any input is required, prefer input of numerical values. I know this rule will most like only apply for dates, IDs and prices, but if you can only handle with those, the better.</p>
<p>Most sites that need text input can't. So if the TV itself doesn't offer an on-screen keyboard, it's up to the website itself to offer one. Have a button visible next to each text field (it can and should be visible only when the text field is focused) that offers an on-screen keyboard.</p>
<p>Use the local-storage mechanism in HTML5 (or any other mechanism you wish) to keep track of last inputs (in case the TV browser won't do it for you) to save the user from re-entering the text again.</p>
<h1>Technology</h1>
Unfortunately, there is no current standard, not a standard "de-facto" for remote control usage, and each and every TV browser is using it's own system. Currently you can find the <a href="https://developers.google.com/tv/web/docs/implement_for_tv#keyboard">Google TV</a>, <a href="http://wiki.meego.com/TV_Browser_Javascript_API">Meego TV Browser</a>, <a href="http://whitlockjc.github.com/directv-remote-api/">DirecTV web browser</a>, <a href="http://www.samsungdforum.com/upload_files/files/guide/data/html/html_2/javascript/manage_applications/remote_events.html">Samsung TV web browser</a>, <a href="http://pc.zinc.tv/developers/javascript">Zinc</a>, <a href="http://developer.boxee.tv/JavaScript_API">Boxee</a> and some others,
each with API of its own (links refer to the control API).</p>
<p>Plan your website's technology in a way it matches the target audience by the technology they use (you can do a market research for that) or just write (or find) a wrapper for the remote control events such that hides the complexity of figuring out which browser is used and to what events you should register.</p>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-91657307361704691602012-05-18T21:05:00.000+03:002012-05-18T21:06:23.032+03:00Custom Resizable Windows in WPF and WinformsThe following post is relevant for both WPF and Winforms projects, wishing to create custom looking windows that can be dragged and resized from all directions (or specific ones).<br />
We will need to use some native Win32 APIs. So first we need to declare the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950(v=vs.85).aspx">SendMessage</a> function:
<br />
<pre class="brush: csharp">[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
</pre>
We will use that function with the window handle, passing <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645620(v=vs.85).aspx">WM_NCLBUTTONDOWN</a> (0x00A1) as message.
The trick is to pass the correct wParam and lParams so Windows will think we're dragging the window or resizing it through any of it's resizing handles:
<br />
<pre class="brush: csharp">enum WindowHandles
{
HTCAPTION = 2,
HTLEFT = 10,
HTRIGHT = 11,
HTTOP = 12,
HTTOPLEFT = 13,
HTTOPRIGHT = 14,
HTBOTTOM = 15,
HTBOTTOMLEFT = 16,
HTBOTTOMRIGHT = 17
}
</pre>
There are actually more handles, for the client area, close button, minimize and maximize buttons, etc. They are all listed in the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645618(v=vs.85).aspx">WM_NCHITTEST</a> message page on MSDN. I only listed the handles relevant to our case.<br />
We will be tricking Windows by simulating a mouse down event on a specific drag-handle. But since we know that the drag starts by listening to mouse-down even, we first need to tell Windows that the mouse button is not down anymore. To do this we will also need the ReleaseCapture function:
<br />
<pre class="brush: csharp">[DllImport("User32.dll")]
public static extern bool ReleaseCapture();
</pre>
Now all there's left to do is to call the SendMessage the mouse button is down for each of our custom drag-handles with the native window handle (HWnd):
<br />
<pre class="brush: csharp">const int WM_NCLBUTTONDOWN = 0x00A1;
void RegisterCustomBorderEvents()
{
//...
// do similar things for all borders and for the caption.
LeftBorder.MouseDown += OnLeftBorderMouseDown;
//...
}
void OnLeftBorderMouseDown (object sender, EventArgs e)
{
ReleaseCapture();
SendMessage(windowHandle, WM_NCLBUTTONDOWN, (uint)WindowHandles.HTLeft, 0);
}
</pre>
<h1>
WPF Notes</h1>
In WPF you will need to use the interop API in order to get the window handle:
<br />
<pre class="brush: csharp"><br />IntPtr windowHandle = new WindowInteropHelper(myWindow).Handle;<br />
</pre>
Where <code>myWindow</code> is the window you want to drag. If you implement this in the window code behind, just pass <code>this</code>.
<br />
<br />
Also in WPF there are built in methods in the Window level for dragging the window (<a href="http://msdn.microsoft.com/en-us/library/system.windows.window.dragmove.aspx">DragMove</a>) and in the UIElement level for releasing the mouse capture (<a href="http://msdn.microsoft.com/en-us/library/system.windows.uielement.releasemousecapture.aspx">ReleaseMouseCapture</a>). You may use them instead of the PInvoke versions where possible.Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-57457544197857658452011-06-11T10:18:00.011+03:002012-09-18T13:07:24.438+03:00Web DevelopmentI recently started developing applications for the Chrome browser. This is as simple as developing any other web application, except I had no experience developing web application before.<br />
<br />
<b>In this post I will share my impressions of web development and finally share my ideas of next generation web development.</b><br />
<br />
I had to learn JavaScript to a level that would allow me to write complex, object-oriented pieces of code. I didn't really bother with HTML5 and CSS3 - whenever I needed something I could easily find it somewhere on the web (mostly in <a href="http://draft.blogger.com/www.w3schools.com">www.w3schools.com</a>). But scripting is different. You can't just not remember the basics, so I had to learn it on the go.<br />
<br />
My impressions of JavaScript is that it is not as good as most compiled languages (like C, C++, C# and even Java). It is not type-safe, and it's object-oriented syntax is horrifying. In addition it lacks data structures like lists and hashtables (or dictionaries), so you need to use alternatives.<br />
<a name='more'></a>By alternatives I don't mean creating your own data structures. You can achieve a mapping between a key to a value using an Object: add a member and give it the value. JSON is all about that... Except JSON comes to represent an object, not a list.<br />
<br />
And there is no such thing as a Class. There are only Functions. You want some function to behave as a class? Add sub-functions. You want to be able to override functions in an inherited "class"? Add prototype-level function.<br />
<br />
It's not that you can't get used to it. Well actually you can't, but still you write it automatically after a while. What I want to say is that there are so many options to write object oriented code even in scripted languages (see Ruby, for instance) that the way JavaScript is designed is simple horrible (especially with a name that suggests some relation to Java)<br />
<br />
Everybody's talking about web development as the next thing. All big software companies push HTML5, CSS3 and JavaScript, each company with its own unique reasons. Microsoft even said writing applets and gadgets to Windows 8 would be in JavaScript (they said that it is much lighter. I don't see how ANY script can be lighter than a compiled code).<br />
<br />
I understand the hype. I also starting to realize that web applications is the way to go for most of everyday's uses. But why JavaScript? or any other type-unsafe script for that matter? There are many applications written in Flash. While this is an improvement for the user who downloads compiled code, Flash was originally designed for web vector animation clips, so writing applications in it is really abusing it. Could be done much easier with, say, Silverlight (and C# is a much saner choice over ActionScript, which, AFAIK, is very similar to JavaScript).<br />
<br />
Why wouldn't new browsers support precompiled code that can access DOM elements? suppose I could write in C# some code that interacts with elements in a webpage, compile it to a DLL, and link to that DLL from an HTML file. Don't worry about security issues now, those can be taken care of in a variety of ways. Think of the result - faster download times, you don't get it as plain, readable text (I know most scripts are scrambled and their variables are shortened so it's not really readable, and I know you can easily decompile a .Net DLL into readable text), and the most important thing - the browser doesn't need to compile the script on the fly. It is ready to go!<br />
<br />
Thinking about it some more - there should be a way to compile an entire webpage. But for now perhaps the best way it to compact it (along with its resources) in a zip file (much like new document formats are doing today).<br />
<br />
To sum things up - from a developer point of view, moving to web applications is welcome, but browsers need to support nicer scripts, and perhaps even precompiled DLLs that can access DOM elements.Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com4tag:blogger.com,1999:blog-3029714609596082708.post-48844833631954005662011-06-10T09:00:00.163+03:002012-09-18T13:08:05.198+03:00Thinking of moving to LinuxWell this thought has been around for a very long time now.<br />
I started to learn to work with Linux a long while ago, in my first professional job. Then was also the time I got to know the world of open source software.<br />
I've been following the development in the Linux world, and every now and then downloaded the latest ISO of some distributions for a test drive. In the end I never gave up Windows. I felt that Linux just could not give me all the tools I need for my everyday tasks.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"></div><br />
<div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-r_vdkHdgAUY/TfHmd1WE8xI/AAAAAAAABqA/lZmN5AbY-wA/s1600/xbmc.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://1.bp.blogspot.com/-r_vdkHdgAUY/TfHmd1WE8xI/AAAAAAAABqA/lZmN5AbY-wA/s1600/xbmc.png" /></a></div>When I started using a Media Center in the living room, I chose <b><a href="http://xbmc.org/">XBMC</a> </b>over Ubuntu Linux. It did a pretty good job and was enough for what I needed.<br />
<br />
<div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-6kMTre7k_30/TfHmQwWCmhI/AAAAAAAABp8/0LcHNQFLJzs/s1600/ubuntu.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://1.bp.blogspot.com/-6kMTre7k_30/TfHmQwWCmhI/AAAAAAAABp8/0LcHNQFLJzs/s1600/ubuntu.png" /></a></div>The <b><a href="http://www.ubuntu.com/">Ubuntu</a> </b>distribution was a good Linux choice for a long time, but only now, in version 11.04 it feels like there is nothing I want to do with it and can't.<br />
<br />
I always prefer open source software over closed source software and commercial software, with the exception of my Home Windows (Vista 64) which I bought with me PC almost 4 years ago, and Office 2007 Home and Student that I bought for my girlfriend while she was a student (in a great student discount).<br />
Every now and then I review all of the installed programs I have and see which have a Linux version of a descent Linux alternative.<br />
<a name='more'></a><br />
Currently, most of my program have a Linux version and the rest have Linux alternatives:<br />
<ul><li>Image Manipulation:</li>
<div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/-b9_e3Zw9adQ/TfHmwZapiWI/AAAAAAAABqE/yE2xDtq24jA/s1600/gimp.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://1.bp.blogspot.com/-b9_e3Zw9adQ/TfHmwZapiWI/AAAAAAAABqE/yE2xDtq24jA/s1600/gimp.png" /></a></div><ul><li><b><a href="http://www.gimp.org/">Gimp </a></b>- originally a native Linux program that was ported to Windows.</li>
<li><a href="http://www.getpaint.net/"><b>Paint.net</b></a> - might run under <b><a href="http://www.mono-project.com/Main_Page">Mono</a></b>, and if not there is <b><a href="http://pinta-project.com/">Pinta</a></b>.</li>
</ul><li>Vector Editing:</li>
<ul><li><b><a href="http://inkscape.org/">Inkscape</a> </b>- originally a native Linux program that was ported to Windows.</li>
</ul><li>Internet:</li>
<ul><div style="float: right;"><img border="0" src="http://4.bp.blogspot.com/-lYQdi5VhzzE/ThoCIGY3-HI/AAAAAAAABsM/bMhCzlHo2cw/s1600/filezilla.png" /><img border="0" src="http://2.bp.blogspot.com/-p0e4ZHz6pKA/TfHlf5Ghx6I/AAAAAAAABp4/ee5j7MMhsN4/s1600/firefox.png" /><img border="0" src="http://2.bp.blogspot.com/-QElVw6U2zdU/TfHlfRzXeAI/AAAAAAAABp0/RV4S5pT_pTw/s1600/chrome.png" /></div><li><b><a href="http://www.google.com/chrome/intl/en/make/download.html?brand=CHKZ&platform=linux">Chrome</a></b></li>
<li><b><a href="http://www.mozilla.com/en-US/firefox/new/">Firefox</a></b></li>
<li><b><a href="http://jdownloader.org/">JDownloader</a></b></li>
<li>Plenty of Bittorernt clients</li>
<li>FTP Client - <a href="http://filezilla-project.org/">FileZilla</a></li>
</ul><li>Programming:</li>
<ul><a href="http://3.bp.blogspot.com/-kqEiK6h0I2o/TfHq31LMmgI/AAAAAAAABqs/Opd_UMz1ljM/s1600/monodevelop.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://3.bp.blogspot.com/-kqEiK6h0I2o/TfHq31LMmgI/AAAAAAAABqs/Opd_UMz1ljM/s1600/monodevelop.png" /></a>
<li>I'm developing mostly in C#, so <b><a href="http://monodevelop.com/">MonoDevelop</a> </b>is my native choice. Used it quite a lot a long time ago. In my current job I'm using Visual Studio. While Mono and MonoDevelop lacks the features of WPF development, I don't think I'll be doing any WPF development at home. I'll try to focus on Internet related development.</li>
</ul><li>Source Control:</li>
<ul><li><b><a href="http://subversion.tigris.org/">Subversion</a></b></li>
<li><b><a href="http://git-scm.com/">GIT</a></b></li>
</ul><li>Media Players:</li>
<div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-qeol8VqnD1w/TfHpzyeVEXI/AAAAAAAABqk/xSh-a72Q4T0/s1600/banshee.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://3.bp.blogspot.com/-qeol8VqnD1w/TfHpzyeVEXI/AAAAAAAABqk/xSh-a72Q4T0/s1600/banshee.png" /></a></div><ul><li><b><a href="http://banshee.fm/">Banshee</a> </b>- while there is a Windows version now, I never tried it. But it works fine on Linux.</li>
<li><b><a href="http://projects.gnome.org/totem/">Totem</a> </b>- another media player for Linux.</li>
</ul><li>Text Editing:</li>
<ul><li>I'm using notepad++ on Windows. There are plenty of alternatives on Linux. This is also my main development tool for Internet scripts (JS, HTML, PHP...)</li>
</ul><li>Office Suites:</li>
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-FnRw6-m9HfM/TfHqCdF4e-I/AAAAAAAABqo/tOZ26oLIcNo/s1600/libreoffice.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://2.bp.blogspot.com/-FnRw6-m9HfM/TfHqCdF4e-I/AAAAAAAABqo/tOZ26oLIcNo/s1600/libreoffice.png" /></a></div><ul><li>No real replacement for MS Office, but then again, I'm rarely using it. I'm using Google Docs to write most documents. If I really need an office suite, <b><a href="http://www.libreoffice.org/">Libre Office</a></b> (a sane fork of Open Office) is available.</li>
</ul><li>Video Editing: (I didn't edit video clips for a long while now, but want to make sure it is possible)</li>
<ul><li><b><a href="http://www.kdenlive.org/">Kdenlive</a> </b>- seems to have all the features one possibly wants.</li>
<li><b><a href="http://cinelerra.org/">Cinelerra</a> </b>- a more professional video editing software, in case Kdenlive won't suffice.</li>
</ul><li>3D Modeling and Animation:</li>
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-HBSSrSGCxpg/TfHokrZkXeI/AAAAAAAABqc/LUSkhri95BY/s1600/blender.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://2.bp.blogspot.com/-HBSSrSGCxpg/TfHokrZkXeI/AAAAAAAABqc/LUSkhri95BY/s1600/blender.png" /></a></div><ul><li>This is a sensitive issue. No free software that even compares to 3D Studio Max. I've started using Google Sketchup lately, but no Linux version for that either. There is <b><a href="http://www.blender.org/">Blender</a></b>, which I've tried using several times, but it lacks the native, streaming UI that 3DSMax and Sketchup have (Although the latest version does present an improvement). There are some other alternatives but not as strong, and not as easy to use. I can always run Skethup with Wine, or start a new open source project that will mimic 3DSMax experience :-)</li>
</ul><div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-Lp9W-T17S60/TfHo23u2_lI/AAAAAAAABqg/3CSAHTica-g/s1600/sweethome3d.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://3.bp.blogspot.com/-Lp9W-T17S60/TfHo23u2_lI/AAAAAAAABqg/3CSAHTica-g/s1600/sweethome3d.png" /></a></div><ul><li><b><a href="http://www.sweethome3d.com/">Sweet Home 3D</a></b> - I was using it to plan my apartment. Written in Java it have a Linux version and also an online-in-browser version.</li>
<li><b><a href="http://www.google.com/earth/">Google Earth</a></b></li>
</ul><li>CAD</li>
<ul><li>In the 3D CAD area there is almost nothing, as the market leaders AutoCAD and SolidWorks are for Windows only. Yet I was able to find <a href="http://varicad.com/">VariCAD</a> that claims to have a Linux version and seems powerful. Never tried it, though, as the prices are quite high.</li>
<li><a href="http://www.linuxcad.com/">LinuxCAD</a> also promises to be AutoCAD compatible, but I just can't understand anything from their website and I actually had to search (using Ctrl+F) for the download link. </li>
<li><a href="http://www.opencascade.org/">Open CASCADE</a> is a free, open source and cross platform CAD software that focuses on mathematical models, and allows you among other things to test the strength of structures.</li>
<li>In the 2D CAD area there are several options, such as <a href="http://www.ribbonsoft.com/qcad.html">QCAD</a>.</li>
</ul><li>Audio Editing:</li>
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/-e3ARVYnLydE/TfHnEpGeYTI/AAAAAAAABqI/Y-423-EcjPc/s1600/audacity.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://2.bp.blogspot.com/-e3ARVYnLydE/TfHnEpGeYTI/AAAAAAAABqI/Y-423-EcjPc/s1600/audacity.png" /></a></div><ul><li><b><a href="http://audacity.sourceforge.net/">Audacity</a> </b>- when ever I needed to record or edit audio this have been my natural choice.</li>
</ul><li>Antivirus:</li>
<ul><li><b><a href="http://free.avg.com/us-en/homepage">AVG</a> </b>- it seems that they have a <a href="http://free.avg.com/us-en/download.prd-alf.tpl-mcr8">Linux version</a> too.</li>
</ul><li>Backup:</li>
<div class="separator" style="clear: both; text-align: center;"><a href="http://3.bp.blogspot.com/-xzwcTFNGjSA/TfHnVP_2MGI/AAAAAAAABqM/HFv5NdREeBg/s1600/crashplan.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://3.bp.blogspot.com/-xzwcTFNGjSA/TfHnVP_2MGI/AAAAAAAABqM/HFv5NdREeBg/s1600/crashplan.png" /></a></div><ul><li>I switch from <b><a href="http://mozy.com/">Mozy</a> </b>to <b><a href="http://www.crashplan.com/">CrashPlan</a> </b>due to Mozy's new pricing and service terms. Anyway, both have a Linux version.</li>
</ul><li>Ability to Fallback:</li>
<ul><a href="http://1.bp.blogspot.com/-ER6uzD5_Rxo/TfHoBNnzfQI/AAAAAAAABqU/vML1_vOiPq4/s1600/winehq.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://1.bp.blogspot.com/-ER6uzD5_Rxo/TfHoBNnzfQI/AAAAAAAABqU/vML1_vOiPq4/s1600/winehq.png" /></a>
<li><b><a href="http://www.winehq.org/">Wine</a> </b>- allows installing and running native Windows applications. Works quite well too, and with its graphics acceleration support (DirectX implemented over OpenGL, I believe) it can also run games.</li>
</ul><ul><a href="http://4.bp.blogspot.com/-Fe63hGGkydc/TfHnq2PraPI/AAAAAAAABqQ/PPyKMnPl15I/s1600/virtualbox.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://4.bp.blogspot.com/-Fe63hGGkydc/TfHnq2PraPI/AAAAAAAABqQ/PPyKMnPl15I/s1600/virtualbox.png" /></a>
<li><b><a href="http://www.virtualbox.org/">VirtualBox</a> </b>- currently I'm using VirtualBox on Windows to run Linux environments. This can also be done the other way...</li>
</ul><ul><a href="http://3.bp.blogspot.com/-XK9g_IPUmaA/TfHoOJfDYVI/AAAAAAAABqY/Bnv1-6Wrm0I/s1600/rdesktop.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="http://3.bp.blogspot.com/-XK9g_IPUmaA/TfHoOJfDYVI/AAAAAAAABqY/Bnv1-6Wrm0I/s1600/rdesktop.png" /></a>
<li><b><a href="http://www.rdesktop.org/">RDesktop</a> </b>- seems like the most used program that allows connecting to a Windows machine using the Remote Desktop feature from Linux. Good to know it is possible.</li>
<li><b><a href="http://sourceforge.net/projects/gnome-rdp/">GnomeRDP</a> </b>- another program that suppose to allow remote desktop connection to Windows. Could not find any screen shots that proves it, though.</li>
</ul></ul><div><div class="separator" style="clear: both; text-align: center;"><br />
</div>With such a long list, I think my switch is closer than ever :-)</div><br />
<script type="text/javascript">
slashdot_url="http://itaibh.blogspot.com/2011/06/thinking-of-moving-to-linux.html";
</script><br />
<script src="http://slashdot.org/slashdot-it.js" type="text/javascript"></script>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com2tag:blogger.com,1999:blog-3029714609596082708.post-56555411527019187512011-06-06T08:30:00.003+03:002011-06-07T07:57:35.889+03:00Mozy’s underhanded opportunismI’m using Mozy as a backup service.<br /><br />To be more precise, I was using Mozy for a year before they raised their prices and downgraded their service. Except I’m still using it now even that I don’t want to.<br /><br />You see, Mozy has two renewal plans on their site once you paid. One – keep with the same plan you’ve paid for (or in my case – pay more and get less). Two – upgraded plan (still gives me less than what I originally signed) that gives you extra storage (I originally signed for unlimited. How it became limited is beyond me).<br /><br />Note that the is no “Three – no renewal”. There’s just no such thing. You don’t want to continue? That’s fine. You have the option to CANCEL your account (no refund,AFAIK).<br /><br />What happened the other day was that I got this email:<br /><blockquote>Thanks for using MozyHome!<br /><br />Your credit card ending in **** was charged $65.89 today for a yearly subscription to MozyHome 50 GB.<br />Your card will be automatically charged again on July 04, 2012 in order to keep your MozyHome 50 GB subscription current.<br /><br />Please visit your account page at <a avglsprocessed="1" href="https://mozy.com/login" target="_blank">https://mozy.com/login</a> to make changes to your MozyHome 50 GB subscription.<br /><br />Thank you!<br /><br />- The MozyHome Team</blockquote><br />You see, not only they never notified me that my subscription is about to end, and never gave me the option not to renew it, they simply took my money without my permission.<br /><br />When I opened a support call regarding that issue, this was the response:<br /><blockquote>When you signed up for service, the plan requires an auto renewal for the plan. ! After you sign up, we will automatically re-bill your credit card every year in order to keep your subscription current, unless you cancel.<br /><br />The only way to un-enroll is to cancel the account. If you wish to cancel your account I have provided step by step instructions to cancel [...clipped...]</blockquote><br />Please do yourself a favor and keep away from Mozy as you would from fire. I was burnt already.Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-67143770851535369522011-02-01T21:45:00.005+02:002011-06-10T16:48:14.112+03:00Performance – My biggest success so far<p>In my <a href="http://itaibh.blogspot.com/2011/02/performance-using-net-and-com.html">last post</a> I shared the story of improving performance while using .Net and COM.</p><p>While improving from a few minutes to a few seconds seems like a great success (if counting such great times ratios*), I haven’t yet beat myself.<br />
The greatest time I’ve improved was from several <strong>hours</strong> to a few seconds.</p><h2>Background</h2><p>In my first workplace there was a C4I application that showed a vector map. No standards where used as it was first develop 15 years ago, before any standards have evolved. In order for the map to run efficiently, its data was split into tiles. First the tiles in view were presented, and then, in background, the other tiles were loaded.</p><p>I want to talk about the tool that cut the one big map into tiles.<br />
That tool was given a map, number of tiles along and across, output folder and several hours to run.</p><a name='more'></a><br />
<h2>The Problem</h2><p>It was only used when the map was replaced, which was very rare, so no one took the time to improve it. However, this had changed, and I hated waiting those hours.<br />
I looked at the code and found it was going in a simple XY loop over the map, slicing a tile at a time, saving it to a file. For every dead tile with nothing in it, it had to go over all the vector data in the map and testing it against the four walls of the tile.</p><h2>The Solution</h2><p>I decided to replace that mechanism with a smarter one. I figured that instead of running over all the data for every tile, I would slice the data recursively, leaving less and less work for next rounds until we get to a single tile size, and then store this tile to disk.</p><p>What do you know – it worked! <img alt="Smile" class="wlEmoticon wlEmoticon-smile" src="http://lh4.ggpht.com/_skWDg2sd0Zc/TUhi8KWnYDI/AAAAAAAABmg/tJL9b7e1k0I/wlEmoticon-smile%5B2%5D.png?imgmax=800" style="border-bottom-style: none; border-left-style: none; border-right-style: none; border-top-style: none;" /> Only a few seconds after years of waiting for hours, leaving the tool running during launch or at night, hoping no mistake was made, and that no power loss will destroy the chance for result.</p><h2>Conclusion</h2><p>This story shows that sometimes a replacement of the wrapping algorithm (in this case – from a simple XY loop to a bit more complicated recursion) is enough to gain major results.</p><h3>*endnote</h3><p>Optimizing code should be about reducing a method runtime from milliseconds to microseconds. Not from hours and minutes to seconds. If something takes that long, obviously something is very wrong with it that must be taken care of right away. Acceptable initial runtimes is the basis for real optimization.</p>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com4tag:blogger.com,1999:blog-3029714609596082708.post-38611169628315393262011-02-01T21:10:00.003+02:002011-06-10T16:48:50.213+03:00Performance - Using .Net and COM<p>Yesterday I was given a task to help improve the performance of a feature. I was told that the feature was written in a very straight forward way, nearly no optimizations taken. The problem was that it took several minutes (yes, minutes) to run, rather than a few seconds or better than that.</p><p>The story is quite long, so if you have time and patience read its whole. If not or you are just too lazy, skip to the summary at the end <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://lh6.ggpht.com/_skWDg2sd0Zc/TUhauPfpQgI/AAAAAAAABmc/7zCJ2juunLQ/wlEmoticon-smile%5B2%5D.png?imgmax=800" /></p><a name='more'></a><br />
<h2>Identifying The Problem</h2><p>The code computed visible area from a given geographic point and <a href="http://en.wikipedia.org/wiki/Digital_terrain_model">DTM</a>. The <a href="http://en.wikipedia.org/wiki/GIS">GIS</a> package used was the one of <a href="http://www.esri.com">ESRI</a>. While ESRI tools must have that feature hidden somewhere, for several reasons, including performance, it was not used. However, the result - performance wise – was no better.</p><p>Using <a href="http://technet.microsoft.com/en-us/sysinternals/default.aspx">Sysinternals Suite</a> <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653">ProcExp</a> I wanted to see just how much CPU the process is using. I saw that the process was using a total of about 70%. That’s a lot, but the interesting part was that about half of it was actually <strong>Kernel Time</strong>. This usually means a lot of IO.</p><p>So I launched <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645">ProcMon</a> to see what happens during the progress. It seemed that for every height sample of the DTM in a given coordinate, the ESRI package accessed the actual DTM file (DTM GeoTiff in that case). </p><h2>Solving The Problem – Phase 1</h2><p>I looked deep into the ESRI API to figure out how to prevent that from happening. Since I couldn’t find any descent way of getting ESRI to do it for me, I just used another ESRI API that reads all the data to the memory. While this requires me to build a big memory manager (I didn’t, by the way, just loaded everything to memory. The files are currently small enough to fit. But I’ll get to it…) it is better than accessing the disk for every request.</p><p>Joyful and happy that I’ve eliminated the constant file access, I ran the program again. A very minor improvement was shown, and still - too much kernel time.</p><h2>Solving The Problem – Phase 2</h2><p>Taking another look on ProcMon, showed a lot of registry access. By asking around (well, asking my supervisor…) I was told that this is due to COM object access. “Strange”, I thought, “I thought I got rid of all COM objects access…”</p><p>So the next step was to really get rid of all COM object access during that process. I tracked down several points that it was easy – the value never changes, so just put it in a primitive type member and we’re done. The hard part was to replace the calls to methods that computed something. However, those computations weren’t so hard to do after all. The converted map coordinates to pixel location value in the DTM. Using some linear algebra at its lowest level gave me a satisfying result. Now the program takes seconds instead of minutes.</p><h2>To sum things up:</h2><ul><li>If using COM objects, try to minimize or even eliminate calls to them when doing something that requires performance, especially if in a tight loop. </li>
<li>Don’t be afraid to “re-invent the wheel” if your current package is too slow. Either find a faster package, or write simple tasks yourself. </li>
<li>After doing this, make sure the results are satisfactory. Not only performance wise, but also in value. You don’t want to screw things up just to gain more speed. </li>
</ul><p>And in a more general note – improving performance (also true for efficiency) is all about getting the same effect with less work. In this case (and most of the other cases you would bump into), this can be done by a couple of simple replacements of one CPU killer method with another one, less costly. Only rarely the entire algorithm would need to be replaced. Knowing the common pitfalls (or hogs) is a good place to start. </p><p>Happy optimizing! <img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://lh6.ggpht.com/_skWDg2sd0Zc/TUhauPfpQgI/AAAAAAAABmc/7zCJ2juunLQ/wlEmoticon-smile%5B2%5D.png?imgmax=800" /></p>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-64067093441316273522010-03-04T23:22:00.001+02:002012-09-18T13:08:12.974+03:00Year 2048<p>In just less than 38 years from now, year 2048. I’ll be 65 years old. The world will be filled with slogans like “The real Y2K” spread by techies.</p> <p>This wasn’t possible on Y1K. Actually, it only became possible in the last several decades. A century, if considering some really old inventions.</p> <p>I said “the world will be filled with slogans”, because I’m not sure that saying “the internet will be filled with slogans” will be correct. The internet had evolved a lot in the last decade. From slow dial-up (yes, it was like that in late 90’s and early 2000) to 100mib constant connection, from home PCs to our cellular phones and PDAs. From simple websites with slowly loading GIFs, line by line, to advanced, interactive sites, filled with animation and streaming video.</p> <p>This all made me think what it would all look like in 38 years. I sometimes feel that when looking ahead in the short term, to the next year or two, it is very hard to think that great revolutions might occur. Thinking of bureaucracy of different authorities, things always seem to get delayed. But in the long term, things does happen very fast indeed. Dazzling fast.</p> <p>I know there are people working on shaping the next generation of the internet. I just wonder how far we can really imagine in such an exponential world.</p> Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-40979212199187953832009-12-17T01:24:00.005+02:002012-11-17T11:11:18.720+02:00XAML exporter for Sketchup - Round 2I just finished fixing some issues with the Google Sketchup Xaml Exporter.<br />
The updated file can be downloaded here:<br />
<br />
<span class="Apple-style-span" style="color: #0000ee;"><u><a href="https://docs.google.com/leaf?id=0BxinGAr39Pd0ODQ2Y2IyZDUtZWNkYi00YTU2LTk3MmMtNDg4NmMzZDhlZjVh&hl=en">https://docs.google.com/leaf?id=0BxinGAr39Pd0ODQ2Y2IyZDUtZWNkYi00YTU2LTk3MmMtNDg4NmMzZDhlZjVh&hl=en</a></u></span><br />
<span style="color: #551a8b;"><span class="Apple-style-span" style="text-decoration: underline;"><br />
</span></span>The new version fixes:<br />
<ul><li>Different materials with the same base texture filename caused only one texture file to be created, thus wrong texture to appear.</li>
<li>Group transformations were ignored.</li>
<li>Back facing materials now supported.</li>
</ul><div><br />
</div><div>Enjoy!<br />
<br />
<br />
<b>UPDATE</b>:<br />
I re-uploaded the file, this time under a bit different name. It seems that Vista shows me one version of the file, and even loads it correctly, while it shows a totally different file to the world.<br />
I was told that the file I uploaded is not the correct file, and when checking locally, I saw that the size is really different. Strange, even rebooting didn't help. Oh well, saving as (and even copying!) to another local folder solved it, but I still don't understand why it happened.</div>
<br/><br/>
<a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://itaibh.blogspot.co.il/2009/09/google-sketchup-xaml-exporter.html"></a>
<noscript><a href="http://flattr.com/thing/998874/Google-Sketchup-XAML-Exporter" target="_blank">
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com7tag:blogger.com,1999:blog-3029714609596082708.post-3367857356859037872009-09-27T16:07:00.006+02:002012-11-17T11:10:41.936+02:00Google SketchUp Xaml exporterI wanted to build a WPF 3D application, that will present models. I didn't want to include code that loads different formats and creates WPF models at runtime, and I wanted an easy-to-use, free modeler.<br /><a href="http://www.blender.org/">Blender</a> is free, but I find it very cumbersome. <a href="http://sketchup.google.com/">Google SketchUp</a> is very easy to use, but was lacking a way to export to XAML.<br />Fortunately, SketchUp has a very easy-to-use <a href="http://www.ruby-lang.org/en/">Ruby</a> <a href="http://code.google.com/apis/sketchup/">API</a> that I could use to build an exporter.<br />It currently exports the meshes separated by materials, and grouped together in geometry groups according to the same hierarchy structure of the model. Materials include front faces only (i.e. no BackMaterials) and support solid color and textures. If no material is given, a solid white material is used.<br />While it's not perfect, it does a pretty good job. Feel free to use and please send feedback,<br /><a href="http://cid-8fbcae0caa96d592.skydrive.live.com/self.aspx/.Public/xamlExporter.rb">http://cid-8fbcae0caa96d592.skydrive.live.com/self.aspx/.Public/xamlExporter.rb</a><br /><br /><b>UPDATE:</b><br />I updated the plugin. Check out the follow-up post: <a href="http://itaibh.blogspot.com/2009/12/xaml-exporter-for-sketchup-round-2.html">XAML exporter for Sketchup - Round 2</a>.<br/><br/>
<a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://itaibh.blogspot.co.il/2009/09/google-sketchup-xaml-exporter.html"></a>
<noscript><a href="http://flattr.com/thing/998874/Google-Sketchup-XAML-Exporter" target="_blank">
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com14tag:blogger.com,1999:blog-3029714609596082708.post-74334329655526505762009-08-07T12:19:00.006+03:002011-06-10T16:10:36.391+03:00Writing Quality Software - CodeCoding is bringing the architecture and design to life. Making the idea work. Correct coding is more than just writing code that runs and do what it supposed to do. Correct coding is about making sure the architectural principles are applied, the code is readable and maintainable, self explanatory and self debuggable. Keep in mind that code is meant to be read much more than it is meant to be written.<br /><h2>Debuggable Code</h2>What exactly is “debuggable code”? Well, I would say a debuggable code is a code that helps you find where the errors are as you run into them. This can be done by:<br /><ul><li>Emitting enough logs where applicable. </li><li>Not “swallowing” exceptions. </li><li>Placing a method result in a local variable and returning it, rather than return a computation. </li><li>Preferring a full if/else when needed for populating a variable over the shorter form of x?a:b. </li><li>Breaking lines between different statements, such as <br /><code>if (something) return;</code> <br />which is not debuggable, since you can’t place a breakpoint on the ‘return’. </li></ul>Generally, if you try to debug a section in your code and think it is too hard to debug because the debugger is not enough feature rich, think again how you can change your code to fit the debugger limitations.<br /><h2>Correct Casting</h2><a href="http://themonkeysgrinder.blogspot.com/">Scott Peterson</a> posted <a href="http://themonkeysgrinder.blogspot.com/2009/07/casting-call.html">this post</a> about casting best practices. There are several things I would like to add upon.<br />First, when you expect a specific object type, prefer static cast, even in the case of a publicly visible method. The reason is that you would like the CLR to check the type for you and throw the relevant exception. Why? The alternative is you doing it yourself and responding correctly. Most people would simply “swallow” that error, which will yield bizarre errors elsewhere (most common ones are a null reference exception much deeper in the code, and it would be a very tedious work figuring out what went wrong).<br /><h2>Readable Code</h2>For each project, select a standard and stick with it. Keep in mind that in some cases you might need to read the code you’ve written outside the IDE. This means you won’t have all the cool features like tooltips specifying a member type, go to member, find member references, etc. You want to write code that will be easier to understand without jumping up and down the file.<br />While it sounds like the <a href="http://en.wikipedia.org/wiki/Hungarian_notation">Hungarian Notation</a> might sound like a good idea (you can know the type and scope just by looking at the member name), it is a very unreadable notation. I like the naming that adds “m_” and “s_” prefixes to class members and static members respectively, but I hate the addition of “p_” prefix to parameters as I’ve seen in several places. So basically, it is all about readability. Whatever you choose, make sure it is easy to read outside an IDE (using notepad is a good test case), and stick with it.<br />Another aspect of readable code relates to indentation. Indentation is not an option, my friends. It’s a must, and its better be done right. Select your favorite method of indentation (most common methods include 4 characters wide, 8 characters wide and “smart”), and make sure all indentations are using the same method (spaces or tabs). I personally believe that spaces are the best way to go (along with <a href="http://en.wikipedia.org/wiki/Monospaced_font">monospaced font</a>), since the overall code “design” is kept in all editors. <a href="http://blogs.microsoft.co.il/blogs/liran_chen/">Liran Chen</a> has a <a href="http://beta.blogs.microsoft.co.il/blogs/liran_chen/archive/2009/08/01/wonders-with-visible-white-space.aspx">post</a> about an indentation issue in Visual Studio (in Hebrew).<br /><h2>Spelling</h2>Don’t underestimate correct spelling. And prefer English in your code and comments over any other language. This will be used as a standard that will ease the process of joining new developers to the project. Minimize the use abbreviations and slang. It doesn’t come out nice, and tend to look unprofessional. <br /><br />These are my two cents of how to write better code, and there’s much more to write on that subject. Maybe in one of my next posts.<br /><br /><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f07%2fwriting-quality-software-code.html"><img alt="kick it on DotNetKicks.com" border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f07%2fwriting-quality-software-code.html" /></a><br /><br /><h1>Update</h1><br />Just found this post regarding programming:<br /><br /><a href="http://sites.google.com/site/yacoset/Home/signs-that-you-re-a-bad-programmer">http://sites.google.com/site/yacoset/Home/signs-that-you-re-a-bad-programmer</a><br /><br />I find it true, helpful and funny.Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com1tag:blogger.com,1999:blog-3029714609596082708.post-85821520774674538082009-08-05T19:07:00.001+03:002009-08-05T19:07:44.285+03:00Installation Cancelled<p><a href="http://lh3.ggpht.com/_skWDg2sd0Zc/SnmuRBflxsI/AAAAAAAABgg/ZHdilT0wk5k/s1600-h/installation%20canceled%5B6%5D.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="installation canceled" border="0" alt="installation canceled" src="http://lh6.ggpht.com/_skWDg2sd0Zc/SnmuTVyPXaI/AAAAAAAABgk/8TY0Gs-g9yY/installation%20canceled_thumb%5B4%5D.png?imgmax=800" width="396" height="306" /></a> </p> <p>The image speaks for itself.</p> Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com2tag:blogger.com,1999:blog-3029714609596082708.post-83998853718337099492009-07-26T23:09:00.006+03:002018-02-12T21:06:22.597+02:00Writing Quality Software – Quality AssuranceOne must not underestimate the necessity of the QA team.<br />
Quality Assurance (QA), the guys that test the software designed by the engineers and written by the developers. Their mission is to make sure that the software does what it needs to do, and do it well. They are also the first users of the software so they have the best review and criticism about the visual design and usability.<br />
A developer needs to learn to listen to the QA team notes. The QA team, on the other hand, must learn how to note.<br />
In order to really understand this, lets check things more thoroughly:<br />
First of all, the role of the QA team versus the role of the development team in terms of <strong>software operability</strong>:<br />
No QA team – Bad software; No development team – No software.<br />
That said, we now need understand that the two teams must <strong>work together</strong> in order to create <strong>good software</strong>.<br />
<a name='more'></a>Alas, those two teams are meant to work as rivals, as the QA must constantly critic the products of the developers, in order to find flaws, and the developers must fix the flaws and prevent new flaws from being introduced.<br />
This is a real fight between the two teams, and not once you hear both sides places the blame on the other doing a bad job, wasting everybody else’s time, etc. While this is not true, this is often the feeling, especially if the organization isn’t done right.<br />
So, how can the two teams work together?<br />
First, developers tend to fix problems presented to them when these are clear enough, and reject or ignore them when these are unclear. Also, a repeated claim, especially if not clear enough, rejects the average developer even more.<br />
This is why a tester must learn how to file a bug report. This is the key to good tester-developer relationship.<br />
A bug report must contain a very clear, short as possible list of steps that reproduce a bug. <strong>THE BUG MUST BE REPRODUCABLE UNDER ANY TERMS.</strong> This means that a bug that could not be reproduced, actually does not exist.<br />
Reproducing a bug is an art by itself. Finding the minimal set of operations that yields a bug to reveal. You think you had found it? Think again. Try to do things differently, see if it still happens. Omit steps. If you can’t make an educated guess, make some uneducated guesses. After that – call a developer who might know how things work on the inside, and direct you to a more simple way to reproduce it.<br />
Now, dear QA guys, please understand – The only people who have anything to do with your bug reports are us, the developers. Not your team leader, not your boss, not even the client. Only the developers. And it is very very frustrating for us not to understand what you have written, because, you see, we really do want to make the software we had written better. It is our reputation on the line.<br />
Since developers are the only people who have anything to do with bug reports (the most important product of the QA team), I believe (and some would not agree, for some unclear reason) that the QA team should be placed next to the development team, under the development manager.<br />
Yes, that’s right. There is no reason for a QA team to stand by itself, as the developers are those who need to use the QA products in order to fix their software. The managers can’t fix it. The client can’t fix it. Only the developers can fix it.<br />
According to the size of the organization and the nature of the project, the QA-DEV relationship nature should be defined. Small company, with small development team and small QA team – consult each other a lot by speaking to each other. Don’t go and file bug reports just like that, and don’t go and write the same pieces of code after given a bad critic. Consult. For bigger companies – bug reports are the only way to go, but make sure everything is written correctly, everything can be understood by the relevant developer (or by anyone, for that matter), everything reproduces. Write the relevant version number in the bug report. Don’t attach error logs – these should be reproduced next time that bug occurs anyhow, so instead, make sure all the steps are clear, and that there are no redundant steps.<br />
This is my two cents philosophy of quality assurance. Please try to put it to good use.Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com2tag:blogger.com,1999:blog-3029714609596082708.post-1961785663852384072009-07-10T16:24:00.007+03:002017-02-08T17:20:44.637+02:00Writing Quality Software - ArchitectureDesigning the architecture of software is very important phase in the software lifecycle.<br />
<h2>
Rules of thumb:</h2>
A good piece of software would follow several rules of thumb:<br />
<ul>
<li><strong>Reusability</strong> – The piece of software should be as reusable as possible (unless it is applicative), and reuse other components as much as possible.</li>
<li><strong>Extensibility</strong> – The piece of software should be as extensible as possible – i.e. have enough places which other developers (or the original developer in a later time) can use to add more functionality.</li>
<li><strong>Functionality</strong> – The piece of software should make the life of its user easier. The <a href="http://en.wikipedia.org/wiki/Pareto_principle">80-20 rule</a> would fit here (at least 80% of the time…)</li>
<li><strong>Order </strong>– The piece of software should be organized for easy finding of each piece of code, and easy thinking of a good place for a new piece of code.</li>
<li><strong>Traceability</strong> – The piece of software should log its actions in details, preferably in different levels of detail. Usage of extensible logging libraries (such as <a href="http://logging.apache.org/log4net/index.html">log4net</a>) are welcome.</li>
<li><strong>Security</strong> – The piece of software should not reveal security leaks, that would allow malicious code to abuse (I am talking about things like code injection, unauthorized privileges modification, system denial of service, etc.)</li>
<li><strong>Portability </strong>– The piece of software should be as portable as possible. Not necessarily between operating systems, but generally between computers. Zero installation (aka -<a href="http://en.wikipedia.org/wiki/XCOPY_deployment">xcopy deployment</a>) is always welcome.</li>
</ul>
<a name='more'></a><br />
<h2>
Reusability</h2>
When writing software, the reusability factor is crucial, especially when you have deadlines. Splitting your code into several well-defined libraries, that each can be used in other projects, would usually yield lower cost factor in terms of time,effort and money when several projects are involved.<br />
If you only have one project, you would still want to reuse. You should still split reusable code to a library of its own (or at least isolate it, so it could be split into a library at a later time). You might also would like to look for libraries that are already out there.<br />
<h2>
When not to reuse</h2>
One case where reuse is not welcome is a very specific case of the <a href="http://en.wikipedia.org/wiki/Not_Invented_Here">NIH - “Not Invented Here” syndrome</a>. This is the case where the potentially reusable code <em><strong>from an external source</strong></em> does what your business is all about. <a href="http://www.joelonsoftware.com/">Joel Spolsky</a> has a <a href="http://www.joelonsoftware.com/articles/fog0000000007.html">blog post about it</a>.<br />
Another case, where reuse should be postponed, is the lack of understanding and/or foreseeing of the correct way to build the reusable code. This would usually be after the relevant code was only written once or twice. I’ll explain: You write a piece of software that does a certain task, and you feel this task might repeat itself in the future. You go and export it to a library. Then, after a while, you want to use it again, somewhere else, but you see that it is not extensible enough, portable enough, answer your functionality requirements, etc. You still have to write your own code. Or you have to fix the library to fit the two projects, then go and fix the old project that already uses it. Fixing the library at this point would be hard, since the new project’s requirements were not taken into consideration in the original design. When a 3rd project would need it, this might repeat itself again.<br />
It is usually a good idea to wait until you have requirements from at least three different projects before you decide to make a piece of code a reusable library.<br />
<h2>
Extensibility</h2>
Extensibility allows adding new functionality in the future. There are several types of extensibility: External extensibility points, and internal extensibility points.<br />
External extensibility points are the most important. The developer of a reusable piece of code should take into account the need of another developer to add functionality, or do things a little different from his own point of view.<br />
For an example, suppose you have a class that contains a user control, and that user control is visible to the end-user. You could wrap it completely, only supplying the functionality you think relevant. But in some cases, a developer might want to tweak that control, and you might have not given him the option to do his little tweak (say, change the font or color). Exposing the wrapped control itself would allow the programmer to tweak it.<br />
<h2>
Extensibility Best Practices</h2>
Another extensibility rule of thumb would be to always expose functionality through interfaces, and if you want the user to be able to implement them in introduce the created objects to your library, use the factory pattern, and allow the user to register his own types. This allows you to replace the code behind the interface as much as you want without the user needs to wary about it, and also allows the user to introduce his own types.<br />
Generally, prefer to introduce interfaces rather than base classes. If the user need to integrate your code into a current project, a base class might prevent him from doing so, as he might need to add functionality to a current class he already has, that already inherits another base class. With interfaces, this is always possible.<br />
If you have a method that returns a result, prefer creating a specialized result class and fill it with the relevant data. If you’d like to add data in the future, this would be as easy as add fields to the already existing result class. In .Net this is also true for EventArgs – create your own even if they are empty. They might get filled later on.<br />
<h2>
Functionality</h2>
When writing software, make sure each portion of the software does what it needs to do, and does not do what it doesn’t need to do.<br />
When thinking where to place each method that implement some of the functionality required, try to group together methods that have related functions. Try to avoid duplicating functionalities, just because of small differences. If you must, do it in smart way, reducing code duplication to the minimum necessary. Use helper class or helper methods as possible, and make them static, to reduce class state artifacts.<br />
The exposed functionality should fit the user needs. In reusable code, don’t try to cover 100% of the cases. At least 10% of them are so rare you won’t even get to think about. Make a good, thorough research and find the 80% case that is relevant to you. Don’t look at other unrelated businesses research. They do things differently since they have different audience. Look inside your own market. Even in your own business. You’ll find plenty of information there. If you don’t – it only means this might be a functionality you don’t need to reuse. Make it applicative, and save others the burden of understanding why this is needed.<br />
Don’t use intrusive technologies in your code, and if you do, document them and the reason you use them. For instance, don’t do communication for traceability. The containing project might be affected by it. If you must, make sure everything is configurable, including the traceability feature itself.<br />
<h2>
Order</h2>
When building your project tree structure (in terms of code files), make meaningful separation by logic, not by physical terms. Think where a new-comer would look for a certain file. If you can’t – ask a new-comer to find that file for you just by looking at the tree structure.<br />
The same goes for using the “region” directives. I see endless “public methods” and “private properties” regions. Where would I find the method that performs the layout? or the methods that respond to user input events? I don’t know. In either of them. Better regions would be based on functionality groups. Region such as “User Interaction”, “Layout Logic”, “Construction and Initialization” are better.<br />
<h2>
Traceability</h2>
The software should log its actions and its errors. This logs are later used to analyze software usage for performance, errors, misbehavior, etc.<br />
Use a common logging method for all parts of the application. A highly configurable and extensible logging method is preferred, because in the horrible case of mismatching with another logging facility used by some 3rd party component, it can be configured or extended to match it, so everything behaves like one logging method.<br />
<h2>
Security</h2>
Security is a very important issue, especially when the software is exposed to a large user base. You don’t know which of them might want to harm you, or your client.<br />
When making database queries, make sure to sanitize the queries to prevent malicious SQL injection, that can result in loss of critical data.<br />
When asking for input of any kind from any source (and this one is especially relevant in native environments, like C and C++), make sure you have enough room for it, to prevent code injection.<br />
<h2>
Portability</h2>
A portable software is much better that a software you need to install. Copying the files to place is the easiest thing to do, and it doesn’t mess up the registry. In .NET all you need to do is make sure all the required DLLs are there, near the main executable.<br />
You might want to use tools like <a href="http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx">ILMerge</a> to reduce the number of DLLs in your distribution.<br />
When writing .NET software that should run on Linux, use <a href="http://www.mono-project.com/MoMA">MoMA</a> to make sure your application and dependencies are portable.<br />
When writing a portable application that need to be run from a portable memory device (such as a disk-on-key), make sure to write the relevant data next to the application itself.<br />
<h2>
Summary</h2>
That’s it for now about writing quality software, a quick review of architectural design. I’ll try to add more about that subject later on, and write about other aspects of writing quality software, such as user interface design, testing your application and modules, etc.<br />
<br />
<br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f07%2fwriting-quality-software-architecture.html"><img alt="kick it on DotNetKicks.com" border="0" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f07%2fwriting-quality-software-architecture.html" /></a>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-27760346488246878112009-05-28T13:01:00.001+03:002012-09-18T13:09:58.272+03:00How can Wikipedia improve its content reliability<p><a href="http://www.wikipedia.org/">Wikipedia</a> is a very common online encyclopedia, built and managed in the form of a wiki, which means anyone can modify its values.</p><p>While this promises many writers, editors and critics, thus up-to-date content all the time, it also introduces great unreliability, as you can’t trust anyone who had written anything.</p><p>While even “<a href="http://www.theregister.co.uk/2005/10/18/wikipedia_quality_problem/">Wikipedia founder admits there are serious quality problems</a>”, I figured something can be done to improved the reliability and quality of the content.</p><p>So here is my idea: Wikipedia should introduce a “<em>Content Reliability Factor</em>” that will be visible, sticking out on the top of each page. This factor will be on a scale (say, from 1 to 10), and will allow the reader to know how reliable the information on this page is.</p><p>In order to calculate the reliability factor, Wikipedia should introduce “<em>Fact Markup</em>”, to specify “<em>Fact Fields</em>”. Items that represent clear, hard facts, preferably numbers, will be marked using this markup.</p><p>There will be different types of fact fields: Absolute numeric fact fields (usually used for scientific articles), Usually climbing numeric fact fields (say, number of children of someone), Citations, etc.</p><p>Readers that come across  fact fields would then be able to rate the correctness of each fact field, and/or the entire article. Some users will be granted higher reliability factor for some values or categories, and their vote will have higher influence of the calculated result. (Of course, some articles will be blocked for such changes, for the same reasons some articles are blocked for public editing today).</p><p>Now to the really good part: When ever someone that is not trusted in a certain value or category, changes a fact field, the reliability factor for that fact field decreases. The amount of decrease depends on the type of that fact field – say, for usually climbing numbers, a decrease of that number would result in a very large decrease of that field’s reliability factor, while an increase would result in a smaller decrease of that reliability factor.</p><p>In the article history, the reliability factor will be stated next to each version. In addition, the highest ever reliability factor will be stated next to the current reliability factor on the top of the page, and will link to the relevant version of the article.</p><p>So all in all, while this idea does not solve the problem completely, and surely does not free us from the need of human approval for the content, it will allow to make better decisions regarding the given content.</p><p>P.S., There are many other methods that can be integrated into such a system that will assist with its automation. Maybe I will discuss those some other time.</p>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-69956039941862863492009-04-28T17:20:00.008+03:002012-09-18T13:10:06.555+03:00What can the government of Israel do to solve the water crisis<p>Israel suffers greatly from lack of water.</p><p>This is the case for many years now, and from one year to another the government is doing more and more to solve it. By "doing more and more" I mean pass on the blame and the responsibility to the citizens.</p><p>Now they have a big campaign featuring all greatest Israeli celebrities, telling us to save water; telling that we must stop watering our gardens; asking to shower less. Before we'll know it they'll limit our tap water drinking.</p><p>This is, of course, useless and idiotic. It won't help even a tiny bit. This is the same as doing micro-optimization to a <a href="http://en.wikipedia.org/wiki/Monkey_sort">monkey-sort</a> algorithm. This is because the reason to this water crisis lies mainly on the fact that the population growing while the amount of water in our reservoirs stays the same (in the good case) or lowers (in the bad, current, case).</p><a name='more'></a><br />
Now, what can really be done to solve that crisis? Understanding the reasons, quite a few things:<br />
<ol><li><b>Fixing Pipes</b> - As what I've read, many of the main water pipes in Israel are leaking. In the announcements they tell us to close and fix leaking taps. A leaking tap costs us about three or four liter of water a day. A leaking main pipe costs us much more than that. I roughly assume between ten times more for a small pipe and a thousand times more for a big, central one.<br />
</li>
<li><b>Desalination</b> - This is the most important one of all. Different versions of it will appear in some other suggestions. This one is the only action that can be taken that actually creates new drinking water out of bad water. Actually, there are some desalination devices used in Israel, but not enough. It seems like the bureaucracy is killing every new attempt to build new desalination devices. It is claimed that it takes about five years to build one, so the required authorizations are rarely granted, given the government is replaced every four years in the good case.<br />
</li>
<li><b>Recycling</b> - Yes, water can be recycled. Actually, today, much of the water for agriculture are recycled water. The idea is that instead of sending all used water to the draining system, we clean them a bit (so they're not good for drinking) then re-use them to water fields. The same thing is also done in some water-smart buildings, where used water are re-used to fill toilet tanks. I say the government should demand that every new building would be built with such a system installed.</li>
<li><b>Mineral Water</b> - There are three main companies that produce bottled mineral water in Israel. These are very good water, that most of the citizens can only buy for a great cost in bottles. I think the government should limit the amount of bottles produced every year, higher the cost of local production by taxing that companies per liter, and encourage importing of bottled water, by lowering import tax for water. In addition, state in law that every place that sells bottled water <b>must</b> sell at least one brand of imported water. Oh, and forbid exporting of local water products.</li>
<li><b>Collecting Rain</b> - Well, here we get a bit into micro-optimization, except this one is actually feasible. We can collect rain water not only in special reservoirs dug for that purpose, but using the roads and roofs draining system. Come to think about it, there is rarely anything bad in water dripping on roofs and roads. This is usually rain water, and there is always a special draining system built for each roof and on each road. Those draining system go usually to the sewer, but it is possible to collect it to reservoirs. Those doesn't have to be open reservoirs. They can be closed and underground. Still they are reservoirs, and they will get filled in the few rains we have each winter.</li>
</ol><p>Well, these are my ideas for solving the water crisis. Not all are original, but I figured I'd put them all in one place, and maybe something will be done about it someday.</p><p>Please feel free to comment and to suggest new ideas.</p>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com2tag:blogger.com,1999:blog-3029714609596082708.post-67295390967052597182009-04-25T15:41:00.003+03:002011-06-10T16:23:53.146+03:00BiDi – What is it, why we need it<p>BiDi stands for Bi-Directional text. Yes, specifically text. In some places (such as the Word text editor) this is referred to as Complex Scripts.</p><p>So what exactly is it? It is the case where several languages of different writing directions are mixed in a single sentence. More than that, in some cases, this is the case where a Right-To-Left language (Hebrew, Arabic and Persian) needs to be rendered to screen.</p><p>Why is this a problem? This is a problem because there is a dilemma of how to store textual data that contains both directions of writing; On the one hand, it can be stored visually, just like it appears on the screen. It will make it much easier to render, and save us from all the burden and improve performance of the rendering phase. On the other hand, however, it will make our writing phase much harder, and will require us to write some of the text reversed. Actually this is exactly what people where doing before the age of Logical Text and the BiDi algorithm.</p><p>The BiDi algorithm brought a new age of Logical Text, and by that we mean the way the text is stored in memory. Instead of storing it the way it is rendered, we store it the way it is being read and written. When we read text that contains several text directions (Hebrew and English mixed, for example), we change our reading direction every time the language is changed. When we write text that contains several directions, we still write the first letters first, and last letters last, even when the language changes. We don’t reverse the order of characters for that task.</p><a name='more'></a><br />
<p>Storing the text logically makes much more sense, and makes it easier to develop software that handles text. The software behaves with text in the same way we think about it. However, in order to draw the characters on the screen in their correct position, we first need to reorder them.</p><p>Rendering text is not an easy task. Rendering each line requires all the letters (and other characters) to appear in their correct positions, since we usually want the renderer to make one pass due to efficiency reasons. Before that, if we want our break our lines to fit in a given width, we need to calculate the widths of the characters and select where to break the line <strong>logically</strong>, as doing it visually might yield an unreadable result.</p><p>The reordering is done in the line level, after the text has been broken to lines. The BiDi algorithm takes each line and returns a new line with all the characters reordered, ready to be rendered.</p><p>The process of reordering can be controlled by inserting special Control Characters to the text. The most common ones define literally the direction of the text, even if the characters themselves implies differently. You can try it yourself: try to launch notepad, write some text, then click the right mouse button, in the context menu go to “Insert Unicode control character”, and select one of the control characters available. Experiment with it a little, see how it effects the text from that point on.</p><p>The BiDi algorithm is a one way algorithm. There is no reversed algorithm, and it is not guaranteed that running the same algorithm on visually ordered text would give the correct logically ordered text, since the visually ordered text could be the result of control characters usage, that might have been lost after the conversion. Thinking deeply about it, you don’t really need to convert back. If you do, think again, you’ve got something wrong in your overall design (this is always true, except for the case where you have <strong>INPUTS</strong> from a legacy device that can’t be altered, and those inputs are ordered <strong>VISUALLY</strong>. I will try to deal with this case in another post, if requested).</p><p>For further reading, the official <a href="http://www.unicode.org/">Unicode</a> website contains all Unicode information needed, including the <a href="http://www.unicode.org/reports/tr9/">BiDi algorithm</a>.</p><p>You can find my implementation for that algorithm,called “<a href="http://nbidi.sf.net">NBiDi</a>”, written in C#, targeting .Net and currently being used to implement <a href="http://www.codeplex.com/SilverlightRTL">Right-To-Left Silverlight controls</a>.</p><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f04%2fbidi-what-is-it-why-we-need-it.html"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f04%2fbidi-what-is-it-why-we-need-it.html" border="0" alt="kick it on DotNetKicks.com" /></a>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com1tag:blogger.com,1999:blog-3029714609596082708.post-59250636981522916242009-04-25T15:19:00.003+03:002011-06-10T16:33:34.049+03:00A quick review of different UI frameworks<p>In this post I'll review several frameworks used for creating graphical user interfaces. I've decided to create such a review after noticing many programmers take a specific GUI framework for granted, as it is their automatic-choice-by-tool (i.e., they use what they're IDE let them, barely understanding the layers required to develop such a framework, and that there are alternatives they might have chosen if they had knew about).</p><p>I will review the following frameworks:</p><ul><li>Windows.Forms</li>
<li>WPF (+Silverlight)</li>
<li>GTK</li>
<li>QT</li>
<li>wxWidgets</li>
<li>AWT</li>
<li>Swing</li>
<li>SWT</li>
<li>X/XT/Motif</li>
</ul><a name='more'></a><br />
<h2>Windows.Forms</h2><p>Naturally the automatic choice for anyone who builds a GUI in .Net. The first version was there from the very first .Net release, and supported by all versions of Visual Studio, the main IDE for .Net development.</p><p>When you ask most .Net developers what are they are using to build forms for their applications, they will most likely say "The default thing that comes with Visual Studio" or "... with .Net". Most won't even know other UI frameworks exist.</p><p>And for some technicalities: Windows.Forms in its original implementation wraps the underlying Windows native controls. In its second version, some controls where added that doesn't wrap any base controls, but rather implemented the entire logic and graphics internally in C#.</p><p>As most .Net frameworks, their immediate audience is the Windows users (or in this case - developers). However, the <a href="http://www.mono-project.com/">Mono</a> project had implemented all the Windows.Forms controls entirely in C#, not wrapping anything at all, while maintaining complete API compatibility (including message loop interference). Due to the nature of .Net binaries, this allows migration of compiled applications from .Net to Mono, hence from Windows to Linux.</p><h2>WPF (+Silverlight)</h2><p>The newest technology reviewed in this list. Has not yet become a natural choice of any developer (mainly due to the lack of tools and IDE integration), but it is getting there. Unlike any other framework listed here, this framework does not base on the underlying windowing system at all. The only use it has for the windowing system is to open and register a top-level window. From now on it is all DirectX (at least in the WPF implementation).</p><p>Using XAML as the main form of defining UI, and tools that resemble artistic programs more than IDEs, WPF really allows developers and designers to work together, letting each one focus on what he can do best, providing better separation between the two worlds. Also, it allows to create applications that are much more appealing visually than most common applications.</p><p>WPF stands for “Windows Presentation Foundation” and was introduced with .Net framework 3.0.</p><p><a href="http://silverlight.net/">Silverlight</a> is a subset of WPF, targeting the web. Allowing roughly the same features as WPF, in the same development model, using the same tools, it bridges the gap for developers and designers to move from desktop to web environment and vice-versa, allowing knowledge and components to be persisted and reused.</p><p><a href="http://www.go-mono.com/moonlight/">Moonlight</a> is an open-source implementation of Silverlight, part of the <a href="http://www.mono-project.com">Mono</a> project, aims to bring Silverlight to the Linux world.</p><h2><a href="http://www.gtk.org/">GTK</a></h2><p>The automatic choice for anyone who develops applications for the <a href="http://www.gnome.org/">Gnome</a> Linux desktop. Written in C, and have many language bindings, including C#.</p><p>GTK was originally developed to support the development of <a href="http://www.gimp.org">The GIMP</a> (the GNU Image Manipulation Program), thus was named “GIMP Tool Kit” – or GTK for short. Later on it became the main toolkit for the entire <a href="http://www.gnome.org">Gnome</a> Linux desktop project.</p><p>This is an open-source (LGPL) library, developed and maintained by the community. <br />
GTK is a source-code-compatible, cross-platform toolkit, that has binary distributions for Linux, Windows, and Mac OS, and has some support for mobile devices as well (it runs on some Nokia smart phones, and used to build the <a href="http://www.laptop.org/">OLPC</a> project and the <a href="http://www.openmoko.com/">OpenMoko</a> project user interfaces).</p><p>It supports several levels of themes (Skins and Theme Engines), and has default themes for each operating system, especially for the Windows and Mac OS, that have very specific themes. This allows GTK applications to merge in the look and feel of those operating systems.</p><h2><a href="http://www.qtsoftware.com/">QT</a></h2><p>Originally developed by TrollTech, now owned by Nokia and supported by the community. Written in C++ and utilizing a Meta-Object-Compiler - a special precompiler that adds several features to the C++ language, mainly used for easier data binding. Some language bindings are available, including a community binding for C#, named <a href="http://techbase.kde.org/Development/Languages/Qyoto">Qyoto</a>.</p><p>QT is a cross platform framework targeting both Desktop and Mobile applications. <br />
In its open-source license (GPL, LGPL) it is used to develop the <a href="http://www.kde.org">KDE</a> Linux desktop environment, while in its commercial license it is used by commercial software and hardware vendors to build the GUI of their products.</p><p>QT has a very good support for themes, allowing it to merge in the look and feel of just about any environment, including Windows, Mac OS, and even the Gnome Linux desktop (by reading the Gnome theme configuration file).</p><h2><a href="http://www.wxwidgets.org/">wxWidgets</a></h2><p>wxWidgets is a cross-platform framework designed to use each system’s native controls to the max, while preserving common API and rich set of controls. Written in C++ and has several language bindings including C#.</p><p>There are no common tools that support visual design for it, but there are several visual designers for it out there, such as “<a href="http://www.anthemion.co.uk/dialogblocks/">DialogBlocks</a>”.</p><h2>AWT</h2><p>The Java most basic set of UI controls. AWT stands for “Abstract Windowing Toolkit”, and works in the same manner as .Net's Windows.Forms, but implemented differently on each JVM (i.e., wraps each system's native controls - The native Windows controls on Windows, usually GTK on Linux, and Cocoa on the Mac.)</p><h2>Swing</h2><p>Swing is Java’s themable UI framework, written completely in Java, using AWT’s most basic controls only, and built from scratch on top of than.</p><p>While this allows much nicer look and feels, Swing came too early and suffered from bad performance caused by the need to draw heavy graphics using a virtual machine on computers not strong enough at the time. This caused many developers to look for alternatives, and SWT was the most common one.</p><h2>SWT</h2><p>This one can be compared to the second version of Windows.Forms, or to wxWidgets, if you'd like. Based on each JVM implementation of AWT, makes a so called "Mix and Match" to create a better set of controls, that can run on each operating system and gains its native look and feel, while bringing large set of controls and maintaining performance by using the operating systems native controls.</p><h2>X/XT/Motif</h2><p>The 'X' Windowing System is the service that bring graphics and windowing operations to the Unix world. Like most windowing systems, this system is also based on a message loop and message dispatching, where each control is usually a window.</p><p>The X-Toolkit (XT) is a library helping to develop controls. It separates the control logic and design from the need to handle all the events passed to it from 'X', thus allowing vendors to focus on developing the controls themselves. Over time this approach has failed to persist, as no new control sets where created after Motif, and newer GUI frameworks (toolkits) had chosen to handle all events themselves, which also helped building cross-platform GUI frameworks.</p><p>Motif is the most commonly used set of controls that was build for the X-Toolkit framework, allowing large variety of controls for different aspects of GUI development.</p><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f04%2fquick-review-of-different-ui-frameworks.html"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f04%2fquick-review-of-different-ui-frameworks.html" border="0" alt="kick it on DotNetKicks.com" /></a>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com4tag:blogger.com,1999:blog-3029714609596082708.post-50724076768766968582009-04-15T16:29:00.011+03:002012-08-07T20:13:46.639+03:00Runtime testing and casting objects of generic typesHow can you tell, in runtime, if an object you have is of a specific generic type? For instance, if it implements the generic interface <code>ICollection<T></code> ?<br /><br />You might say, "lets get all interfaces implemented by that object, first by getting its type (using <code>GetType()</code>), then by calling <code><a href="http://msdn.microsoft.com/en-us/library/ayfa0fcd.aspx">GetInterface(string name)</a></code>, passing in the type name in its mangled form".<br />This will work, however, this yields to error prone, non-type-safe code, plus, making us required to know how to build the relevant mangled string.<br /><br />We would like something better. We would like to be able to get the generic type itself. Fortunately this can be easily done the following way:<br /><pre class="brush: csharp">Type genericCollectionInterfaceType = typeof(ICollection<>);</pre><br />This will return the generic collection interface type. Now, what can we do with it? We wanted to test if a certain object implements this interface. However, a list of, say, strings, will NOT implement that interface. It will implement the <code>ICollection<String></code> interface, which is not the same as <code>ICollection<></code>.<br /><br />What can we do? We need to build, in runtime, a generic interface type that corresponds to the interface signature of our object:<br /><pre class="brush: csharp">Type testedObjectType = testedObject.GetType();<br />Type genericType = typeof(ICollection<>).MakeGenericType(testedObjectType.GetGenericArguments());</pre><br />Then we can use that type to test for assignability:<br /><pre class="brush: csharp">collectionType.IsAssignableFrom(testedObjectType);</pre><br />Calling <code><a href="http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx">MakeGenericType</a></code> creates a new <code>Type</code> object that represents the type we are looking for. We pass it a list of types, in this case taken from the object itself (using <code><a href="http://msdn.microsoft.com/en-us/library/system.type.getgenericarguments.aspx">GetGenericArguments</a></code>). Then we can check for assignability between the two.<br /><br /><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f04%2fruntime-testing-and-casting-objects-of.html"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fitaibh.blogspot.com%2f2009%2f04%2fruntime-testing-and-casting-objects-of.html" border="0" alt="kick it on DotNetKicks.com" /></a>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com2tag:blogger.com,1999:blog-3029714609596082708.post-11268364356357388462009-04-11T20:00:00.005+03:002009-04-11T22:42:21.457+03:00Lasers and experimentsI tried to activate a laser diode today, that I disassembled from an old DVD player.<br />I used a cellphone recharger (outputs 5V) and connected the wires.<br />It worked for about half a second. I think it is now dead. R.I.P.<br />Anyone got old DVD/Bluray players they don't need?<br /><br /><div style="text-align: center;"><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_skWDg2sd0Zc/SeDQFnD5wII/AAAAAAAABcg/Dw8Rix5gJEo/s1600-h/Laser+Diode+Parts+2.JPG"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 239px;" src="http://2.bp.blogspot.com/_skWDg2sd0Zc/SeDQFnD5wII/AAAAAAAABcg/Dw8Rix5gJEo/s320/Laser+Diode+Parts+2.JPG" alt="" id="BLOGGER_PHOTO_ID_5323483554355200130" border="0" /></a><span style="font-size:85%;">The dead laser diode (on the right), and its original housing and controller.</span><br /><br /><br /></div><div style="text-align: center;"><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/_skWDg2sd0Zc/SeDQFWJD5QI/AAAAAAAABcY/cbnZuFxmBWo/s1600-h/DVD+parts+4.JPG"><img style="margin: 0px auto 10px; display: block; text-align: center; cursor: pointer; width: 320px; height: 240px;" src="http://3.bp.blogspot.com/_skWDg2sd0Zc/SeDQFWJD5QI/AAAAAAAABcY/cbnZuFxmBWo/s320/DVD+parts+4.JPG" alt="" id="BLOGGER_PHOTO_ID_5323483549813433602" border="0" /></a><span style="font-size:85%;">The disassembled DVD player.</span><br /></div>Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com0tag:blogger.com,1999:blog-3029714609596082708.post-3310315545305541282009-04-09T11:50:00.018+03:002013-04-17T19:04:19.537+03:00Creating customizable WPF drop-down menus (7)<section class="related"><h2>Related Posts:</h2>
<ul>
<li><a href="http://itaibh.blogspot.co.il/2009/03/creating-customizable-wpf-drop-down.html">Part 1</a></li>
<li><a href="http://itaibh.blogspot.co.il/2009/04/creating-customizable-wpf-drop-down.html">Part 2</a></li>
<li><a href="http://itaibh.blogspot.co.il/2009/04/creating-customizable-wpf-drop-down_06.html">Part 3</a></li>
<li><a href="http://itaibh.blogspot.co.il/2009/04/creating-customizable-wpf-drop-down_2044.html">Parts 4 and 5</a></li>
<li><a href="http://itaibh.blogspot.co.il/2009/04/creating-customizable-wpf-drop-down_09.html">Part 6</a></li>
<li><a href="http://itaibh.blogspot.co.il/2009/04/creating-customizable-wpf-drop-down_3705.html">Part 7</a></li>
<li><a href="https://docs.google.com/file/d/0BxinGAr39Pd0Rmk0VFNFd25PaVU/edit?usp=sharing">Sample Project</a></li>
</ul>
</section>
<br />
<h1>Step 7: Using the new binding correctly</h1><br />
Remember that we overridden <code>OnDragEnter</code> so the menu will open upon hovering? Well, we will have to make a slight change to that code, to (also) use our new property:<br />
<br />
<pre class="brush: csharp">protected override void OnDragEnter(DragEventArgs e)
{
IsSubmenuOpen = true;
IsSubmenuOpenInternal = true;
e.Handled = true;
}</pre><br />
Great! Except now the menu never closes. Well, the first occasion we want it to close is when we're done dropping. So we will add the following snippet to our <code>OnDrop</code> code, just before the <code>e.Handle = true</code> code:<br />
<pre class="brush: csharp">if (parentMenuItem != null)
parentMenuItem.IsSubmenuOpenInternal = false;</pre><br />
Another case when we want it to close is whenever a neighbor menu opens, or in case we stopped using the menu at all (like, clicking any other place). But the thing is, we really don't want to write such code, as it is already written. We need a way to find when the original property would change to <code>false</code> and do the same.<br />
Luckily, there is a routed event just for that: <code><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.submenuclosed.aspx">SubmenuClosed</a></code>.<br />
We will register to that event, and change our new property to <code>false</code> likewise. Except, we do it with a minor change: we need to make sure we are not in the middle of a drag operation, or right in the drop handling code. We will register to that event in the constructor, and implement it:<br />
<pre class="brush: csharp">public DraggableMenuItem()
{
AllowDrop = true;
SubmenuClosed += new RoutedEventHandler(DraggableMenuItem_SubmenuClosed);
}
void DraggableMenuItem_SubmenuClosed(object sender, RoutedEventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Pressed || !IsDragging)
IsSubmenuOpenInternal = false;
}</pre><br />
But now there is another problem - the menu doesn't open well, since we replaced the <code>IsSubmenuOpen</code> with <code>IsSubmenuOpenInternal</code>. So the same way, we need to handle the open event - <code><a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.submenuopened.aspx">SubmenuOpened</a></code>:
<pre class="brush: csharp">public DraggableMenuItem()
{
AllowDrop = true;
SubmenuClosed += new RoutedEventHandler(DraggableMenuItem_SubmenuClosed);
SubmenuOpened += new RoutedEventHandler(DraggableMenuItem_SubmenuOpened);
}
void DraggableMenuItem_SubmenuOpened(object sender, RoutedEventArgs e)
{
IsSubmenuOpenInternal = true;
}</pre><br />
And that's it! The menu is now Drag-and-Drop customizable! Note that the code brought here in this article is for explanatory purposes only, and is far from perfect. Its goal is to explain the main issues and problems encountered while developing such a control, so use it as a reference only.<br />
<br />
Hope you have found it useful, and please let me know if you did, and I'll be glad to hear about successful (preferably complete) implementations.<br />
<br />Itai Bar-Haimhttp://www.blogger.com/profile/09367004872480545744noreply@blogger.com1