| Hernan's profile3D StudiosPhotosBlogLists | Help |
|
July, 2006 Collections++Problems of the past One of the most annoying programming issues with the .NET Framework was Array management. Using a Type[]-kind arrays is complicated, they cannot grow nor shrink, they don't have Add or Remove functions, and so on. From my point of view, arrays were left as a somehow untouched feature of the Framework. To bring a solution, they've introduced the System.Collections Namespace which provided array-like classes like the ArrayList, which has almost everything you could ask for to a native array: Add, Remove, Contains methods among others and it can auto-grow and shrink itself on demand. But this solution introduced yet another problem: ArrayLists are NOT strong-typed. While that can be considered a flexibility, it can also let in programming issues like, mistakenly, insert a string into an array of what you think are integers and get runtime type-casting exceptions thrown. We should also mention some of the performance issues that ArrayLists bring to table, but we'll talk about that later on. Generics to the rescue With the introduction of the version 2.0 of the .NET Framework, Microsoft has added Generics support, which is a brand new feature. Generics are not a feature specific to C# or VB, Generics are a feature of the Framework itself and both of the aforementioned languages support them as, I guess, C++ and J# do. Generics have also been added to the ECMA standard so don't be surprised by the fact that the Mono community has already added support to their runtimes and to the C# 2.0 (or GMCS) compiler as well (although they say that that's not yet finished). Brief introduction Brief and concise: As well as parameters turn your methods useful, Generics allow you to pass parameters to your Types and turn them yet more useful than they already are. Case examples Let's say that you're working on your little business management application and you have two types which represent your Customers and your Representatives respectively: //We don't care about the implementation public class Customer {...} public class Representative {...} By normal data flow, is obvious that the Representative Class will have a collection of Customers which the Representative represents (seriously, isn't that logic?). In the .NET Framework 1.x, we'd write: using System.Collections; . . . public class Representative { ArrayList customers; public Representative() { customers = new ArrayList(); } } The first thing that we realize here is that the ArrayList is a collection of objects, not Customers. Therefore, whenever you add a Customer, is has to be casted to an object and when you read one out, it needs to be casted back. So: //Add //Either customers.Add ( new Customer() ); //Implicit Cast //Or customers.Add ( (object)( new Customer() ) ); //Explicit Cast //Read //Either Customer customer0 = customers[0]; //Implicit Cast //Or Customer customer0 = (Customer)customers[0]; //Explicit Cast All that takes some processing. The runtime has to check whether the second can be done. Imagine that you have an array of Integers. They need to be Boxed and Unboxed, which also needs processing... Something like the following could happen, too: customers.Add ( “I was sleepy when I wrote this. I forgot the coffee.” ); //A string comes in. i.e.: In index 0 Customer customer0 = (Customer)customers[0]; //Oops, this will cause a runtime exception. Resuming: While ArrayLists are powerful and simple to use, they need some unnecessary processing and are not strong-typed. Generics' features and improvements So far we've read the bad news, but we'll now read the good ones, followed by code examples, of course. Generics allow strong-typed, auto-growing, on-demand shrinking arrays filled with useful methods as well as other “dynamisms” for delegates, for example. So, let's see how a generic List would look like: public List<T> { int count; T[] objects; public List() {} public void Add ( T value ) { objects[++count] = value; } public T Read ( int index ) { return objects[index]; } } The first question you'd ask yourself should be: “What does that T thing mean?!” I'll tell you. Analyze the following class: public ListOfCustomers { int count; Customer[] customers; public ListOfCustomers() {} public void Add ( Customer value ) { customers[++count] = value; } public Customer Read ( int index ) { return customers[index]; } } In the second case, the only object, I'll say that twice the only object that we can add and read to and from the array is “Customer”. So, suppose that you need a list of Representatives, well, you'd need to write the same thing once again and change the data type to Representative (if you want strong-typing). Wouldn't it be easier if we just instantiated the first List twice like follows List<Customer> customers = new List<Customer> (); List<Representative> representatives = new List<Representative> (); and still have the same result? Yes, it'd be and is possible today! I mentioned improvements and I won't finish the article without explaining why I did. Do you remember what I said about the type-casting and boxing and unboxing that has to be done with ArrayLists? Well, as we're passing this T parameter to the List type and this type is then used to define the type that the array of objects will be, the type passed to our Add method and the return type of our Read method, casting is unnecessary. Boxing and unboxing is unnecessary too if we'd pass in an int or float, for example. So, the type that the list uses is always the one that you pass in the T parameter. Isn't that great? Filtering Ts out It may happen that you only want T to be a Class, or a Struct for example. Well, that can be fixed like the following: public class List<T> where T:class //T must be a Class. //Or public class List<T> where T:struct //T must be a Struct. In the CLR As I said, Generic types are initialized at runtime which would mean that if we need two lists of different types, the list would have to be recompiled every single time. Well, here's where the CLR's intelligence comes in. If it is the first time in our whole application's run time, the list will be compiled. If it's not the first time, and the type that you're passing in is a Reference Type, the code is shared as in the underlying assembler code, they're just pointers. So, for Reference Types, they're compiled just once. If the type is a Value one, the list will be recompiled every time. Go and run CSC! To close, be aware of the following: There's already a type List<T> in the System.Collections.Generics Namespace (where all the generic types are), so don't implement it by yourself. I also mentioned that generics add some “dynamism” to delegates and stuff, but we'll cover that in some future article. Last word: Read List<T> as “List of T”. Be Generic! Hernán A. Gatta May, 2006 SuSE is live baby!Alright, I’ve been for years trying to get a functional Linux installation. I guess the attraction of unknown technology keeps me trying new stuff. I remember some years ago my try to get Corel Linux 1.0 November 1999 Release up and running on my PII PC: X didn't run (yes, X Windowing System – “System”). I gave up. Fast forward to today, I had to try again. I downloaded SuSE 10.1 from http://en.opensuse.org/. I opted for the DVD which is a 3.49GB download. I got it from a server somewhere in Italy from which I reached ~450KB/s of download rate (compared to the ~68KB/s from their servers). I burnt the ISO Image and I booted the DVD. I installed it following the pre-defined settings and I got it up and running perfectly, even dual-boot with WXP is perfect.
I’ll be posting about some of the issues that I had to “tackle” soon.
Happy installing!!! J Hernán A. Gatta April, 2006 Managed/Unmanaged InteroperabilityThe .NET Framework is quite a new technology and native code stills around, so isn’t a surprise the fact that the Framework provides interoperability with native libraries. There are three methods that you can use to use native libraries. If you have a COM Component that you’d like to use from your managed application, this is the best way of doing it. Simply do right click over the project from which you’ll be referencing the component and choose “Add Reference...” Then click the “COM” tab. Visual Studio will scan the Windows Registry for registered COM Libraries and will show you what it has found. After you select the components that you’d like to use, click OK. Then you’ll have a namespace corresponding to the components you’ve selected. As the name suggests, it implies mapping your native class into a .NET Class. For example, you may have the following: MethodSomething() { Implementation } Managed Class: That is, you expose the all the same methods through your managed class and you call the unmanaged implementation. As I’ve explained in other post, this is the lowest level communication between Managed and Unmanaged. You can use this to make calls into almost anything. Check the previous post for more information. Hernán A. Gatta April, 2006 A primer to Integer Overflows/Underflows1 bottle of beer on the wall, 1 bottle of beer, you take 1 down, pass it around, 0 bottles of beer on the wall. Hernán A. Gatta April, 2006 Controlling Objects' LifetimesAll .NET objects contain a Finalize() method that is inherited from the ultimate base System.Object class. Finalizers are methods that are used to release any unmanaged resources and perform clean-up operations before the object gets garbage collected. If you need to do such clean-up, you can always override the method with your own implementation. Finalizers are non-deterministic, that is, you can’t tell when they are going to be called as that’s up to the GC; so you shouldn’t put any code in it that you depend on being called. Only implement Finalize() if your class really needs one as objects with finalizers take longer to allocate and longer to destroy because the finalizer has to be called. Now, there’s no way to call an object’s finalizer explicitly so what if you want to release an object’s resources? Putting the code into the finalizer won’t work because you don’t know when it is going to be called and you can’t call it by yourself, so in the .NET Framework we have the IDisposable Interface which provides a simple clean-up model for your classes. Classes that implement this interface must implement a Dispose() method that is used with the same purposes as the finalizers plus you can free managed resources if you wish as well. Calling code can run Dispose() to free up resources and leave the garbage collection on the object up to the system. Hernán A. Gatta .NET's GCWe’ve got a short title this time. Well, if you’re wondering what the GC is, here’s the answer: The GC is a Garbage Collector that is directly built into the CLR. Its task is to track unused objects and delete them from memory. That means that we don’t have to worry about memory management as we used to do with native code. Thousands of C++ developers around the world have only dreamed about having this feature integrated into their runtime libraries, so guys, you now have C++ .NET that contains a nice-working GC. Of course we optionally still have the control of objects' lifetimes. One of the common mistakes is not freeing memory up; also called memory leakage. It happened to me many years ago with one of my first VB6 applications. It was a tiny text editor with some rich text formatting capabilities and image importing. The program started up using 40MB of RAM and could end up using 140MB after editing a few documents with large images. If you create an object in native code, it will remain there until your application is shut down. In some extreme cases, an application could leak memory up to the point that it will start interfering with other applications and with the OS itself, and most probably, it will make your computer crash. The worst memory management mistake is when you free memory up at the wrong time. If delete gets called on an object too soon and another piece of code tries to access that object, you can expect a run-time exception. The same will happen if delete gets called more than once on the same object. Although manual memory management allows you to do some really tiny adjustments to your code, it can mess it up as well. Under the covers, every .NET object belongs to a specific generation. When an object is first allocated, it is placed in generation 0 and then they get promoted to higher generations with longer lived objects; that is, you don’t need to run garbage collections on the whole heap, you just have to consider the age of an object. The collection occurs when generation 0 is full. Unused objects are deleted and objects that didn’t get collected are promoted to generation 1. The GC always runs first on generation 0. If it doesn’t free up enough memory, it will continue on higher generations. On .NET 1.0, only generations 0, 1 and 2 were supported. If you ever need to access the GC by yourself, you can use the System.GC class. You can run a collection on the default generation or you can specify one by using the Collect method. If you want to know the generation an object belongs to, you can call the GetGeneration method passing in a reference to a specific object. Hernán A. Gatta April, 2006 What the .NET Framework can't do, P/Invokes canAs we all know, creating class libraries that encapsulate every single method of the Windows API is almost impossible, so it wouldn’t be hard to believe that .NET can’t do everything. But what happens when you need to do something that .NET can’t? Well, there are a few answers but everyone ends up in a P/Invoke. That’s the short for Platform Invoke and it’s the lowest level possible communication between Managed and Unmanaged Code. P/Invokes can be done against the Windows API or any other library (they don’t need to be COM Components). Let’s take a look at some Visual Basic .NET (2.0) code and analyse it word by word: Public: As when you define a method, is its scope. Declare: Same as “extern” for other languages. Means that the function is somewhere outside your application. Auto | Ansi | Unicode: Encoding. For non-NT systems better use ANSI, for NT systems, Unicode and if you’re not sure of where you’re application will run, use Auto. Function | Sub: Same as when use in a Visual Basic .NET application, if the method returns a value, use Function otherwise, use Sub. SetWindowText: The name of the method. Lib: Where the method is located. If the library you’re calling into is a well-known one (such as a Windows API library), you can just type the name of it like in this case otherwise, you’ll need to type the whole path. user32.dll: In this case, there’s the method located. Alias: An alias for the method, in this case the last W at the end denotes “Unicode”, that is that the string that we’ll be passing to lpString is Unicode-encoded. The ANSI variant is “A” instead of “W”. Normally, you should accord the encoding at the beginning with the method’s alias. The rest are the function parameters and the return type. Remember to use native types, never pass a SqlConnection Object to one of those or you’ll run into trouble.
Hernán A. Gatta February, 2006 Asynchronous Operations on .NETHave you ever wanted to show a nice progress bar while executing something in the background but you couldn’t because you had no idea on how to pass parameters to a thread? If that did happen to you, you may remember the frustration you first felt. There’s not too much about asynchronous operations, and getting to do them on .NET is quite straightforward. Before starting to code, let’s get some theory of what this is all about: what you first need to know about asyncing is that there are methods that are Thread-Safe and Non-Thread-Safe; this means that you may call a method on the main thread from your second thread but if the method is Non-Thread-Safe, you’ll get an exception. Normally, Thread-Safe methods’ names start with ‘Begin’ and ‘End’. Now, in the case we need to call a synchronous method asynchronously we need some method to call, a calling method and a Callback one; hereby an example: […] End Sub […] End Sub Sub Callback(ByVal ar as IAsyncResult) ‘Callback method. […] End Sub Dim del As DAsync = New DAsync(AddressOf DoSomeStuff) Dim DCallback As AsyncCallback = AddressOf Callback In your DoSomethingAtBackground() method you should have at least the following to get asyncing. up: del.BeginInvoke(“Hello World!”, DCallBack, Nothing) del.EndInvoke(ar) ‘Always remember this. Here I drop a simple example (this is a Console Project. You need to call DoSomethingAtBackground() from your Main() method): Module Sample Delegate Sub DAsync(ByVal Text As String) Dim del As DAsync = New DAsync(AddressOf DoSomeStuff) Dim DCallback As AsyncCallback = AddressOf Callback del.BeginInvoke(“Hello World!”, DCallBack, Nothing) End Sub MsgBox(Text) End Sub del.EndInvoke(ar) ‘Always remember this. Console.WriteLine(“Is task done? ” & ar.IsCompleted.ToString()) End Sub End Module Happy Asyncing! Hernán A. Gatta January, 2006 XAML...I got into XAML (Extensible Application Markup Language) a few days ago. I downloaded and installed the WinFX SDK, the Windows SDK and the WinFX Extensions for Visual Studio 2005. It is a ‘Wiring Technology’ that lets you descriptively set up your UI (WPF), Events and Properties; Networking Services (WCF), Data Binding (CLR Integration) and so on in an XML-looking experience. For most developers, XAML will be replacing the well-known Windows Forms Designer file. If you’re not a programmer, you could still find XAML useful as you can set up also 2D and 3D static or even animated graphics. For a developer’s example, let’s take a look at a little comparison:
XAML (pretty much the same thing):
Yes, XAML lacks Class Attributes… For Graphical People:
Happy XAMLing!
Hernán A. Gatta January, 2006 About DTA...About the DTA's double attempt to initialize the CRT (C++ Runtime Library): After a couple weeks waiting the Microsoft's answer to this tricky kind of ‘bug’, we got that there's an incompatibility in the AppCompat Layer in Windows when applied to the ‘explorer.exe’ (the basic Windows Shell). This Layer does an emulation that somehow maps the old Windows APIs to the new ones and lets you run apps. designed to run in older Windows versions. This is new to WXP. There's a defect in the AppCompat Layer that causes double initialization of the CRT. When ‘explorer.exe’ is set to use AppCompat shims, EVERY app. that is launched by it will inherit the same AppCompat settings, therefore, causing the app. to hang (as long as your program also initializes the CRT). This can be fixed by deleting the entry for ‘explorer.exe’ under ‘HKLM\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers’ in the Window's Registry. For this to take effect, of course, you'll need to either restart your computer or kill the ‘explorer.exe’ process and start it again.
Reference:
Happy fixing!
Hernán A. Gatta December, 2005 The Future's… Platform?A bunch of Microsoft guys telling you in a conference that Visual Studio 2005, SQL Server 2005 and BizTalk Server 2006 will resolve your business problems is not the best way of getting up-to-date. Although Visual Studio is a kind of ‘recognized piece of artwork’ in the software development world, doesn't really mean that it's bug-free. Nothing new, right? The problem comes up when bugs are too easy to discover. When you have an application that works fine, doesn't matter if it has scenario-specific bugs, it's alright; but when you have an application like Visual Studio and the first thing that you see is not the new Device Emulator, is a bug, well, we have an issue. If you got the opportunity to go to the Launch 2005 and hear in the opening session that more than 8000 bugs were fixed because of the BETA customer's feedback, is a little bit shocking doesn't matter what you think. Seems like there is a bug behind every single line of code that they write. A good example of this is the Database Tuning Advisor that comes with SQL Server 2005 Standard Edition and upwards: I installed the whole SQL package, that, by the way, it took me like forty-five minutes, not fifteen as someone said. One of the things that I did first after restarting the computer was to open the DTA. I fulfilled the fields with the correct data and I pressed ‘Connect’. What did I get? The beautiful C++ Runtime Library Error telling me: ‘Attempt to initialize the CRT more than once. This indicates a bug in your application.’ It's somehow an unexpected thing to happen right after installation. Anyway, continuing with my helpful ideas, I went into the feedback center and started posting bugs and suggestions. The only way of them getting to know that you want to kill them. What did I discover so far?
Suggestions so far:
Anyways, that's, so far so close, the future's platform…
Happy coding!
Hernán A. Gatta December, 2005 Are you Ready to Rock?I'm just back from the Launch Tour 2005: AMAZING! A great journey of learning and fun. The welcome time was 7:30. I arrived at 8:25 aprox. There was all the team to get your registration information, the surveys and the little thing to identify you. We went to the upper floor and there was a big breakfast with coffee, cream and some good stuff to eat. At 8:40 we started taking places in the auditorium. They were showing up some videos and there were a couple big balls with some reflective paper inside that we were hitting to ourselves. That was fun. The keynote with Scott started at 9:00. We saw a lot of the new functionality in Visual Studio 2005, SQL Server 2005 and BizTalk Server 2006. At ten we had the first brake. After, we went to a SQL Server 2005 session. It was a bit boring for me because I'm more a developer than an IT Guy. We saw some cool stuff from the management perspective with SQL Server Management Studio. Is a very good app. for managing and developing Queries and others for the different instances of SQL (including also SQL Server 2000) running in different computers; all in a unified Visual Studio looking interface. We saw also some features of the SQL Server Surface Area Configuration app. that lets you modify the configuration for the different services and features running in your different SQL Server instances (including SQL Server 2000) and, of course, that may be running in different PC's. What I found out about this tools, the Tuning Advisor (I did not see this in the sessions) doesn’t start in my SQL installation. I will try to contact Microsoft about this issue. We had a little free breakfast and then we went into a Visual Studio Team System session. I woke up. Is very cool the way you can manage different stuff, all from the same window: you can assign tasks, Check Code Changes, mark tasks as completed and all that management stuff. In addition, they have this handy thing that they call the MSF (Microsoft Solutions Framework). It has principles, and proven practices to deliver guidance to the user for the tasks that he has been assigned to do. They didn’t really show too much about this. Check the Reference section at the end of this Post. They also showed up the Unit Test functionality that gives you the opportunity to check, for example, if the Web Site you’re developing will be able to support a given number of users, before you deploy it definitely. You can also perform Unit Tests on Stand-Alone applications with a Third-Party Add-in for Visual Studio (a Microsoft’s Partner). There’s also the possibility (again, with a Third-Party Add-in) to save kind of ‘Macros’ inside IE and then run them as tests to check the correct function of the Web Interface (not the same as the other Unit Test). This session took more that designated, so we lost part of our other SQL Server session. We saw half of it, showing Reporting Services and then we had a new Visual Studio session about Smart Client Application Development. Is very interesting the way you can easily (yes, even easier) to create common scenarios applications. Now, with a couple clicks, you can have a Data Form in all its luxury showing live data in a DataGrid and a nice ToolStrip with all the needed stuff and more to navigate through the data. They demonstrated too, some of the new stuff included in ASP.NET 2.0, like automated Logins, Data Components, Master Pages and some of the new controls. In this version of ASP.NET we got a new couple components for user authentication called the ‘Login Controls’ which you can simply drag and drop them into your Web Forms and all the validation and all they ‘hard-to-do’ stuff automatically, using the default SQL Server Instance (this is configurable; what I don’t know is if you can talk to Oracle). Master Pages allows you to simply create a page that contains the stuff that has to be there in every single form in your Web Site and by adding Content Placeholders, you can reserve the space that the other forms will be using for customized stuff. Any single thing that you change in a Master Page, will automatically be updated in inherited Web Forms (if you want to update the live Web Site, of course, you need to Re-Build it). Is also introduced with this version of ASP.NET, they concept of Web Parts that, for the simplest example, have an object that contains other controls and applies them a unified color scheme. They also showed ClickOnce Deployment, where you can simply click a ‘Publish’ button to put your application in the server. Whenever a user types the URL in their browser, a page will pop with a brief explanation and the ‘Install’ or ‘Run’ button on it (depending on your publishing configuration). Once the user clicks Run or Install .NET will do the necessary sets-up to run the program. In the case you choose to use ‘Install’, .NET installs in the user’s machine all the necessary components for the application’s runtime. Next time the user opens the application, it will always check for a new update: if there is any, it will be downloaded, installed and ran. Right after this session, we had the Q&A (Question and Answer; of course, the MSDN one). After all this, we got our resource kit including: A Launch t-shirt, Visual Studio 2005 Standard Edition and SQL Server 2005 Standard Edition and an Evaluation Kit of the latest version of Virtual Server. Of course, they also included the entire bunch of marketing papers.
Reference: MSDN: http://msdn.microsoft.com/ Visual Studio 2005: http://msdn.microsoft.com/vstudio/ SQL Server 2005: http://www.microsoft.com/sql/default.mspx MSF (Microsoft Solutions Framework): http://msdn.microsoft.com/vstudio/teamsystem/msf/default.aspx
Happy coding!
Hernán A. Gatta November, 2005 Montreal Microsoft Launch Tour 2005The Microsoft Launch Tour 2005 is coming soon over the Centre-Montreal in a few weeks!!!
They will be presenting the new .NET Framework 2.0 with Visual Studio 2005, SQL Server 2005 and BizTalk Server 2006. I've been already taking a 'sneak peek' to the new features on Visual Studio (VB) and are very interesting: It includes a very handy feature for Code Refactoring that whenever you change the name of a variable, changes all of the references that are in your Solution to it. Also, with features like Extract to Method and Souround With makes it easy to extract code from a routine and put it into another very easily and adding contructions such as With...End With.
I'll be posting some pictures soon (if I can).
See you all there!
Hernán A. Gatta October, 2005 Internet SecurityI passed the last two months of my summer vacations working in the IT Team of a pharmaceutical company. Among others, I was helping to create filters for Spam and Phising. In that time, I realized that people don't know much about these things and they consider this two as annoyance. The only problem is that it goes beyond an annoyance. Spamming is also used to distribute viruses and stuff to track your movements in Internet or even your passwords to, for example, your bank account. Phising, the most important of these, consists of an E-Mail that comes from somebody pretending to be other, such a bank. They write very accurate text that really makes you think that comes from a known sender, but really, is not. They may invent a situation such as a problem with servers and ask you to go to a web page. Now, here you can have a couple things that can happen: They can ask you to put your bank account information and then they can easily steal your money, or they can install software, as I said before, without your knowledge to steal this information in a more silent mode. What to do now? Well, is not possible to have software 100% accurate to filter all this stuff, even if there is people behind checking E-Mail’s that may be suspicious. Always check that you know where the link goes before clicking the Hyperlink. If you don’t know, call the institution that is supposed to be the sender of the E-Mail and check that they are really having this kind of problem. Also, you should suggest to them if they want a copy of the message that you got to see if they can do something about this, due people like you may be experiencing the same thing. Microsoft is also taking their approach to this problem with their own investigation team. Also, be sure to have a Pop-Up blocker installed on your machine from a know distributor, such as Google or MSN (Microsoft). If you have Windows XP installed, be sure to update it to SP2 (if it is possible to) and have their Pop-Up blocker enabled. This SP also comes with a quite nice Firewall and a blocker that prevents you that software is trying to be automatically installed without your knowledge.
You can check out some of this pages if you are interested on this topic: http://www.microsoft.com/security/default.mspx http://www.microsoft.com/athome/security/default.mspx http://www.microsoft.com/athome/security/email/default.mspx http://www.bewebaware.ca/english/default.aspx
Many regards! Hernán A. Gatta October, 2005 Development EraFor first time I was thinking about creating a 'serious' blog entry.
What do I do?
Many regards! Hernán A. Gatta |
|
|