A Better Visual Studio!

3. June 2009 04:21 by Mrojas in General  //  Tags: , , ,   //   Comments (0)

Recently I discovered in MSDN a great addition, a must to for all C# developers. CodeRush Express.

This product was build by DevExpress and it just make it perfect your experience with Visual Studio.

 

For example finding symbols or files, tabbing between references, and more than 20 differente refactorings!!!!

Take at look at this new extension! It’s a absolutely a must.

Extended WebBrowser Control Series:And the WebBrowser keeps going…

Well recently Kingsley has point me to a lot of useful links to improve the ExtendedWebBrowser. However he found another detail. When in Javascript you do something like a:

window.open(‘url’,’window’,’width=200;height=300’);

Those width and height settings were not being considered in the new window. I researched for I while until I found this great link:

HOW TO: Get Width and Height from window.open() Inside a WebBrowser Host by Using Visual Basic .NET

So basicly I follow the sugested code and added logic in my EventSink class:

        public void WindowSetLeft(int Left)
        {
            ///Should I calculate any diff?
            _Browser.Parent.Left = Left;

        }

        public void WindowSetTop(int Top)
        {
            _Browser.Parent.Top = Top;

        }

        public void WindowSetWidth(int Width)
        {
            int diff = 0;
            diff = _Browser.Parent.Width - _Browser.Width;
            _Browser.Parent.Width = diff + Width;

        }
        public void WindowSetHeight(int Height)
        {
            int diff = 0;
            diff = _Browser.Parent.Height - _Browser.Height;
            _Browser.Parent.Height = diff + Height;

        }
So now when the window opens it takes the specified width, heigth, left and top.

As always

HERE IS THE UPDATED CODE

Extended WebBrowser Control Series: WebBrowser Control and window.Close()

I had previously posted an extended version of the WebBrowser Control. This code posted in Opening Popup in a NewWindow and NewWindow2 Events in the C# WebBrowserControl, dealt with some issues when you want to have a form with a WebBrowser and in the enclosed page you have a Javascript code like:

window.open(“ <some url to a page”)

But recently another problem arised. What if you have a Javascript snippet like:

window.close()

OMG!!! Why haven’t I thought about it. Well Kelder wrote me about this problem and he also sent me some of his\her research results:

Solution (Add WebBrowser as unmanaged code):  blogs.msdn.com/jpsanders/archive/2008/04/23/window-close-freezes-net-2-0-webbrowser-control-in-windows-form-application.aspx

Solution (Add WebBrowser using WM_NOTIFYPARENT override):blogs.msdn.com/jpsanders/archive/2007/05/25/how-to-close-the-form-hosting-the-webbrowser-control-when-scripting-calls-window-close-in-the-net-framework-version-2-0.aspx

http://blogs.msdn.com/jpsanders/archive/2007/05/25/how-to-close-the-form-hosting-the-webbrowser-control-when-scripting-calls-window-close-in-the-net-framework-version-2-0.aspx

Solution (Implementation not detailed): social.msdn.microsoft.com/forums/en-US/winforms/thread/1199c004-9eb2-400d-a118-6e06bca9f1f0/

Proposes changing pop-up links to WebBrowser navigate: dotnetninja.wordpress.com/2008/02/26/prevent-opening-new-window-from-webbrowser-control/Close

problem observed (no solution):www.codeproject.com/KB/cpp/ExtendedWebBrowser.aspx

It seams to me that the better solution is to use jpsanders solution, so I created an ExtendWebBrowser_v2 (the following is the modified fragment):

//Extend the WebBrowser control
public class ExtendedWebBrowser : WebBrowser
{
    
    // Define constants from winuser.h
    private const int WM_PARENTNOTIFY = 0x210;
    private const int WM_DESTROY = 2;
    
    AxHost.ConnectionPointCookie cookie;
    WebBrowserExtendedEvents events;

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_PARENTNOTIFY:
             if (!DesignMode) 
             {
                if (m.WParam.ToInt32() == WM_DESTROY) 
                {
                    Message newMsg = new Message();
                    newMsg.Msg = WM_DESTROY;
                    // Tell whoever cares we are closing
                    Form parent = this.Parent as Form;
                    if (parent!=null)
                        parent.Close();
                }
             }
            DefWndProc(ref m);
            break;
          default:
            base.WndProc(ref m);
            break;
        }
    }

The problem that might arise with this solution is that the parent might not be a Form but an user control, etc. For a more general aproach I think I should send a WM_DESTROY directly to the parent, but for most cases it works. I’m attaching the code and a sample page called test0.htm. I hope this helps and rembember you can always donate to programming geeks jejejejeje just kidding

HERE IS THE CODE

List Jobs in Oracle

21. May 2009 06:41 by Mrojas in General  //  Tags: ,   //   Comments (0)

If you have created any schedule jobs or you just need to see what jobs are available in a server you use the dba_jobs table.

The following links provides more details about this view: http://www.praetoriate.com/data_dictionary/dd_dba_jobs.htm

Minimize pain when executing Visual Basic 6 migrations in a Migration Factory Model.

18. May 2009 07:06 by algomez in General  //  Tags: , ,   //   Comments (0)

More and more companies are deciding to migrate their portfolio of Visual Basic 6.0 applications using a Migration Factory Model where knowledge, tools, methodologies and resources are reused.  A successful Visual Basic 6.0 migration to .NET in a migration factory model can bring enormous benefits if executed correctly and a lot of pain if not.

For that reason, here is a list of factors that should be taken into account by your factory teams to minimize pains, risks and ensure success:

  • Use a proven methodology to do software migrations from VB6 to .NET. ArtinSoft can help you review and tune your migration methodology based on years of experience to help mitigate risks and execute cost-effective migrations.
  • Knowledge transfer – Every migration project is different but having a knowledge base of best practices, learnings and manual changes in place and updated with every project, will give you a great tool to successfully complete your projects. Within your migration methodology you need to make sure that your teams are constantly updating this repository, especially during the manual changes phase. Developers won’t have to spend time doing research, trial and error exercises or navigating in the internet since the solution will be in this repository.
  • VBUC customizations are a key part of a migration methodology in a factory model. These customizations will increase the automatic migration rate, minimize manual work on pending projects and ensure that effort, duration and financial goals will be achieved. The knowledge base created during the migration process is the best input for VBUC customizations. You need to ensure that knowledge is gathered and store in a repository at all times.
  • Reengineering versus functional equivalence – Integrating source code migration work with reengineering work will drastically increase the complexity of your migration project. Whenever possible, plan for a staged migration where you achieve functional equivalence first and then work on reengineering tasks.
  • For optimal migration factory team performance, communication is a key. Not always everything is documented so besides the knowledge base, you need to integrate the different teams to learn from each other.
  • Dependencies between projects may minimize the ability to migrate projects in parallel. During the detailed assessment phase you need to work o a migration plan where you clearly define the dependencies between the different projects in your portfolio. You usually do this by using the VBUC in assessment model, application surveys, priorization lists and interviews with application developers.
  • The migration factory requires migration experts especially at early stages of the process. Be aware of training your people in advanced to be productive at early and not middle stages of the migration process.

Changing Software in these Times of Crisis Article at El Financiero

17. May 2009 11:46 by Jaguilar in General  //  Tags: ,   //   Comments (0)

The business-oriented newspaper, El Financiero, just published an article talking about the advantages of performing a migration instead of a manual rewrite. The article talks about how Banamex (part of Citigroup) saved an estimated 80% of the cost when compared to rewriting their 125 applications, totaling over 5 million lines of code. It also talks about the advantages of being in .NET, including how it allows customers to rapidly respond to changes in market conditions.

You can read the original article in Spanish at the following link: Cambiar el software en estos tiempos de crisis or read the Google Translation in English. You can also check out the Banamex/Citigroup case study at the following link: Banamex - Citigroup turns to ArtinSoft to ensure compliance and business continuity through massive migration to C#.NET

Aberdeen Group recognizes ArtinSoft as a key player in the VB 6 migration industry

Aberdeen Group recently published a report titled “Migrating from VB6 to .NET: The challenge of Software Agility in a Volatile Economy”.

The report contains a good summary of the status quo with respect to Visual Basic 6 renewal efforts.  It is based on a survey of 130 organizations at the end of 2008. 

The Aberdeen report contains lots of advice for organizations that are faced with the challenge of upgrading their infrastructure, I think it is worth reading it.

ArtinSoft is very proud to have been recognized as a key player in the Visual Basic migration game along with a number of its outsourcing partners.  This shows once more how our 15 years trajectory in the migration business is our best letter of presentation.

In his summary of the report, Aberdeen analyst Michael Lock also shows how best in class companies have a much greater tendency to use automatic migration tools to support their porting efforts.  During these times of financial uncertainty is more important than ever to minimize the cost of evolving your infrastructure and automation is certainly a good way of doing so.  ArtinSoft approach to automatic migration is aimed at minimizing the cost of reaching functional equivalence while at the same time ensuring that all delivered code is completely .NET native and ready to be evolved to the next level by our customers.  ArtinSoft offers the best balance between cost speed and future insurance.  Jose Aguilar also analyzes some of the conclusions from Aberdeen in this blog post.

If you are deciding what’s your next move with VB6, you should certainly read the Aberdeen report and you should look at our Visual Basic Upgrade Companion 3.0 and our new technical resources site www.VBtoNET.com .

Best-in-Class Companies more likely to use Code Conversion or Automated Porting Tools

8. May 2009 05:51 by Jaguilar in General  //  Tags: ,   //   Comments (0)

Yesterday TechNewsWorld published an article called Planning a Migration Route From Visual Basic 6 to .Net, which discusses some aspects of a report by the Aberdeen Group. The article contains lots of valuable information for those of you considering moving your VB6.0 applications to .NET, by giving a very good idea on the best practices performed by the “Best-in-Class” organizations. I wanted to touch briefly on some of the points from the article, and how it matches our experience helping Fortune/Global 1000 companies upgrade their applications to the latest technology.

Something that is consistent with what we’ve seen is that 33% of the respondents from Best-in-Class and 15% of the “All Others” organizations engage a third party to assist with the migration. We at ArtinSoft, with our Consulting Services group, and along with our world-wide partners, have seen this as a growing trend, and have accumulated a vast a mount of experience that can be leveraged by these organizations to move away from legacy environments.

Also, as part of our migration methodology, we promote a controlled process that first brings your VB6.0 application up to Functional Equivalence in .NET, and then you can use this as a base to enhance an improve your investment. For many clients we also use the extensibility capabilities of the Visual Basic Upgrade Companion to prepare the source code for these enhancements by automating specific architectural modifications required by our customers. These modifications represent an enhancement in itself, and also leave the code ready for further changes by making sure it meets all the practices and coding standards of the organization. The Vertex Omiga and Supervisor Case Studies are a good example in this regard – and we’ve done other migrations with even more important customizations that, unfortunately, I can’t mention directly.

Finally, I want to quote the following text from near the end of the article:

“The research shows that Best-in-Class companies are six times more likely than all other companies to use code conversion or automated porting tools in order to help accelerate part of the migration process.”

You can read our case studies that show this is in fact the case, and we have helped many organizations save time and resources when performing migrations aided by using the Visual Basic Upgrade Companion.

On VB6 and Windows 7 XPM, Part Deux

7. May 2009 14:46 by Jaguilar in General  //  Tags: , ,   //   Comments (0)

Yesterday I blogged about Windows 7’s XP Compatibility Mode, and have some additional pieces of information that I consider interesting if you are considering using it in the future:

  • First of all, not all CPUs would be able to use XP compatibility mode. Take a look at this page over at Tom’s Hardware, and the post over at Ed Bott’s blog. I think the image halfway down the page on the second link speaks for itself – you probably won’t be able to know if the deployment target for your application supports XP Mode or not, which can complicate the installation experience.
  • The second bit of information I want to comment about is the fact that even though applications running under XP mode appear seamlessly alongside Windows 7 applications, they are still running on a virtual machine. From what I’ve seen the boundary is not noticeable to the end user - the application’s shortcuts appear in Windows 7’s start menu, the tray icons appear in Windows 7’s tray, etc. But apps in XP Mode run completely separate from their Win7 counterparts, and the VM itself needs to be patched with its own version of Windows Update, requires specific policies applied to it, etc. It goes without saying that all this adds overhead to managing these type of deployments, and may cause incompatibilities if an app requires interaction with other programs installed on the Windows 7 side (VB6 apps using Office’s COM API is a common example – will you require separate versions of Office, one in the XPVM, and another one on W7 for daily use?).
  • Finally, XP Mode uses Terminal Services and something similar to the RemoteApp mechanism to display applications on the Windows 7 desktop (not sure how other VMMs such as Parallels’ Coherence manage it) . Even though the integration is almost seamless, there are a few quirks here and there that make for an inconsistent experience (drag and drop files, etc), and may affect the performance and L&F of the application.

This post argues that the best solution would be to use Microsoft’s App-V technology to virtualize “XP and older” applications. I agree that would be an ideal solution. But maybe there is a reason why it works like it does – so that you won’t get too comfortable. XPM, IMHO, should be considered as an intermediate step towards moving your legacy apps to the latest technologies.

(As a side note, remember I did a lot of work on Virtualization, and think it is a good way to get the most out of your IT infrastructure resources. XPM, to me, is an excellent idea to start dropping all the legacy parts of Windows without compromising application compatibility, and a smart move at that. )

On Visual Basic 6.0 and Windows 7 XP Compatibility Mode

6. May 2009 14:19 by Jaguilar in General  //  Tags: , ,   //   Comments (0)

As you are probably well aware, along with the release of Windows 7 RC came some big news that affect Visual Basic 6.0 applications: Professional and Ultimate Editions of Windows 7 will feature a Windows XP Mode for backwards compatibility with legacy applications. This means that even if you are using components that have issues with Windows 7, you will be able to run your VB6.0 application on the new operating system, albeit within a Windows XP virtual machine.

It is important to mention that the VB team over at Microsoft was already making sure the IDE and VB6 runtime would work on Windows 7, as I commented before (second comment on that post) based on the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7:

The Visual Basic team is committed to “It Just Works” compatibility for Visual Basic 6.0 applications on Windows Vista, Windows Server 2008 and Windows 7.
The Visual Basic team’s goal is that Visual Basic 6.0 applications that run on Windows XP will also run on Windows Vista, Windows Server 2008 and Windows 7. The Visual Basic team is also committed to the Visual Basic 6.0 development environment running on Windows Vista, Windows Server 2008 and Windows 7.

The objective of XP Mode is clearly to move forward the Windows architecture to the latest technologies, free of all the legacy bits required to maintain compatibility of old applications (read the History posts at the The Old New Thing blog for examples), while at the same time it allows developers to smoothly upgrade their applications without the threat of the application not working in the new OS. It is basically a compromise of old vs. new. And it is very easy to draw parallels between XP Mode and the approach taken by Apple, first with Classic and then with Rosetta, to smooth the transition to new platforms. But as was the case in those scenarios, Classic was eventually phased out, and Rosetta will eventually be as well.

I personally think that this technology may end up being around for a while, and may even end up included in the next versions of Windows if there is enough customer demand for it. This has to be the same technology used in their Microsoft Enterprise Desktop Virtualization (MED-V) solution, targeted towards enterprise customers:

“Microsoft Enterprise Desktop Virtualization (MED-V) provides deployment and management of virtual Windows desktops to enable key enterprise scenarios. MED-V 1.0 helps enterprises upgrade to the latest version of Windows even when some applications are not yet compatible.”

Even in the scenario that XP Mode is supported for a long time, you still have to consider it as something that can be used for a smooth transition while you upgrade your applications to the .NET Framework, and not as an excuse for not upgrading. It can help you plan a gradual migration, were you first start migrating certain modules while leaving others in VB6, with tools like the Interop Forms Toolkit. And keep in mind that even though the application will run, the IDE is simply not supported anymore and neither are most controls that cause compatibility issues. And at the same time you will be missing the benefits of using the latest technologies and the increased productivity of the .NET Framework.

Visual Basic migratioon now faster than ever!

6. May 2009 09:44 by Fzoufaly in General  //  Tags: , , , ,   //   Comments (0)

Today ArtinSoft launched the Visual Basic Upgrade Companion 3.0 both for our Enterprise and Developer Editions.  This latest release of the best (I am biased!) Visual Basic migration tool in the world is focused on reducing the total effort of a migration project.  Together with the conversion tool release we also revamped its companion technical site http://www.vbtonet.com/ .  This site, which will be continuously updated in the following weeks, is the perfect side help to any person that needs to complete a migration project.  It contains everything from a getting started guide to how-to articles with advanced migration topics.

At ArtinSoft we are truly proud of this release and we continue to be fully committed to support our customers in their transition from VB 6 to Visual Basic .NET or C#. 

Specifically, here are the latest additions to the VBUC 3.0.  Click here to get a trial of this exciting product.

VBUC 3.0 New Features

 Source Code Conversion Features
  • Windows API and 'Declare' Support
    VBUC 3.0 introduces support for external DLL function declarations and invocations. A vast research was performed to identify the correct way of declaring and passing parameters and return types for primitives, classes, enums, structs, fixed lenght strings, arrays and combinations of these types.
  • Increased Support for Windows Common Controls Conversion
    VBUC 3.0 introduces a substantial amount of improvements for the conversion of Windows Common Controls to native .NET controls.  An extensive effort was performed to identify and resolve issues related to these components which are present in most VB6 applications. The main improvements are related (but not limited) to the following controls:  ImageList, ListView, StatusBar, Toolbar, TreeView.
  • Public Class Instantiation Models Support
    Public classes in ActiveX EXE/DLL projects may have different instantiation models (multiuse, singleuse, etc.) To achieve the same behavior in .NET a whole conversion solution was implemented and incorporated into VBUC 3.0.
  • Default Property Resolution Through Helper
    The VBUC contains a new helper class designed to resolve several late binding issues that are not solved by the typing mechanism. This solution significantly reduces compile errors and EWIs while providing higher functional equivalence.
    This solution resolves the EWIs related to late-binding and default property issues which represent around 50% of known issues from older versions.
  • Data Access Conversion Improvements
    The data access conversion to ADO.NET with System.Data.Common has been a very popular feature from the previous VBUC versions.  VBUC 3.0 introduces several improvements to this feature. It includes enhancements to the helper classes functionality as well as additional members coverage (clone, sort, getrows and many others)
  • IsMissing Support
    VBUC 3.0 introduces support for the IsMissing function. Since VS.NET doesn't include the concept of missing parameters, VBUC now generates a code pattern that produces the same behavior by taking advantage of nullable types and overloading.
  • NotUpgradedHelper for Not-Upgraded Statements and Members Handling
    A very common problem with older versions of VBUC was the handling of NotUpgraded members and statements.  They were usually generating compile or runtime errors that made the post-VBUC manual work more difficult.
    VBUC 3.0 introduces a helper class to report and handle the usages of not supported elements while avoiding compile and runtime errors.
  • Multiple improvements to existing features
    Around 450 individual improvements were implemented for VBUC 3.0.  Most of them are related to providing increased automation and enhance the resulting code quality, others are related to other areas such as robustness and graphical interface.
 Performance Improvements
  • Speed Boosting
    For VBUC 3.0 several time performance improvements were implemented to achieve a substantial improvement, reducing to 50% the required time to perform an upgrade process.  Additional time improvements could be experienced when converting large projects which used large amounts of memory.
  • Reduced Memory Requirements
    Memory usage was also significantly improved.  Based on tests over medium projects we estimate around a 30% improvement.  It is estimated that more significant improvements will be experienced with bigger projects.
 Assessment
  • Assessment Tool Integration
    The VBUC Assessment Tool functionality has been incorporated into the VBUC. Users can now execute the assessment process from the VBUC main window. One important advantage of this approach is that users can solve migration warnings before executing the assessment process, allowing the obtention of better quality information.
  • Additional Assessment Reports
    Two additional reports have been included into the integrated assessment process:
    • An advanced dependency analysis that shows internal-dependency trees per project.
    • A shared and potential-duplicate files report.  It includes the following sub reports:
      • A shared files report indicating which projects include each shared file.
      • A potential-duplicate files report indicating which projects include each presumed duplicate file.
      • A projects list sorted topologically with LOC counts for each project where shared and potential-duplicate files are counted only in the first project they occur.
 Other Features
  • Graphical Interface Status Information
    The VBUC 3.0 graphical user interface shows detailed information for each project.  It shows sizes, progress and status by project and by source file detail.
    It helps the user to understand the volume of work required for each project and its current upgrade progress as well as to identify any eventual pieces of code that may have not been fully converted.
  • EWIs and Upgrade Report Improvements
    Several modification have been implemented to the upgrade messages generated by VBUC into the generated code.
    • UpgradeReport Synchronization: for previous versions of VBUC the UpgradeReport didn't show properly all the EWIs generated into the upgraded code.  For VBUC 3.0 this report includes all the EWIs generated in the converted code plus the global EWIs that are not included into the target source code.
      In addition, the accumulated counts per section where also improved to show the correct amount of occurrences.
    • Links to Online Documentation: Hiperlinks are added for each EWI to its corresponding online documentation in the new www.vbtonet.com site.
    • Restructuring: The EWI message structure was modified to show the numeric code first.  Also some messages where improved and some EWIs were removed or merged.
  • Increased Robustness and Logging
    Several actions were taken to handle and recover from unexpected situations.  In the event that any exceptional situation may arise, an window is displayed explaining the issue and providing the user with options to generate debugging information that can be sent to ArtinSoft support for diagnosis and recommendations.
 Products, Versions and License Types Formalization
  • Developer and Enterprise Editions
    The second version of VBUC Developer Edition is released with VBUC 3.0.  The development process has been formalized to syncronize the maintenance and releases of both versions.  The Developer Edition includes an improved activation and licensing model as well as an easier on-line sale mechanism.
  • Trial Licenses
    Both Developer and Enterprise editions support trial licenses.  Developer trials are now available for download in the Artinsoft web site.
  • ASP Upgrade Engine Integration
    The ASP Upgrade Engine has been integrated into the VBUC 3.0.  It is now installed together with VBUC.  The license file can still restrict the use of ASP upgrade abilities though.
  kick it on DotNetKicks.com

Visual Basic Upgrade Companion 3.0 Official Release

6. May 2009 07:34 by Jaguilar in General  //  Tags: ,   //   Comments (0)

Today we formally released version 3.0 of the Visual Basic Upgrade Companion, including both the Enterprise and Developer Edition of the migration tool. This is a significant new release, which has improved the efficiency of the conversion tool by reducing the amount of work required to the the applications to functional equivalence by over 30% (and more in some cases). All migration improvements are based on the feedback from the experiences of both our clients and our own consulting team, and we are very happy the changes have such an effect. I already talked about specific new features on a previous post.

Also, today we went live with a new companion website to the VBUC at www.vbtonet.com. This repository of information should help you in all aspects of the migration, and includes both best practices for, for example, finding customization opportunities in the code, and both overall strategies and detailed examples on how to solve migration issues. This site is tightly integrated with the VBUC, and migration issues identified in the code by the tool will contain a link to latest information to help you solve the issue, like the following example:

'UPGRADE_TODO: (1067) Member MyMember is not defined in type Variant. More Information: http://www.vbtonet.com/ewis/ewi1067.aspx

This library of information will continue growing over time, so make sure you come back often during your migration project to check out the latest content.

You can read the official press release here.

Extended WebBrowser Control Series: Opening Popup in a NewWindow

In a previous post, i had published an “Extended Version” of the WebBrowser control
that gave you access to events like the NewWindow2.
This event that is not public in the common WebBrowser control allows you to intercept
the NewWindow event but gives you the posibility to setup the the ppDisp property witch sets
a pointer to the WebBrowser where the new window will be open.

So i setup a small example using this “ExtendedBrowser”.

I created a simple page (well really it was my wife, I know about transport-layer, C++, bits etc, but I never remember HTML syntax):

<html>
<body>
<H1> This is sample page to test opening a pop up in a new form </H1>
<input type="button" onclick="window.open('test0.htm')"/>
</body>
</html>

And created a simple form like in the following picture:

image

 

Instead of using a WebBrowser control i just used an ExtendedWebBrowser from my previous post.

And added code like:

        private void extendedWebBrowser1_NewWindow2(object sender, NewWindow2EventArgs e)
        {
            //Intercepting this event will allow us to create a new form in which
            //we will open the new webpage, to do that we must set the ppDisp property
            //of the NewWindow2EventArgs
            FormWithExtendedBrowser form1 = new FormWithExtendedBrowser();
            form1.Show();
            e.PPDisp = form1.extendedWebBrowser1.Application;
        }

When I run the code , it now opens the pop up in my form:

image

But test if for yourself! :) HERE IS THE CODE

VB6 Migrating MouseIcon Property

30. April 2009 13:17 by Mrojas in General  //  Tags:   //   Comments (0)

In VB6 you can have code like:

Private Sub Command1_Click()
    Dim x As StdPicture
    Set x = LoadPicture("C:\setup.ico")
    Me.MouseIcon = LoadPicture("C:\setup.ico")
    Me.MousePointer = ccCustom
End Sub

 

How can you migrate that to .NET??????

Well maybe with a helper like the following can help:

using System; 
using System.Windows.Forms; 
using VB6 = Microsoft.VisualBasic.Compatibility.VB6.Support;

namespace Project2
{
    internal partial class Form1
        : System.Windows.Forms.Form
        {
        
            private void  Command1_Click( Object eventSender,  EventArgs eventArgs)
            {
                System.Drawing.Image x;
                x = System.Drawing.Image.FromFile("C:\\setup.ico");
                this.Cursor = CursorHelper.CreateCursor(x);

        }
            [STAThread]
             static void  Main()
            {
                    Application.Run(new Form1());
            }
        }




  public class CursorHelper 
  {
      private struct IconInfo
      {
        public bool fIcon;
        public int xHotspot;
        public int yHotspot;
        public IntPtr hbmMask;
        public IntPtr hbmColor;
      }
  
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern IntPtr CreateIconIndirect(ref IconInfo icon);

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    [return: System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.Bool)]
    static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

    private static Cursor CreateCursor(System.Drawing.Bitmap bmp, int xHotSpot, int yHotSpot)
    {
        IconInfo tmp = new IconInfo();
        GetIconInfo(bmp.GetHicon(), ref tmp);
        tmp.xHotspot = xHotSpot;
        tmp.yHotspot = yHotSpot;
        tmp.fIcon = false;
        return new Cursor(CreateIconIndirect(ref tmp));
    }


    public static Cursor CreateCursor(object picture)
    {
      if (picture is System.Drawing.Bitmap)
          return CreateCursor(picture as System.Drawing.Bitmap, 3, 3);
      else 
      {
          System.Drawing.Image image = null;
          IntPtr iunknown = System.Runtime.InteropServices.Marshal.GetIUnknownForObject(picture);
          if (iunknown == IntPtr.Zero)
          {
              throw new Exception("Unsupported format");
          }
          else 
          {
              Guid guidIPicture = new Guid("7BF80980-BF32-101A-8BBB-00AA00300CAB");
              Guid guidIPictureDisp = new Guid("7BF80981-BF32-101A-8BBB-00AA00300CAB");
              IntPtr testIntPtr = IntPtr.Zero;
              if (System.Runtime.InteropServices.Marshal.QueryInterface(iunknown,ref guidIPicture,out testIntPtr)==0)
              {
                  image = Microsoft.VisualBasic.Compatibility.VB6.Support.IPictureToImage(picture);
              }
              else if (System.Runtime.InteropServices.Marshal.QueryInterface(iunknown,ref guidIPictureDisp,out testIntPtr)==0)
              {
                  image = Microsoft.VisualBasic.Compatibility.VB6.Support.IPictureDispToImage(picture);
              }
              if (image == null)
              {
                  throw new Exception("Unsupported format");
              }
              using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image))
              {
                  return CreateCursor(bitmap, 3, 3);
              }
          };
           
          
      }

    }

  }

}

Get the Week Number in C#

30. April 2009 10:56 by Mrojas in General  //  Tags: , , ,   //   Comments (0)

Here is some examples of how to determine the WeekNumber of a given Date

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

        object index = DateTime.Now;
        int res = 0;
        //0    First day of year
        res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
        Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstDay, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

        //1    (Default) First four day week from Sunday
        res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
        Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);

        //2    First four day week from StartOfWeek
        res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstFourDayWeek, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

        //3    First full week from Sunday
        res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);
        
        //4    First full week from StartOfWeek
        res = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(
                Convert.ToDateTime(index), System.Globalization.CalendarWeekRule.FirstFullWeek, System.Globalization.DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);


        }
    }
}

Visual Basic Upgrade Companion 3.0 Release Candidate available

A couple of days ago we made available the final release candidate for version 3.0 of both the Visual Basic Upgrade Companion Enterprise Edition and Developer Edition. You can now directly download a trial of the VBUC Developer Edition on the trial download page, or request a trial of the Enterprise Edition on this page.

I need to mention an obligatory disclaimer saying this is the final Release Candidate, so, unless we find something at the last minute, it should be the same version officially released within a week or so. We need your help to verify we won’t find anything by downloading it and trying it out. :)

I already covered some of the features of this version on a previous post. There was significant improvements in several areas from version 2.2, which should help you achieve even greater productivity on your migration projects.

Coming Soon: Visual Basic Upgrade Companion Version 3.0 with Enhancements in Automation, Features and Code Quality

20. April 2009 11:52 by Jaguilar in General  //  Tags: ,   //   Comments (0)

As I blogged before, the release of the VB Upgrade Companion v3.0 is due within the next few weeks. In this version we concentrated on three major areas:

  • Automation: We analyzed the data from several million lines of code to determine the most common causes of manual intervention, and, by making some strategic changes to the way the code is generated, managed to reduce the amount of both EWIs (Error, Warning and Information messages) and compilation errors significantly on large (>1 million Lines of Code), complex applications. Also, depending on the VB6 features used, the VBUC now automates the migration of even more smaller applications and components completely!
  • New Features: The VBUC v3.0 also contains additional features, such as the migration of the IsMissing statement and increased support for additional third party components. We are also integrating the VBUC with brand new online documentation resources that should help you as you perform the migration!
  • Code Quality: The Visual Basic Upgrade Companion always tries to generate high-quality code that looks as if it was originally written in .NET. This increases the maintainability of the migrated application, and allows developers joining the project at a later date to very quickly start working on the codebase. Because of the great differences between Visual Basic 6.0 and VB.NET/C#, however, achieving this goal is not always possible. For this release we continued increasing the quality of the migrated code, including minor refactorings to control structures, and adding things like support for translating additional error handling statements to try/catch statements.

All of these was supported by some significant changes we did under the hood, which should make it easier to add new features in the future (including customer-specific customizations) and reduced the memory footprint significantly, while increasing migration speed. Watch this space for more details as the release date approaches!

VB6 AddressOf operator Migration

31. March 2009 09:14 by Mrojas in General  //  Tags:   //   Comments (0)

I was looking into ways to migrate something like the AddressOf operator in VB6. I read in some forums that I could use a delegate, but I hadn’t seen a code sample, so I started googling until I found this great post.

It provided a great example of how to pass a pointer to a function. I am attaching here the code so you can benefit from this too.

 

Remember to put the Working directory pointing to the output directory of the C DLL. In my case it is

image

The idea in general is like this:

/// <summary>
/// Simple callback function.
/// </summary>
/// <param name="a">Some integer parameter.</param>
public delegate void CBFUNC(int a);

/// <summary>
/// Demo of a simple callback.
/// </summary>
/// <param name="f">Function to call back to</param>
/// <param name="a">Parameter which will be returned through the callback</param>
[DllImport("c_test_lib.dll")]
public static extern void DoCallback(CBFUNC f, int a);

DOWNLOAD CODE

Bittable What????

As vb6 migration experts in our company we deal everyday with a lot of issues around Interop and serialization.

One important thing to note is the concept of “Bittable Types”. I’m not making up terms. Those terms actually exist. Just see this link in MSDN.

In a few words, a bittable type is a type that has the same representation in managed and unmanaged code.

Why in earth is that important at all?

Because if you are calling that great C++ DLL implemented some years ago that just works ok, you won’t be able to pass a NON-Bittable type because that DLL will expect a binary representation different from that in the .NET virtual machine.

This is also an issue in other scenarios like:

  • Serializing content to files
  • Sending messages through messaging mechanisms like named-pipes or sockets.

Well, we have just introduced the problem so now let’s think on a nice solution for this problem.

Well Bittable Types are:

The following types from the System namespace are blittable types:

 

So now let’s look at a couple of non-BITTABLE types

DateTime

To test this differences let’s make a small test in VB6 and write a Date value to a file:

 

Private Sub SaveDateToFile()
    Open "C:\test1.bin" For Binary Access Write As #1
    Dim d1 As Date
    d1 = "1/1/2009"
    Put #1, , d1
    Close #1
End Sub

Now let’s make a quick program in Vb.NET

 

Sub Main()
        Dim f As System.IO.FileStream = System.IO.File.Open("C:\test2.bin", IO.FileMode.Create, IO.FileAccess.Write)
        Dim fw As New System.IO.BinaryWriter(f)
        Dim d As Date
        d = Convert.ToDateTime("1/1/2009")
        Dim val As Long = d.ToBinary()
        fw.Write(val)
        fw.Close()
        Main2()
    End Sub

 

If we compare these files we will have:

image

So the values are obviously different. This is because VB6 Date are stores with the OLE Automation DateFormat

So let’s change the C# code for something like:

 

    Sub Main2()
        Dim f As System.IO.FileStream = System.IO.File.Open("C:\test3.bin", IO.FileMode.Create, IO.FileAccess.Write)
        Dim fw As New System.IO.BinaryWriter(f)
        Dim d As Date
        d = Convert.ToDateTime("1/1/2009")
        fw.Write(d.ToOADate())
        fw.Close()
    End Sub

And now when we compare the files we will have:

image

 

So to make your Date values compatible with VB6 format you must user the DateTime method .ToOADate. Now if you are calling a DLL that expects a Date value in the same format used by VB6 then you will have to do this:

 

        Dim d As Date
        d = Convert.ToDateTime("1/1/2009")
        Dim handle As System.Runtime.InteropServices.GCHandle = System.Runtime.InteropServices.GCHandle.Alloc(d.ToOADate(), Runtime.InteropServices.GCHandleType.Pinned)
        Dim memory_address As IntPtr = handle.AddrOfPinnedObject()
        Try
            APICall(memory_address)
        Finally
            d = DateTime.FromOADate(System.Runtime.InteropServices.Marshal.ReadInt64(memory_address))
            handle.Free()
        End Try  

 

String

Most of the time you wont have to deal with String marshalling because adding marshaling tags to your API call solves most of the problems, but if you arent that luckyly then you might do something like:

IntPtr ptrToStringVar = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(strVar);
try
{
   APICall(ptrToStringVar);
}
finally
{
strVar = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptrToStringVar);
System.Runtime.InteropServices.Marshal.FreeHGlobal(ptrToStringVar);
}

NOTE: if you have an API that might return an string with /0 characters you must call the API with System.Runtime.InteropServices.Marshal.PtrToStringAnsi(ptrToStringVar,size), if you do that the Framework will take in consideration the size bytes at the ptrToStringVar memory address.

 

Double and Singles

At least between VB6 and VB.NET the double and single types follows the same format. Well, at least, that is the result of my tests.

Try it yourself, the following shows a simple test for double variables:

VB6

Private Sub SaveDoubleToFile()
    Open "C:\test1.bin" For Binary Access Write As #1
    Dim d1 As Double
    d1 = 1.123
    Put #1, , d1
    Close #1
End Sub

Sub Main()
    SaveDoubleToFile
End Sub

 

.NET

Module Module1

    Sub Main()
        Dim f As System.IO.FileStream = System.IO.File.Open("C:\test2.bin", IO.FileMode.Create, IO.FileAccess.Write)
        Dim fw As New System.IO.BinaryWriter(f)
        Dim d As Double
        d = 1.123
        fw.Write(d)
        fw.Close()
    End Sub


End Module
 

So you could make an api call in those cases with something like:

Dim handle As System.Runtime.InteropServices.GCHandle = System.Runtime.InteropServices.GCHandle.Alloc(d, System.Runtime.InteropServices.GCHandleType.Pinned)
Dim ptr As System.IntPtr = handle.AddrOfPinnedObject()
Try
    APICall(ptr)
Finally
    handle.Free()
End Try

Upcoming features in the Visual Basic Upgrade Companion version 3.0

We are currently wrapping up all development effort to focus on the final testing and stabilization of the next version of the Visual Basic Upgrade Companion, both Enterprise and Developer Editions, version 3.0. For this version we focused more on architecture improvements, preparing the code base for more significant upgrades in the future. We still we managed to add some great features such as:

  • Enhanced resolution of default properties: By both improving the typing engine of the VBUC and generating additional code for runtime resolution of default properties, we were able to reduce the total amount of EWIs present in the code by 30%!
  • Improved support for API Calls: Most API calls should now work correctly. There are still a couple of issues, but they should be sorted out by the final release
  • IsMissing migration: We now correctly support the migration of the IsMissing statement.
  • Enhanced support for the migration of common controls, such as Imagelist, Listview, Statusbar, Toolbar and Treeview, to native .NET components. We now correctly convert most functionality of these controls to .NET
  • A greatly enhanced Assessment Mode to better estimate the effort required to perform a migration project
  • Significant performance improvements and memory footprint
  • Over 150 code generation improvements based on feedback from projects we’ve done, our clients and partners

We are currently conducting a limited Beta program for the VBUC Developer Edition v3.0. If you are interested in participating, drop me a line and I’ll get back to you with further instructions.

Edit: The upcoming version of the VBUC will be version 3.0 - this release represents a leap in the level of automation and additional features we managed to squeeze in, and thus deserved a new major version number. I will post additional details on the different features as the final release date approaches.

Categories