Fix errors for atlbase.h and atlthunk.lib not found in Visual C++ 2010 express

29. June 2011 03:53 by Mrojas in General  //  Tags: , , , , ,   //   Comments (0)

If for some reason you have to use VC++ Express and you have projects that use ATL,
you will get annoying error messages like:

LINK : fatal error LNK1104: cannot open file 'atlthunk.lib'

Just follow the steps in this post and you well be ready to go:

http://www.quantcode.com/modules/smartfaq/faq.php?faqid=99

Hyper-V: Failed to create partition: Insufficient system resources exist to complete the requested service. (0x800705AA)

21. June 2011 09:15 by Mrojas in General  //  Tags: , , , , ,   //   Comments (0)

Well I was trying to create a VM Role for Azure and I got this error from my Hyper-V machine.

After some tests I hit my head and got to a clear conclusion: Silly me how could have I missed it.
The problem was I set up the VM with more memory that the available in Hyper-V, so
I changed this setting and my VM just worked!!

If I was not able to transfer any sense of sarcasm, I think that this is really hard to understand error message. Confused smile

Program database manager mismatch

21. June 2011 08:58 by Mrojas in General  //  Tags: , , , , , , ,   //   Comments (0)

I was playing around with dumpbin trying to figure out some problems with a 32-bit dll and in order to make
dumpbin run from the command line I just copied the mspdb100.dll file to
C:\Program Files\Microsoft Visual Studio 10.0\VC\bin>

Something simple right! No harm can be gotten from something like that? WRONG!!!

After that some of my C++ project stop compiling with the annoying message: Program database manager mismatch!!.

Luckily I remembered copying that file, so I just gave it a try, and guest what? Everything works fine now.

Well I’m posting it just a reminder that for VS C++ you must put attention on all the details Smile

VB6 Windows Service

2. June 2011 04:30 by Mrojas in General  //  Tags: , , , , , , , ,   //   Comments (0)

How do you write a Windows Service in VB6?

Althought this is not a recommend practice due to the stability issues and VB6 support, if for
any reason you need to do this I provide a guide of how to do that in VB6 and how do the same thing
in VB.NET and C#.

Using the NTSVC.ocx

This is an OCX implement by Mauricio Ordonez some time ago.
It is very simple to use. You just drop it on a form and add some code to your VB6.

Example: VB6 Form with the NTSVC.ocx control

Private Sub Form_Load()
Me.Visible = False
    Dim strDisplayName As String

On Error GoTo Err_Load

    strDisplayName = NTService1.DisplayName
   
    If Command = "-install" Then
        ' Enable interaction with desktop.
        NTService1.Interactive = True
       
        If NTService1.Install Then
MsgBox strDisplayName & " installed successfully"
        Else
            MsgBox strDisplayName & " failed to install"
        End If
        End
   
    ElseIf Command = "-uninstall" Then
        If NTService1.Uninstall Then
            MsgBox strDisplayName & " uninstalled successfully"
        Else
            MsgBox strDisplayName & " failed to uninstall"
        End If
        End
   
    ElseIf Command = "-debug" Then
        NTService1.Debug = True
   
    ElseIf Command <> "" Then
        MsgBox "Invalid command option"
        End
   
    End If
   
    ' Connect service to Win32 services controller.
    NTService1.StartService
   
Err_Load:
    ' Error starting service
   
End Sub


Private Sub Timer1_Timer()
MsgBox "hola"
End Sub

 

NOTE: Remember that VB6 is not a supported platform and that even if it is true
that you can still run VB6 code in Windows Vista and Windows 7 MS does not support this
platform anymore.

How can I convert my VB6 service to .NET?

To create a Windows Service in VB.NET follow this steps.

1. First you need to create a Windows Service Project:

a. Open Visual Studio 2010

b. Go to the File\New\Project….

c. Select the Windows Service Template

d. And you just put your code in the OnStart method:

Public Class Service1

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        ExecuteWindowsServiceCode()
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub

    Private Sub ExecuteWindowsServiceCode()
        'TODO Add Some Code
    End Sub

End Class
 

e. Another typical thing to do in Windows Service is to add a Timer Control, you you can have
your windows service performs some actions every number of seconds. To do that, drag a
Timer Control on your Service component, execute the Start method of the timer control on the OnStart method and
handle the Tick event:

 

 

 

Public Class Service1

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.
        Timer1.Start()
        ExecuteWindowsServiceCode()
    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
        Timer1.Stop()
    End Sub

    Private Sub ExecuteWindowsServiceCode()
        'TODO Add Some Code
    End Sub

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        MsgBox("Viva la vida Loca!")
    End Sub
End Class

If you need to recover some of your code from your VB6 project, download our Visual Basic Conversion Tool VBUC tool.

 

How do I Install my Windows Service?

In general you just need to use the command line utility installutil.exe for more details see this other post.

From VB6 to WP7: App Config for WP7 Applications

27. May 2011 04:33 by Mrojas in General  //  Tags:   //   Comments (0)

 

When you start moving applications to the Silverlight and the Cloud
it wont belong for you to start wondering if you can move your applications
to be able to work on mobile devices, and it is a natural thing to wonder.

One of the best features of Artinsoft conversion tools from VB6 and other languages
to .NET is that we generate very clean code, it is not a runtime as much as possible
it is plain vanilla .NET code. And that allows us to easily move to other .NET platforms
using our evolution framework.

Moving a VB6 or Winforms applications will require some libraries not currently present in WP7,
one of those libraries are the one to read from a Config file. If you are in need of this functionaly
Alex Yakhnin has provided a good port of the Mobility Configuration block that will allow you to do something as simple as:

/ Get section
ApplicationSettingsSection section = (ApplicationSettingsSection)ConfigurationManager.GetSection("ApplicationSettings");
// Display values
this.textBlock1.Text = section.AppSettings["localServer"].Value;
this.textBlock2.Text = section.AppSettings["remoteServer"].Value;

The Mango is close!!!

24. May 2011 03:04 by Mrojas in General  //  Tags: , , , , , ,   //   Comments (0)

Jejeje. Well if you are a phone developer, either an iOS guy who is thinking on offering
his/her apps in the MS Marketplace or just someone with a great interest in Windows Phone
then you should know what mango is.

Mango is a new update for the Windows Phone, and it will mean a lot for developers,
because if you already liked WP7 you will love MANGO.

 

VIDEO LINK 

 

Mango means HTML5 yes!
Mango means Multitasking!
Mango means Hands-free messaging, did you ever
wanted to send SMS without using your fingers, now you can!

I don’t think is mentioned in this video but Mango is also SQLCE a great alternative
for Android and iPhone developers who were using sqllite.

Convert iOS to Windows Phone 7; SQLite

23. May 2011 05:00 by Mrojas in General  //  Tags: , , , , , , , ,   //   Comments (0)

In iOS SQLite is part of the Core Services and you can easily integrate it in your applications.
Even in Android you have access to this platform.

If you don’t know what SQ Lite this is a quote from www.sqlite.org:

“SQLite is a software library that implements a self-contained, serverless, zero-configuration,transactional SQL database engine. SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain.“

So what is your equivalent in WP7. Well if you want to wait the Mango Release of Windows Phone 7
will include Sql Server Compact Edition, so that will provide a fairly good and supported platform, but
in the meantime I recommend that you check http://wp7sqlite.codeplex.com/

Interop Structures to UnManaged Dlls

For VB6 applications it is common to rely on OS or Kernel API Calls. Some of those APIs might
need you to send data back and for the native API.

Marshalling in .NET can be complicated and bothersome. I have published several posts about
interop. But it usually depends on adding several marshalling attributes and even tricks specially for
fixed strings.

So I decided to provide a more a simpler approach for conversion. In this approach you just need to things:

1. Your VB6 types or structs will be mapped to .NET classes
2. All VB6 type or struct fields will be mapped to public fields
3. An attribute must be used on those fields to indicate the field length, for arrays or strings.
4. Extension methods .AsString() .SetFromString and .GetClassLength will handle all the complexities of setting the struct fields.

Let’s see an example:

Type EmployeeRecord
    FirstName As String * 5
    LastName As String * 5
End Type

That vb6 type will be mapped in .NET following this approach to:

    public class EmployeeRecord 
    {
        [FixedLength(5)]
        public string FirstName = "Mau";
        [FixedLength(5)]
        public string LastName = "Rojas";

    }

You can then simple use that class in .NET

var emp = new EmployeeRecord {FirstName="Mauricio",LastName="Rojas"} ;
var str = emp.AsString();
//This str value will be "MauriRojas" the helper extension methods
// .AsString and .SetFromString will handle setting the internal class fields

All that is very good but how is this used in Marshalling?? Well very simple. Let’s say you have a Dll called foo.dll
with a function foo that receives an EmployeeRecord:

        [DllImport("foo.dll")]
        public static extern int foo(IntPtr Struct);

Then if you want to call that function you will do something like:

            var emp = new EmployeeRecord { FirstName="Ann",LastName="Smith"};
            string str = emp.AsString();
            var ptr = IntPtr.Zero;
            ptr = Marshal.StringToBSTR(str);
            //or 
            ptr = Marshal.StringToHGlobalAnsi(str);
            //or
            ptr = Marshal.StringToHGlobalAuto(str);
            //or
            ptr = Marshal.StringToHGlobalUni(str);

            //And call the native function
            foo(ptr);

If the function modifies the structure and you want to reflect those changes then you will do something like:

str = Marshal.PtrToStringAnsi(ptr,typeof(EmployeeRecord).GetClassLength())
emp.SetFromString(str);

This solution can also be applied for more complex structures. For example:

    public class EmployeeRecord 
    {
        [FixedLength(5)]
        public string FirstName = "Mau";
        [FixedLength(5)]
        public string LastName = "Rojas";

    }

    public class Record1
    {
        public int field1;
        [FixedLength(10)]
        public string field2 = "";
        public EmployeeRecord rec = new EmployeeRecord();
    }

    public class GeneralInfo
    {
        public int field1;
        [ArrayLength(5)]
        [FixedLength(2)]
        public String[] countrycodes = { "cr","es","mx","pa","ni"};
        [FixedLength(2)]
        public EmployeeRecord[] employees;
    }

If you want to try it out this is the link to the CODE

Windows Azure Connect Endpoint Software versions supported

17. May 2011 08:55 by Mrojas in General  //  Tags: , , , , , , , , , , , , ,   //   Comments (0)

A common doubt when using you want to use Azure Connect is which platforms does it support.
Remember that in order to establish a VPN between your On-Premises computer and a Web/Worker Role
you need to install a client pieces of software.
But which are the supported platforms.
Normally what you can do is just download it and then if you get something like
”Not a valid Win32 application” it means that it is not supported.

From the MSDN site (http://msdn.microsoft.com/en-us/library/gg508836.aspx in the Prerequisites section ) it is stated that:

Windows Azure Connect supported platforms:

Windows 2003 and Windows XP are not supported.

It is supported in Windows Vista, Windows 7, Windows 2008 and Windows 2008 R2

Getting the IP Address of the client in a Windows Azure Role

Are que getting null or empty with some Request.ServerVariables

When you convert your ASP application to run on Windows Azure it is a good
to put attention to the methods that are used to get the user IP Address.
Normally the recommendation will be to use Request.UserHostAddress however
our friend Alex has found that this property can return null or empty.

After some research Alex found that there are several scenarios under which
you must check both the REMOTE_ADDR and the HTTP_X_FORWARD_FOR server variables:

More info:
http://forums.asp.net/t/1138908.aspx and
http://meatballwiki.org/wiki/AnonymousProxy

A possible code snipped that can provide a value for the client address can be:

public static string ReturnIP()
        {
            var request = System.Web.HttpContext.Current.Request;
            var ServerVariables_HTTP_X_FORWARDED_FOR = (String)request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            var ServerVariables_REMOTE_ADDR = (String)request.ServerVariables["REMOTE_ADDR"];
            string ip = "127.0.0.1";
            if (!string.IsNullOrEmpty(ServerVariables_HTTP_X_FORWARDED_FOR) && 
                !ServerVariables_HTTP_X_FORWARDED_FOR.ToLower().Contains("unknown"))
            {
                ServerVariables_HTTP_X_FORWARDED_FOR = ServerVariables_HTTP_X_FORWARDED_FOR.Trim();
                string[] ipRange = ServerVariables_HTTP_X_FORWARDED_FOR.Split(',');
                ip = ipRange[0];
            }
            else if (!string.IsNullOrEmpty(ServerVariables_REMOTE_ADDR))
            {
                ServerVariables_REMOTE_ADDR = ServerVariables_REMOTE_ADDR.Trim();
                ip = ServerVariables_REMOTE_ADDR;
            }
            return ip;
       }

In the previous code the HTTP_X_FORWARDED_FOR value is examined first and if it is not null or unknown then ip address of the client
is gotten from there.

Converting from VB6 or Winforms to Context-Sensitive Help in Silverlight

If you were in VB6 HelpContextID will be familiar for you (http://msdn.microsoft.com/en-us/library/aa267690(v=vs.60).aspx). In those sweet VB6 days all you had to do was:

Private Sub Form_Load ()
   App.HelpFile = "VB.HLP"
   Frame1.HelpContextID = 21004   
   Text1.HelpContextID = 21001
   Form1.HelpContextID = 21005
End Sub

And each time you pressed the F1 button your application will have opened the .hlp file and show you the Help Topic corresponding to that ID. After migration from VB6 to WinForms Help you now have the HelpProvider.SetHelpKeyword http://msdn.microsoft.com/en-us/library/system.windows.forms.helpprovider.sethelpkeyword.aspx And you had to do something like:

internal System.Windows.Forms.HelpProvider HelpProvider1;
...
HelpProvider1.HelpNamespace = "sample.chm";
HelpProvider1.SetHelpKeyword(TextBox1, "1007.html");
HelpProvider1.SetHelpNavigator(TextBox1, HelpNavigator.Topic);
HelpProvider1.SetHelpKeyword(ListBox1, "1006.html");
HelpProvider1.SetHelpNavigator(ListBox1, HelpNavigator.Topic);

And all that seems nice. But, what can you do when you cross over to SilverlightjQuery15205164761650376022_1357918518660? Well, in general there are several systems that allow you to author your help files in html or convert your .hlp or .chm files to html, but how do you link your components to that help system in order to provide context-sensitive help???? Ok. So one of the possible solutions is very very simple. In general, the solution that I will show in this post is this: 1) First implement an attached property for adding a HelpKeyword to Silverlight components 2) Set the helpkeyword in the desired components 3) Provide logic that will open the appropiate help file. Ok. So let's implement a Silverlight Attached property. An attached propery is like adding a new property to your controls. This new attached property will be called Helpkeyword

using System;
using System.Windows.Shapes;
namespace System.Windows.Controls
{
    public class HelpProvider
    {
        public static readonly DependencyProperty HelpKeyword = 
            DependencyProperty.RegisterAttached("HelpKeyword", typeof(string), typeof(HelpProvider), new PropertyMetadata(null));
        public static void SetHelpKeyword(UIElement element, string keyword)
        {
            element.SetValue(HelpKeyword, keyword);
        }

        public static string GetHelpKeyword(UIElement element)
        {
            return (string)element.GetValue(HelpKeyword);
        }
    }
}

Ok. So once we have the attached property we have to use it, and set it on the code: To set it on the code we must add a namespace:

<UserControl x:Class="SilverlightApplication.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    ...    
    xmlns:help="clr-namespace:System.Windows.Controls"
    mc:Ignorable="d"
    ....>

And apply the attribute to components

<Button help:HelpProvider.HelpKeyword="helpforbutton1" Content="Button" ...  />
<TextBox help:HelpProvider.HelpKeyword="helpfortext1" Height="47" ... />

So that almost everything, now we just need to trigger the appropiate logic, to do that we will add a KeyUp handler to the top most element, in this example a grid. NOTE: if Silverlight is running on the browser F1 is not an option. I just used F2 here as an example.

<Grid x:Name="LayoutRoot" Background="White" Height="205" KeyUp="LayoutRoot_KeyUp">
<Button help:HelpProvider.HelpKeyword="helpforbutton1" ...  />
<TextBox help:HelpProvider.HelpKeyword="helpfortext1" ... />
</Grid>
 
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Browser;

namespace SilverlightApplication
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
        {
            //check for the specific key. For now use F2 as the Help Shortcut
            if (e.Key==Key.F2) { 
                    var uielement = FocusManager.GetFocusedElement() as UIElement;
                    if (uielement!=null)
                    {
                        
                        var keyword = HelpProvider.GetHelpKeyword(uielement);
                        var host = HtmlPage.Document.DocumentUri.Host;
                        var port = HtmlPage.Document.DocumentUri.Port;
                        var url = string.Format("http://{0}:{1}/help/{2}.html", host,port,keyword);
                        HtmlPage.Window.Navigate(new Uri(url),"_blank");
                    }
            } // else ignore the keystroke
        }
    }
}
This property can be used on the IDE:

On code
var uielement = FocusManager.GetFocusedElement() as UIElement; 
if (uielement!=null) { 
var keyword = HelpProvider.GetHelpKeyword(uielement); 
}
This is an image of the application running.

And you can download the code from: CODE

If you have any questions or would like more info on Silverlight migration check www.silverlightmigration.com

More on iOS / XCode / Objective-C Migration Methods and Multiple Parameters to C#

6. May 2011 03:16 by Mrojas in General  //  Tags: , , , , , , , , , , , , , , ,   //   Comments (0)

On a previous post I was describing how some basic Objective-C elements were mapped to C#.
In particular I showed how the @interface and @implementation definitions are to be mapped in .Net, including basic properties.
In this post I will show a little about how methods are migrated.

There are several things to analyze when moving Objective-C code to C# it might be simple but can be a complicated
task. Objective-C is a language created under the inspiration of SmallTalk. And in Smalltalk programmer do not think of
method calls but instead of message sending and that is something to keep in mind when doing this migration.
Also all methods are virtual and even if there are access restriction in Objective-C I will map those methods to
public for simplicity sake.

In the previous post we had:

FIRSTFIRST

Fraction.h
#import <Foundation/NSObject.h>
@interface Fraction: NSObject {
    int numerator;
    int denominator;
}
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end

And

Fraction.m

#import "Fraction.h"
#import <stdio.h>

@implementation Fraction
-(void) print {
    printf( "%i/%i", numerator, denominator );
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(int) denominator {
    return denominator;
}

-(int) numerator {
    return numerator;
}
@end

And that example shows properties and methods with no parameter. OK. Now lets just focus on methods with 0, 1 and more parameters.

MethodsExample.h

#import <Foundation/NSObject.h>
@interface MethodsExample: NSObject {

}
-(void) print;
-(int) multiplyByTwo: (int) n ;
-(void) multiplyTwoNumers: (int) a andSecondNumber: b;
@end
 
MethodsExample.m
#import "MethodsExample.h"
#import <stdio.h>

@implementation MethodsExample
-(void) print {
    printf( "Hola mundo\n" );
}

-(int) multiplyByTwo: (int) n {
    return n * 2;
} -(int) multiplyTwoNumbers: (int) a andSecondNumber (int) b { return a * b;
} @end
And calling those functions will be:
#import <stdio.h>
#import "MethodsExample.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    MethodsExample *m = [[MethodsExample alloc] init];
    [m print]; 
int result; result = [m multiplyByTwo: 1]; result = [m multiplyTwoNumbers: 1 andSecondNumber: 5]; // free memory [m release]; return 0; }
This little example shows some of the particularities of Objective-C. 
In Objetive-C all parameters starting from the second parameter can have
what is called a label and labels are similar to namedParameter. Ok lets go ahead and map that class.
using System;

public class MethodsExample
{
    public virtual print() {
        Console.WriteLine("Hola mundo\n");
    }
    public virtual int multiplyByTwo(int n)
    {
      return n * 2;
    }
    //AproachOne
    public virtual int multiplyTwoNumber(int a,int andSecondNumber)
    {
        return a * andSecondNumber;
    }
    //AproachTwo
    //I just renamed as multiplyTwoNumber2 to avoid compilation errors.
    //The idea is that you will choose one of the two aproaches
    //or define a criteria for the instances where aproach one should be used
    //instead of approach two
    public virtual int multiplyTwoNumber(int a,int andSecondNumber)
    {
        int n = andSecondNumber;
        //This aproach will be better if you have a lot of code in the method
        //and you prefer to keep the original arg name
        return a * n;
    }

}
So the thing here is what to use as the parameter name, the label or the argument name. 
In the example you can see the two approaches in the multiplyTwoNumbers case.
 And calling the methods is simple and the named parameters syntax can be exploited.
using System;

public static class Program
{
    public static int Main(string[] argv ) {
        // create a new instance
        var m = new MethodsExample();
        m.print();
        int result;
        result = m.multiplyByTwo(1);
        result = m.multiplyTwoNumbers(1,andSecondNumber: 5); //using named parameters
        // free memory
        m.release();
        return 0;
    }
}
REMEMBER: This is just a glimpse of some mapping concepts from Objective-C to C#. 
There are many subtle details in this kind of migration and is my belief that only
an automated tool is able to process all those details in an effectively and more error-free
than a manual approach. For example in objective-c if m is null that will not cause any error if you
do something like [m print] and in C# that will throw an error. However a migration tool could determine
if the variable will have a value before its use and avoid adding unnecessary if (m!=null) statements.
We will examine this and other details in following posts. I hope this little examples give you enough information

for playing around migrating some Objective-C code. And if it gets too complicated just send me an email!!!

Windows Azure and Websites in a Flux

1. May 2011 07:47 by Mrojas in   //  Tags: , , , ,   //   Comments (0)

Windows Azure is a great platform and the escalatity oportunities are great,
and deployment time is also great.
You can have all your website up and running in just 10-15minutes.

But… and yes there is always a but.

Sometimes you can have a WebSite that is not that static, that as a matter of fact
you are changing its views constantly. Specially if some ideas are not finished.
And yes you can test locally, but there is also a situation where you might want to have that flexibility.

Well looking around I found a very interesting solution by
Maatern Balliauw. http://blog.maartenballiauw.be/post/2009/06/09/A-view-from-the-cloud-(or-locate-your-ASPNET-MVC-views-on-Windows-Azure-Blob-Storage).aspx

What he proposes is to use windows azure storage as a virtual file system, so you can with simple tools
like the Windows Azure Explorer modify your web pages without the need of going through a lengthy republish process.

So go ahead and keep enyoing Azure

Porting Application from iOS to WP7C#. Some toughts migration of Objective-C to C#

29. April 2011 12:07 by Mrojas in   //  Tags: , , , , , , , , , , , , ,   //   Comments (0)

Windows Phone 7 (WP7) is out! and it’s a great platform for developing new Apps. After being involved with Silverlight for a while
I am glad to have now the option to deploy apps to Windows Phone 7.

But we have to recognize that there are tons of great Apps for iPhone already. You might even have some of them.
So it’s porting time. Here at Artinsoft we love to upgrade/port application to all platforms.
So I will provide here some basic thoughts to help you upgrade your code.

For this post let’s discuss a little about applications written for XCode.

XCode applications are written in Objetive-C.Let’s map some examples:

In Objective-C your class will be usually

#import <Foundation/NSObject.h>
#import <Foundation/NSObject.h>

@interface Fraction: NSObject {
    int numerator;
    int denominator;
}

-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;
@end
How you should understand that? Well this is just the list of methods in your class something like:
using System;
public class Fraction {    
    int _numerator;    
    int _denominator;    
    public void print() { /* TODO*/}     
    public int numerator   { get { /* TODO */ } set { /*TODO*/} }    
    public int denominator { get { /* TODO */ } set { /*TODO*/} }
}
The code for these methods will be in the .m file.
#import "Fraction.h"
#import <stdio.h>

@implementation Fraction
-(void) print {
    printf( "%i/%i", numerator, denominator );
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(int) denominator {
    return denominator;
}

-(int) numerator {
    return numerator;
}
@end
So that will complement your class implementation for something like:
using System;
public class Fraction 
{    
    int _numerator;    
    int _denominator;    
    public void print() 
    { 
        Console.Write("{0}/{1}" ,numerator,denominator);
    }     
    public int numerator     
    {         
        get { return _numerator; }        
        set { _numerator = value; }    
    }    
    public int denominator     
    {        
        get { return _denominator; }       
        set { _denominator = value; }    
    }
}
Ok An now let’s look at the Objective-C main.m:
#import <stdio.h>
#import "Fraction.h"

int main( int argc, const char *argv[] ) {
    // create a new instance
    Fraction *frac = [[Fraction alloc] init];
    Fraction *frac2 = [[Fraction alloc] init];

    // set the values
    [frac setNumerator: 1];
    [frac setDenominator: 3];

    // combined set
    [frac2 setNumerator: 1 andDenominator: 5];

    // print it
    printf( "The fraction is: " );
    [frac print];
    printf( "\n" );

    // print it
    printf( "Fraction 2 is: " );
    [frac2 print];
    printf( "\n" );

    // free memory
    [frac release];
    [frac2 release];

    return 0;
}
 
Which can be rewritten in C# as:
 
using System;
static class ProgramMain{static int Main(string[] argv) {
    // create a new instance
    Fraction frac = new Fraction();
    // set the values frac.Numerator = 1; frac.Denominator = 3;
    // print it
    Console.Write( "The fraction is: " );
    frac.print();    Console.Write( "\n" );
    // free memory frac = null;
    return 0;
}}
Well this is just for warming up. In following posts we will be looking 
at more Objective-C \ XCode concept mapping to C#.
I recommend looking at the site http://wp7mapping.interoperabilitybridges.com/ 
that provides a lot about mapping iOS API
 

Silverlight project Error Cannot get the list of output files from Project

28. April 2011 07:20 by Mrojas in General  //  Tags: , ,   //   Comments (0)

This problem appear to web because I opened some forms with
Expression Web 4.0 and it seems to have modified my project files.

I finally found that to solve it all I have to do is to:

1. Open the .csproj with a text editor
2. Look for the ToolsVersion an change it from 4.0 to 3.5

And that’s all.

Silverlight: Isolated Storage Locations and Sizes

15. April 2011 08:35 by Mrojas in General  //  Tags: , , , , ,   //   Comments (0)

The actual Isolated Storage location is fixed but depends on the operating system where the Silverlight application is running:

From: http://msdn.microsoft.com/en-us/library/3ak841sy.aspx#isolated_storage_locations

Operating system

Location in file system

Windows 98, Windows Me - user profiles not enabled

Roaming-enabled stores =
<SYSTEMROOT>\Application Data
Non Roaming stores = WINDOWS\Local Settings\Application Data

Windows 98, Windows Me - user profiles enabled

Roaming-enabled stores =
<SYSTEMROOT>\Profiles\<user>\Application Data
Non roaming stores = Windows\Local Settings\Application Data

Windows NT 4.0

<SYSTEMROOT>\Profiles\<user>\Application Data

Windows NT 4.0 - Service Pack 4

Roaming-enabled stores =
<SYSTEMROOT>\Profiles\<user>\Application Data
Non roaming stores =
<SYSTEMROOT>\Profiles\<user>\Local Settings\Application Data

Windows 2000, Windows XP, Windows Server 2003 - upgrade from Windows NT 4.0

Roaming-enabled stores =
<SYSTEMROOT>\Profiles\<user>\Application Data
Non roaming stores =
<SYSTEMROOT>\Profiles\<user>\Local Settings\Application Data

Windows 2000 - clean installation (and upgrades from Windows 98 and Windows NT 3.51)

Roaming-enabled stores =
<SYSTEMDRIVE>\Documents and Settings\<user>\Application Data
Non roaming stores =
<SYSTEMDRIVE>\Documents and Settings\<user>\Local Settings\Application Data

Windows XP, Windows Server 2003 - clean installation (and upgrades from Windows 2000 and Windows 98)

Roaming-enabled stores =
<SYSTEMDRIVE>\Documents and Settings\<user>\Application Data
Non roaming stores =
<SYSTEMDRIVE>\Documents and Settings\<user>\Local Settings\Application Data

Windows Vista

Roaming-enabled stores =
<SYSTEMDRIVE>\Users\<user>\AppData\Roaming
Non roaming stores =
<SYSTEMDRIVE>\Users\<user>\AppData\Local

 

The amount of data that you can put on the isolated storage is limited by the UserQuota property.

By default an application has 1MB of storage space.
(see http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.increasequotato(VS.95).aspx)


If more space is needed the user can call the method increaseQuotaTo() that will allow prompting the user for permision to increase the amount of storage.

This will show a prompt dialog like:

To define policies I recommed looked at the Group Policy settings page
http://www.microsoft.com/GetSilverlight/resources/documentation/grouppolicysettings.aspx#isolated-storage and we might see more details about that in another post.

Windows Azure Migration: Database Migration, Post 1

2. April 2011 18:14 by Mrojas in   //  Tags: , , , , , , , , , ,   //   Comments (0)

WheWhen you are doing an azure migration, one of the first thing you must do is
collect all the information you can about your database.
Also at some point in your migration process you might consider between migration to
SQL Azure or Azure Storage or Azure Tables.

Do do all the appropriate decisions you need to collect at least basic data like:

  • Database Size
  • Table Size
  • Row Size
  • User Defined Types or any other code that depends on the CLR
  • Extended Properties

Database Size

You can use a script like this to collect some general information:

create table #spaceused(
databasename varchar(255),
size varchar(255),
owner varchar(255),
dbid int,
created varchar(255),
status varchar(255),
level int)

insert #spaceused (databasename , size,owner,dbid,created,status, level)  exec sp_helpdb

select * from #spaceused for xml raw
drop table  #spaceused
 

When you run this script you will get an XML like:

<row databasename="master" 
size=" 33.69 MB" 
owner="sa" 
dbid="1" 
created="Apr 8 2003" 
status="Status=ONLINE, ..." 
level="90"/>
<row databasename="msdb" 
size=" 50.50 MB" 
owner="sa" 
dbid="4" 
created="Oct 14 2005" 
status="Status=ONLINE, ..." 
level="90"/>
<row databasename="mycooldb" 
size=" 180.94 MB" 
owner="sa" 
dbid="89" 
created="Apr 22 2010" 
status="Status=ONLINE, ..." 
level="90"/>
<row databasename="cooldb" 
size=" 10.49 MB" 
owner="sa" 
dbid="53" 
created="Jul 22 2010" 
status="Status=ONLINE, ..." 
level="90"/>
<row databasename="tempdb" 
size=" 398.44 MB" 
owner="sa" dbid="2" 
created="Feb 16 2011" 
status="Status=ONLINE, ..." 
level="90"/>

And yes I know there are several other scripts that can give you more detailed information about your database
but this one answers simple questions like

Does my database fits in SQL Azure?
Which is an appropriate SQL Azure DB Size?

Also remember that SQL Azure is based on SQL Server 2008 (level 100).

80 = SQL Server 2000

90 = SQL Server 2005

100 = SQL Server 2008


If you are migrating from an older database (level 80 or 90) it might be necessary to upgrade first.

This post might be helpful: http://blog.scalabilityexperts.com/2008/01/28/upgrade-sql-server-2000-to-2005-or-2008/

Table Size

Table size is also important.There great script for that:

http://vyaskn.tripod.com/sp_show_biggest_tables.htm

If you plan to migrate to Azure Storage there are certain constraints. For example consider looking at the number of columns:

You can use these scripts: http://www.novicksoftware.com/udfofweek/vol2/t-sql-udf-vol-2-num-27-udf_tbl_colcounttab.htm (I just had to change the alter for create)

Row Size

I found this on a forum (thanks to Lee Dice and Michael Lee)

DECLARE @sql        VARCHAR (8000)
        , @tablename  VARCHAR (255)
        , @delim      VARCHAR (3)
        , @q          CHAR (1)

  SELECT @tablename = '{table name}'
       , @q         = CHAR (39)

  SELECT @delim = ''
       , @sql   = 'SELECT '

  SELECT @sql   = @sql
                + @delim
                + 'ISNULL(DATALENGTH ([' + name + ']),0)'
       , @delim = ' + '
  FROM   syscolumns
  WHERE  id = OBJECT_ID (@tablename)
  ORDER BY colid

  SELECT @sql = @sql + ' rowlength'
              + ' FROM [' + @tablename + ']'
       , @sql =  'SELECT MAX (rowlength)'
              + ' FROM (' + @sql + ') rowlengths'
  PRINT @sql
  EXEC (@sql)

Remember to change the {table name} for the name of the table you need

User Defined Types or any other code that depends on the CLR

Just look at your db scripts at determine if there are any CREATE TYPE statements with the assembly keyword.
Also determine if CLR is enabled with a query like:

select * from sys.configurations where name = 'clr enabled'

If this query has a column value = 1 then it is enabled.

Extended Properties

Look for calls to sp_addextendedproperty dropextendedproperty OBJECTPROPERTY and sys.extended_properties  in your scripts.

Silverlight and what to do with Application or User Settings or INI files

Some people ofter forget about this (even me Confused smile ) So that;’s why I’m posting about this.

In my work (at Artinsoft) we are currently performing a lot of Winforms and VB6 
migration to Silverlight. And a common problem is “What can I do with the user settings!!!”.

In VB6 you had your INI files and in Winforms you probably used something like the App settings.
But when you move to Silverlight what can you do!.
You need a set of initial values and you probably wont want to “burn” those inicial values in your XAP file.
It would be nicer if those values can just be set in the Web.Config file.

So a common way to solve this, is develop a simple helper class. This helper class will use a service that will
collect your initial ini files or appsettings values and store them in your Isolated Storage.
You can even use some kind of basic cryptography if you feel that your date is sensitive.

And then you can use the helpful IsolatedStorageSettings class. For example see this code,
that I borrowed from this post: http://wildermuth.com/2008/10/21/Using_Isolated_Storage_Settings_in_Silverlight_2

const string FAVCOLORNAME = "favoriteColor";
public Color? FavoriteColor
{
  get
  {
    if (IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] != null)
    {
      Color? colorSetting =         IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] as Color?;
      if (colorSetting != null) return colorSetting;
    }

    // If we can't find a favorite color, return a null color
    return new Color?();
  }
  set
  {
    IsolatedStorageSettings.ApplicationSettings[FAVCOLORNAME] = value;
  }
}

As you can see is very easy to save and recover simple settings from the Silverlight Isolated Storage

Dynamically change WCF Endpoint

23. March 2011 11:33 by Mrojas in General  //  Tags: , , , , , , , , ,   //   Comments (0)

Specially if you are working with Silverlight and Azure you will end up in situation where you would
like to redirect your WCF Endpoint dinamically ( I don’t think you can guess the GUID that Azure will generate
for your staging enviroment).

 

Out of the box the silverlight behaviour is that the WCF endpoints are hardcoded in a config file called
ServicesClient.config embedded in the .xap file.

This can be problematic at least for Azure deployment infraestructure because you can deploy to different sites:
Staging and Production.
Each of this Web Sites will have differente URLs.For example phonebook.cloudapp.net or asdf-asdf-asdf-dasxxx.cloudapp.net

So an easy workaround is:

In WCF when a channel is created in code you can specify the endpoint,
so we only need to created different endpoints depending of the site where the the .xap file was download.

The proposed changes will be:

For example if you create services in your App.xaml.cs method Application_Startup
Then you can change your code for something like:

string url = "http://" + HtmlPage.Document.DocumentUri.Host + "/MyService.svc";
EndpointAddress endpoint = new EndpointAddress(url);
var service = new MyService(new ChannelFactory<IMyService>("*").CreateChannel(endpoint)));

This will allow you to just deploy your application to either Staging or Production environment
in Azure with no more code or config file changes.

Silverlight: Error HRESULT E_FAIL has been returned from a call to a COM component

23. March 2011 05:05 by Mrojas in General  //  Tags: , , , ,   //   Comments (0)

While developing some user controls in Silverlight I have come with a situation,
for example when dragging a Chart control in the Visual Studio 2010 designer where I get something like:

Error HRESULT E_FAIL has been returned from a call to a COM component

I have been looking for a solution but have not found anything yet.
The only workaround has been:  
a) Close all windows. Do a Clean and a Rebuild or Close Visual Studio and open it again.

Categories