Showing posts with label development. Show all posts
Showing posts with label development. Show all posts

Mixing C# source code with PowerShell script code to speed your development

I had some C# code ready but needed to use it inside a PowerShell script.

At StackOverflow I found some code that put me in the right path. So here's a practical example when mixing codes inside a PowerShell script file:

. ".\Invoke-Parallel.ps1" # Importing another script into this PowerShell script file

$csharpSource = @"

using System;
using System.Collections.Generic;
using System.Linq;

public class DateExtensions
{
     public static List<Tuple<DateTime, DateTime>> GetWeeksBetweenDates(DateTime startDate, DateTime endDate)
     {
        var weeks = new List<Tuple<DateTime, DateTime>>();
        
    
         for (DateTime date = startDate; date <= endDate; date = date.AddDays(8))
         {
            var weekEnd = date.AddDays(7);
                            
            weeks.Add(new Tuple<DateTime, DateTime>(date, weekEnd <= endDate ? weekEnd : endDate));
         }

        return weeks;
    }
}
"@

Add-Type -TypeDefinition $csharpSource # Includes the C# code defined above to be called through the PowerShell script

$appPath = "C:\SomeFolder"
$startDate = [datetime]'6/1/2017'
$endDate = [datetime]'5/5/2018'

$weeks = [DateExtensions]::GetWeeksBetweenDates($startDate, $endDate)

#Calls MyApp in batches, that is, for each week...
$weeks | Invoke-Parallel -ImportVariables -ScriptBlock {   
    Set-Location -Path $appPath
           
    $date = [string]::Format("{0:yyyyMMdd},{1:yyyyMMdd}", $_.Item1, $_.Item2)

    #Write-Host $date

    dotnet MyApp.dll budat=$date cpudt=$date # Calls .NET Core "executable" DLL for each week
}

pause #Keeps PowerShell window open to see the results

As we see in the code above, the variable $csharpSource holds the C# source code that later will called in the PowerShell script.

We then add\mix the C# code to\with PowerShell with the command Add-Type passing to it the $csharpSource variable that holds the source code. Simple as that.

Inside PowerShell script code we call the method defined in C# code with:

$weeks = [DateExtensions]::GetWeeksBetweenDates($startDate, $endDate)

This is pretty useful because we don't need to convert our C# code to PowerShell idiom.

Hope it helps.

Reference:
How to convert C# code to a PowerShell Script?

Xcode iPhone beginner projects with GitHub integration

I decided to follow a different path to learn software development for the iPhone - instead of online tutorials and Apple docs I got a book. I postponed my desire to learn but it’s time to revive it. I grabbed a beginner’s book on the subject: A Beginner's Guide to iOS SDK Programming by James A. Brannan & Black Ward. This book covers iOS 4.2 + Xcode 4. iOS 5 is on the verge of being released…Smiley confuso

I had to download the recent Xcode and its accompanying SDK bits again ( 3.17 GB ) as the ones I had installed were out of date (from September 2010) Smiley pensativo. It was just a matter of hitting Mac App Store and looking for Xcode. The download has everything you need to install to be able to follow the book samples.

As I started creating the sample projects in Xcode I thought it’d be an excellent opportunity to store these samples in an online repository ( repo ) with source code control for further reference and to share/allow the beginner developer to download and study all the samples. It’s also a good chance I have to play with Git since I’ve been using Subversion during the last years.

This post covers the basics to integrate Xcode with GitHub for the Mac OS user. GitHub is a web-based hosting service for software development projects that use the Git revision control system.

I try to synthetize lengthy and scattered docs you find on the subject and provide links to key docs and posts…

I learned how to use Xcode Organizer to integrate my online GitHub repository with Xcode built in support for software control management and started sending the projects to GitHub right after the second book sample. It’s better to start early or you’ll never do it!

This article in Mac OS Developer Library: Managing Versions of Your Project has everything you need to configure your project to use it with Git.

When you create an online/remote repository in GitHub you get instructions on how to set up the repo as getting a copy of the repo to work locally in your computer or sending an existing project to the remote repo. This help article from GitHub clarifies some things: Set up Git in Mac OS.

This post has the steps you have to follow to get a GitHub repo to work with Xcode projects: Version Control System with XCode 4 and Git Tutorial.

You’ll have to use Mac OS Terminal to type some commands. Nothing difficult.
As a matter of fact you should familiarize yourself with Terminal if you haven’t yet. The real fun is when you play with git commands in Terminal (take for example the powerful rebase command). Later in this post I’m going to use the support offered by Xcode which has UI for basic git commands as commit, push, pull, merge, etc - but Xcode doesn’t give you the power of the full set of git commands that are only available through the command line.

These are the Terminal commands I typed to send the book’s initial sample projects (QuickStart and C Main Project) to my remote repository located at GitHub: https://github.com/leniel/iPhone-Beginner-Guide
Take a special look at the highlighted commands:

Last login: Fri Aug 19 19:29:32 on ttys001
Leniel-Macaferis-Mac-mini:~ leniel$ cd /
Leniel-Macaferis-Mac-mini:/ leniel$ cd iPhone
Leniel-Macaferis-Mac-mini:iPhone leniel$ cd Local
Leniel-Macaferis-Mac-mini:Local leniel$ ls
C Main Project                iPhone Beginner's Guide.xcworkspace
QuickStart
Leniel-Macaferis-Mac-mini:Local leniel$ cd QuickStart
Leniel-Macaferis-Mac-mini:QuickStart leniel$ ls
QuickStart        QuickStart.xcodeproj
Leniel-Macaferis-Mac-mini:QuickStart leniel$ git remote add origin git@github.com:leniel/iPhone-Beginner-Guide.git
Leniel-Macaferis-Mac-mini:QuickStart leniel$ git push -u origin master
Counting objects: 16, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (16/16), 8.27 KiB, done.
Total 16 (delta 2), reused 0 (delta 0)
To git@github.com:leniel/iPhone-Beginner-Guide.git
* [new branch]      master -> master
Branch master set up to track remote branch master from origin.

Leniel-Macaferis-Mac-mini:Local leniel$ cd "C Main Project"
Leniel-Macaferis-Mac-mini:C Main Project leniel$ ls
C Main Project            C Main Project.xcodeproj
Leniel-Macaferis-Mac-mini:C Main Project leniel$ git push -u origin master
To git@github.com:leniel/iPhone-Beginner-Guide.git
! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:leniel/iPhone-Beginner-Guide.git'
To prevent you from losing history, non-fast-forward updates were rejected.
Merge the remote changes (e.g. 'git pull') before pushing again.
  See the 'Note about fast-forwards' section of 'git push --help' for details.
Leniel-Macaferis-Mac-mini:C Main Project leniel$ git pull origin master
warning: no common commits
remote: Counting objects: 16, done.
remote: Compressing objects: 100% (12/12), done.
remote: Total 16 (delta 2), reused 16 (delta 2)
Unpacking objects: 100% (16/16), done.
From github.com:leniel/iPhone-Beginner-Guide
* branch            master     -> FETCH_HEAD
Merge made by recursive.
QuickStart.xcodeproj/project.pbxproj             |  288 ++++++++++++++
QuickStart/QuickStart-Info.plist                 |   38 ++
QuickStart/QuickStart-Prefix.pch                 |   14 +
QuickStart/QuickStartAppDelegate.h               |   19 +
QuickStart/QuickStartAppDelegate.m               |   73 ++++
QuickStart/QuickStartViewController.h            |   13 +
QuickStart/QuickStartViewController.m            |   44 +++
QuickStart/en.lproj/InfoPlist.strings            |    2 +
QuickStart/en.lproj/MainWindow.xib               |  444 ++++++++++++++++++++++
QuickStart/en.lproj/QuickStartViewController.xib |  156 ++++++++
QuickStart/main.m                                |   17 +
11 files changed, 1108 insertions(+), 0 deletions(-)
create mode 100644 QuickStart.xcodeproj/project.pbxproj
create mode 100644 QuickStart/QuickStart-Info.plist
create mode 100644 QuickStart/QuickStart-Prefix.pch
create mode 100644 QuickStart/QuickStartAppDelegate.h
create mode 100644 QuickStart/QuickStartAppDelegate.m
create mode 100644 QuickStart/QuickStartViewController.h
create mode 100644 QuickStart/QuickStartViewController.m
create mode 100644 QuickStart/en.lproj/InfoPlist.strings
create mode 100644 QuickStart/en.lproj/MainWindow.xib
create mode 100644 QuickStart/en.lproj/QuickStartViewController.xib
create mode 100644 QuickStart/main.m
Leniel-Macaferis-Mac-mini:C Main Project leniel$ git push -u origin master
Counting objects: 14, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (12/12), done.
Writing objects: 100% (13/13), 3.95 KiB, done.
Total 13 (delta 3), reused 0 (delta 0)
To git@github.com:leniel/iPhone-Beginner-Guide.git
   05ec270..fe84a7a  master -> master
Branch master set up to track remote branch master from origin.
Leniel-Macaferis-Mac-mini:C Main Project leniel$

Great! With the above commands I have sent both projects to my repo located at GitHub.

It’s important to note that for each project I created in Xcode I selected the option to create a local git repository as shown in Figure 1:

Xcode - Selecting Create local git repository for this projectFigure 1 - Xcode - Selecting Create local git repository for this project

With this in place I can now safely delete my local copy of both projects (folder Local I used above in Terminal commands) and work directly with the code of my remote repository. Let’s do it:

Open Xcode Organizer selecting the menu Window => Organizer:

Organizer window accessible through Xcode’s Window menuFigure 2 - Organizer window accessible through Xcode’s Window menu

I suppose you have already configured and added (+ button in the bottom left of Figure 2) your GitHub repo (green circle in Figure 2) to the Organizer following the docs I linked above.

To get a local working copy of your remote repository you must click the Clone button (see bottom part of Figure 2) and choose a location to place the repo files. After doing this you’ll get a new repo (mine is located in the folder /iPhone/iPhone-Beginner-Guide as you see in Figure 2). When I click my local copy of the repo I get this beautiful screen where I can see commit comments and changes I made to each file along the way (click to enlarge):

Local ( Clone ) copy of my online GitHub repository seen in Xcode OrganizerFigure 3 - Local ( Clone ) copy of my online GitHub repository seen in Xcode Organizer

Now it’s just a matter of working and modifying the project files or adding new projects and commit them to the repository through the menu File => Source Control => Commit…

One more important note is: when you commit something, it’s just committed in your local copy. You need one additional step: push the changes to GitHub. In Xcode you can select the file(s) or project(s) you want and go to File => Source Control => Push… For more on this, read: Commit Files to Add Them to a Repository.

In my case, when I select Push I get this Xcode dialog where I can select the Remote endpoint (GitHub repository) to which my committed files will go:

Xcode Push user interface and GitHub remote locationFigure 4 - Xcode Push user interface and GitHub remote location

As a bonus I created a Workspace as seen in Figure 5 to have all the sample projects at hand in a single Xcode window. The workspace has references to the projects and work somewhat like Microsoft Visual Studio’s solution file if you’re used to Microsoft developer tools. The workspace helps a lot during the commit and push tasks!

Xcode workspace with projects at left side paneFigure 5 - Xcode workspace with projects at left side pane

Well, I’m new to this new Xcode world and I think I’ll learn a lot from these simple sample beginner projects.

The next thing I'm gonna do is learn what file types I can ignore when committing… Thanks to StackOverflow there’s already a question addressing this very topic: Git ignore file for Xcode projects

Edit: following the advice of the above StackOverflow question, I added a .gitignore file to the repo.

Hope this helps.

Sistema para Gerenciamento de Academia de Ginástica

Esta é uma aplicação web que nasceu através de uma parceria entre mim (o único desenvolvedor) e o proprietário de uma academia de ginástica ( a qual eu frequento ). O sistema está em uso e o proprietário/usuário está muito satisfeito.

A aplicação valoriza a simplicidade e é super fácil de usar.

A figura a seguir mostra a home page de onde o usuário pode acessar as funcionalidades da aplicação. Clique nela para ver uma versão ampliada...

Página inicial da aplicação Fitness Center

A aplicação é composta por 5 módulos e possui Controle de Acesso baseado em cargos (Administrador, Professor, Usuário, etc).

Módulos
- Alunos
- Anamneses
- Medidas
- Pagamentos
- Relatórios ( baseados em gráficos e listas )

O sistema está disponível em Português do Brasil (pt-BR) e Inglês (en-US). Ele tem tudo pronto para o caso em que exista a necessidades de localizações adicionais. É completamente viável ter a aplicação em execução em qualquer outra cultura/idioma com pouco trabalho.

Estilos/cores/formatação e logotipo podem ser personalizados usando (CSS).

Tecnologias
A aplicação usa o estado da arte das tecnologias da pilha Microsoft, bem como bibliotecas de código aberto:

C#, .NET Framework 4, ASP.NET MVC 3, SQL Server Compact 4.1, CSS, jQuery 1.5.2, jQuery UI 1.8.12, jQuery Globalization 1.0, jQuery qTip2, modernizr 1.7, Microsoft MVC Ajax, Microsoft Chart Controls for. NET 4, WebGrid, Chirpy

Telas
Você pode ver screenshots da aplicação aqui.

Descrição
As seções subsequentes descrevem cada módulo e as ações que o usuário tem permissão para executar.

A lógica de negócios também é descrita ao longo do caminho se eu ver que ela se encaixa na descrição do módulo.

Não é minha intenção descrever cada regra de negócio da aplicação neste post. Este post é uma visão geral.

Alunos
Ações: Criar, Editar, Detalhes, Excluir
Este módulo trata de dados básicos do aluno como foto, nome e sobrenome, data de nascimento, endereço, sexo, telefone, e-mail, etc. 
Tudo no sistema está relacionado ao aluno. Isto significa que se um aluno é excluído, os dados de cada módulo que fazem referência aquele aluno também serão excluídos.
Alunos que estão em débito são destacados em vermelho na lista/grid de alunos.
Se o nome de um aluno é clicado na lista de alunos, o sistema leva o usuário à lista de pagamentos do respectivo aluno.

Anamneses
Ações: Criar, Editar, Detalhes, Excluir
Este módulo manipula as informações básicas sobre o histórico de saúde do aluno, tais como se o aluno é hipertenso, diabético, fumante, etc. Diferentes tipos de doenças também podem ser selecionados. Estas doenças são agrupadas em categorias, tais como doenças dos ossos e articulações, respiratórias e doenças da tireoide. O estilo da atividade física na qual um aluno se encaixa quando ele se matricula na academia também pode ser selecionado.

Medidas
Ações: Criar, Editar, Detalhes, Excluir
Este módulo trata das medidas das circunferências do corpo do aluno. Estas são as medidas que o sistema controla:
- Altura (m)
- Peso (kg)
- Gordura (%) 
- Pescoço (m)
- Tórax (m)
- Glúteos (m)
- Ombro (m)
- Abdome (m)
- Cintura (m)
- Braço Esquerdo (m)
- Braço Direito (m)
- Coxa Esquerda (m)
- Coxa direita (m)
- Panturrilha Esquerda (m)
- Panturrilha Direita (m)

O usuário é notificado através da lista de medidas se é hora de tomar novas medidas de um aluno. O intervalo de tempo entre as avaliações (medidas) pode ser configurado no sistema. Atualmente está definido como um intervalo de três meses.
A % de Gordura é calculada pelo sistema através de uma fórmula padrão (ver link). Se o usuário passar o mouse sobre o cabeçalho da coluna (%) Gordura na listagem de medidas ele verá uma tabela com valores padrão para % de gordura que inclui Essencial, Atleta, Fitness, Média e Obeso.

Pagamentos
Ações: Criar, Editar, Detalhes, Excluir
Este módulo é o coração do sistema, uma vez que lida com o que podemos chamar de a Raison d'être (razão de ser) de um sistema como este.
O sistema permite a criação de pagamentos para um determinado aluno.
O usuário define um valor de desconto (se necessário) e o campo total é calculado automaticamente. Depois disso uma data de pagamento deve ser selecionada. Há também um campo de observação no qual o usuário pode anotar alguma coisa importante relacionada ao pagamento.
O usuário sinaliza que o pagamento foi realizado marcando o campo pago.
Sempre que um pagamento é marcado como pago, o sistema gera um novo pagamento automaticamente (cópia do pagamento feito) para o mesmo aluno com a data de vencimento 1 mês à frente.

Relatórios
Este módulo gera 4 tipos de relatórios. São eles:

- Total de Pagamentos (gráfico)
O usuário seleciona uma data de início e uma data de fim para gerar um gráfico de colunas que agrupa os pagamentos por mês.

- Pagamentos em Atraso/Vencidos (grid/lista) 
O sistema gera automaticamente um relatório em formato de lista extraindo os dados dos pagamentos que têm uma data de vencimento inferior a uma data especificada. Por exemplo: pode-se conceder uma margem (em dias) para que o sistema considere que o aluno está em débito - 1 semana, 2 semanas, etc após a data do vencimento do pagamento. Isso pode ser configurado no sistema.

- % Alunos Ativos/Inativos (gráfico)
O sistema gera automaticamente um gráfico em formato de pizza que retrata muito bem essa informação.

- Medidas ao Longo do Tempo (gráfico)
O usuário seleciona um aluno e uma data de início e fim para gerar um belo gráfico de linhas que mostra o aumento/diminuição das medidas ao longo do tempo.

Por que comprar?
O principal benefício é que você terá um ponto central para gerenciar sua Academia de Ginástica. A partir dele você pode extrair informações valiosas dos dados. Isto te permite estar sempre um passo à frente para planejar seu próximo passo. Não haverá mais anotações em cadernos e com isso você deixará de perder dados importantes!

Instalação
A aplicação é um arquivo .zip (arquivo compactado) e possui todo o que é necessário para ser executada em um servidor web que tenha o .NET Framework 4 instalado.

Se precisar de ajuda adicional no que diz respeito à hospedagem web/instalação e configuração, eu também posso fazer isso por você. É só me avisar.

Há também a possibilidade de executar a aplicação em um servidor web local usando Microsoft WebMatrix por exemplo. É assim que instalei o sistema no computador do usuário. Fazendo dessa forma você não terá que pagar um provedor de hospedagem on-line. A única desvantagem neste caso é que você não será capaz de acessar a aplicação a partir de qualquer lugar.

Como comprar?
Basta clicar no botão abaixo para comprar esta app barata ( somente R$ 1.200,00 ) através do PayPal:


Depois de clicar no botão acima e concluir o processo de pagamento, escreva para mim e me informe sobre sua compra. Poderei, então, dar prosseguimento no processo de negociação entregando para você a aplicação através de e-mail. A aplicação está contida em um arquivo .zip pequeno ~4MB.

Software é um campo muito interessante porque você trabalha muito para construir uma aplicação, digamos meses, e o produto é apenas um pacote de alguns megabytes. Vai entender…

Direitos autorais
Este produto de software é protegido por direitos autorais.

Você pode ler a EULA aqui (em construção).

Suporte
Ficarei mais do que feliz em fornecer qualquer informação adicional que você precise para que a aplicação seja instalada e funcione em seu servidor.

Se você encontrar algum bug na aplicação eu prontamente irei corrigi-lo e disponibilizarei a aplicação atualizada para você.

Recursos adicionais
Se você precisar de qualquer outro recurso, seja ele um novo módulo ou relatório que não faz parte desta aplicação, apenas me informe e o considerarei para uma versão futura.

Fitness Center management software ( web app )

Fitness Center Management System/Web Application
This is a web application that was born in a partnership between me (the only developer) and the owner of a Fitness Center that I happen to be a frequenter/student. It’s currently being used there and he (the owner/user) is really satisfied with it.

The application values simplicity and is super easy to use.

The following screenshot shows the home page from where the user can access the application functionalities. Click it to see a larger version…

Fitness Center Management System Home page

The app comprises 5 modules and has access control based on Roles (Administrator, User, etc).

Modules
- Students
- Anamneses
- Measurements
- Payments
- Reports (chart and grid based reports)

It’s available in Portuguese from Brazil (pt-BR) and English (en-US). It has everything in place in case of additional localization needs. It’s completely viable to have the app running in any other culture/language with little work.

Application styles/colors and logo can be customized using cascading style sheet (CSS).

Technologies
The app uses state of the art technologies from Microsoft stack as well as open source libraries:
C#, .NET Framework 4, ASP.NET MVC 3, SQL Server Compact 4.1, CSS, jQuery 1.5.2, jQuery UI 1.8.12, jQuery Globalization 1.0, jQuery qTip2, modernizr 1.7, Microsoft MVC Ajax, Microsoft Chart Controls for .NET 4, WebGrid, Chirpy

Screenshots
You can see screenshots of the application here.

Description
The subsequent sections describe each module and the actions the user is allowed to perform. Business logic is also described along the way if I see it fits. It’s not my intention to describe every business rule of the application in this post. It’s just an overview.

Students
Actions: Create, Edit, Details, Delete
This module handles basic student data as photo, first and last names, birth date, address, gender, phone, email, etc. 
Everything in the system is related to Student. This means that if a Student is deleted, every other module's data is deleted as well.
Students that are in debt are highlighted in red in the Students list/grid.
If the name of a Student is clicked in the list, the system takes the user to the Payments list of that respective Student.

Anamneses
Actions: Create, Edit, Details, Delete
This module handles basic information about the Student health history such as if the student is hypertense, diabetic, smoker, etc. Different types of diseases can also be selected. These diseases are grouped in categories such as Bones and Joints, Respiratory and Thyroid diseases. The style of physical activity a student currently fits in when he/she joins the Fitness Center can also be selected.

Measurements
Actions: Create, Edit, Details, Delete
This module handles measurements of a Student's body circumferences. These are the measurements the system keeps track:
- Height (m)
- Weight (kg)
- Fat (%)
- Neck (m)
- Thorax (m)
- Buttocks (m)
- Shoulder (m)
- Abdomen (m)
- Waist (m)
- Left Arm (m)
- Right Arm (m)
- Left Thigh (m)
- Right Thigh (m)
- Left Calf (m)
- Right Calf (m)

The user is notified through the measurements list if it's time to take new measurements for a Student. The time interval between measurements can be configured in the system. Currently this is set as a 3 month interval.
Fat (%) is calculated by the system. If the user hovers his mouse over the Fat (%) table header he/she can see a table with standard Fat (%) values that include Essential, Athletes, Fitness, Average and Obese.

Payments
Actions: Create, Edit, Details, Delete
This module is the heart of the system since it handles what we can call the Raison d'être of a system like this.
The system allows the creation of payments for a given Student. The user defines a value, discount (if necessary) and the Total field is automatically calculated. After that a Due date must be selected. There’s also an observation field in which the user can annotate anything important related to that payment. The user signals that a payment was made by checking the Paid field.
Whenever a payment is marked paid, the system automatically generates a new payment (copy of the payment being made) for that same Student with a due date 1 month ahead.

Reports
This module generates 4 types of reports. They are:

- Total Payments ( chart )
The user selects a Start and End date to generate a column chart that groups the payments by month.

- Overdue Payments ( grid/listing ) 
The system automatically generates a grid/listing report extracting data for payments that have a due date less than a specified date. This can be configured in the system.

- % of Active/Inactive Students ( chart )
The system automatically generates a pie chart that depicts very well this information.

- Measurements Over Time ( chart )
The user selects a Student and a Start and End date to generate a beautiful line chart that shows measurements increase/decrease over time.

Why to buy?
I think the main benefit is that you’ll have a centralized point to manage your Fitness Center. From this you can extract valued information from data and be always one step ahead to plan your next endeavor. No more notebook entries and missing important data!

Installation
The app is self-contained in a .zip file that has everything it needs to run on a webserver that has the .NET Framework 4 installed.

If you need additional assistance regarding installation/web server hosting and configuration, I can also do that for you. Just let me know.

There's also the possibility of running the app in a local webserver by using Microsoft WebMatrix for example. This is how I installed it in the user's computer. Doing this way you won't need to pay an online hosting provider. The only downside here is that you won't be able to access the app on the go.

How to buy?
Just click the following button to buy this cheap app ( only $ 600.00 ) through PayPal:

After clicking the button above and completing the payment process, write to me and let me know about the purchase. I can then go further in the negotiation process and handle you the app through e-mail since it’s a small .zip package ~4MB.

Software is a really interesting field because you put a lot of work to construct it, let’s say months and the product is just a package of only a few megabytes. Go figure.

Support
I'll be more than happy in providing any further information you need to get the app up and running on your server.

If you find any bug in the app I'll promptly correct it and send the patched app to you.

Additional features
If you need any other feature, be it a new module or report that is not part of this app, just let me know and I'll consider it for a future release.

Access web app from Parallels Win 7 VM in Mac OS

About a month ago I started the creation of an ASP.NET MVC 3 app to a buddy. I’ll write some blog posts in the near future sharing my experiences with this awesome web framework. This app I’m still developing is a web application that I develop using my "new” computer. Today I use Mac OS as my main operating system and since I’m using ASP.NET I also need to use Windows.

Parallels Desktop is the way to go to have a Windows virtual machine [ VM ] running side by side with Mac OS. This way you have the best of both worlds. I discuss more about Parallels Desktop here.

One of the things I wanted to do during the development was seeing how the app would look like when viewed in a different OS, in this case, I’d like to see it running in Mac OS as if I were an end user accessing the app. This is good to test how the app behaves when it’s viewed in a different environment, that is, the perspective/environment of the end user, and not the developer’s perspective/development environment.

It’s cool to see the app running in a different OS and different web browsers. In Mac OS I have the chance of testing it against Safari too. I also have the chance of seeing how exceptions are being handled. There are certain types of errors that only happen when the end user is using the app in his environment. I think you know that already. This kind of testing allows me to deliver a better user experience.

When the app is accessed from the Mac side, the first difference is mainly visual because my Win 7 VM has all visual effects (clear type) disabled and so things look really simple if compared to Mac OS. I’m running the VM with no visual effects so that I have a somewhat fast VM to do the development. I only have 4 GB RAM available and I have to share it with both operating systems. I thought 4 GB RAM would suffice but that’s not the case. I have already ordered 8 GB RAM but am eagerly waiting it arrive from US. That’s another story that I plan to write in other blog post.

The reason I’m writing this post is that things don’t work at first when you try to access in Mac your app that is running in Windows VM. To get things working from both sides ( host = Mac OS and VM = Windows 7 ) they must see/communicate with each other. That’s where I had to do some work to get things going. So here are some instructions of what you need do:

1 - Set a fixed IP address for Windows VM
Set up a fixed IP address (read this page for a complete guide) in your Windows 7 virtual machine. This will make it easy when you need to access your app from Mac OS side. You won’t need to take note of different IP addresses handled by the DHCP server each time you restart your VM.

Windows 7 VM with fixed IP addressFigure 1 - Windows7 VM with fixed IP address

Above I have given the IP 192.168.1.106 to the VM. As I do not have a lot of devices connected to my wireless router, this IP is just fine.

2 - Set Virtual Machine’s Network Type
In your Parallels VM devices bar set your network type (orange arrow) as bridged:

Parallels Desktop VM devices toolbarFigure 2 - Parallels Desktop VM devices toolbar

3 - Test Communication between Host and VM
Make sure both operating systems can see each other.

Open Mac OS Terminal and execute a ping command:

ping 192.168.1.106

Change the IP with the IP you have in your Windows VM.

You should see something like this:

Mac OS Terminal pinging Windows 7 VMFigure 3 - Mac OS Terminal pinging Windows 7 VM

Now, open Windows 7 Command Prompt and ping Mac IP address. To see your Mac IP address go to System Preferences. Under Internet & Wireless, select Network.

Mac OS IP addressFigure 4 - Mac OS IP address

Let’s ping 192.168.1.100:

Windows 7 VM Command Prompt pinging MacFigure 5 - Windows 7 VM Command Prompt pinging Mac

As you see, both computers can see/communicate with each other. This means that the Network is working as expected.

4 - Configure Windows VM webserver for external traffic
What address should you type in a Mac OS browser to access the app? Well, this needs a little bit of caring. You’ll probably fail when trying to access the app with the same address you use in Windows side.

I’m using IIS Express as the web server in Windows. You can install it using Microsoft WebMatrix. IIS Express is by default configured to only server internal traffic (Windows VM). As I’m trying to access it from an external environment (Mac OS), I needed to configure it. The first link bellow was the main doc that helped me:

Serving external traffic with WebMatrix Beta
Handling URL Binding Failures in IIS Express (Serving External Traffic)

Basically I had to configure HTTP.SYS, create a URL binding that allow me to access the app in Mac side and disable Windows Firewall for my private home network.

4.1 - Configure HTTP.SYS
Type this command in Windows command prompt:

netsh http add urlacl url=http://leniel-pc:7777/ user=everyone

Change the url in the above command according to your desired configuration.

Note: the above command requires elevation. Right click the command prompt shortcut and select Run as administrator.

4.2 - Configure URL binding
As mentioned in the 2nd doc referenced above you must open your applicationhost.config file and add URL bindings that fit your needs. Mine is located here:

C:\Users\Leniel\Documents\IISExpress\config\applicationhost.config

Take a look at the last binding I have added:

<site name="FitnessCenter" id="3">

<application path="/" applicationPool="Clr4IntegratedAppPool">

<virtualDirectory path="/" physicalPath="C:\Users\Leniel\Documents\Visual Studio 2010\Projects\FitnessCenter\FitnessCenter.Web" />

</application>

<bindings>

<binding protocol="http" bindingInformation="*:7777:leniel-pc" />
<binding protocol="http" bindingInformation="*:7777:localhost" />

<binding protocol="http" bindingInformation=":7777:leniel-pc" />

<binding protocol="http" bindingInformation="192.168.1.106:7777:"/>

</bindings>

</site>

4.3 - Configure Windows VM firewall
The last step is disabling Windows VM firewall for your Home or work private networks.

Windows 7 VM FirewallFigure 6 - Windows 7 VM Firewall

As I just use this virtual machine to do software development, it’s ok to me to disable the firewall. Be careful though. Surprised smile

5 - Access Win 7 VM web app in Mac OS
After all this configuration you should be able to browse your app externally.

To see if everything is working, open a browser in Mac OS and try to access the app typing something as this in my case:

http://192.168.1.106:7777/

That’s it.

Hope it helps.

Installing PHP on Mac OS X Snow Leopard 10.6.5

Motivated by this question at StackOverflow: RegExp PHP get text between multiple span tags, I decided to help.

Recently I got a Mac mini. I still hadn’t played with PHP on Mac and to debug my answer to that question I needed a way to test the code. So I thought: why not also give PHP a try on Mac OS since its my main OS today? Oh, good idea, go learn something new… :D

The first thing I did obviously was recurring to Google and searching for something that could help me get there.

I hit a pretty good tutorial to enable PHP on Mac at About.com written by Angela Bradley that gets to the point: How to Install PHP on a Mac. Along the way I had to solve only one minor thing described in the caveat section at the end of this post.

You see that the title of this post has the word installing (well I thought I had to install it – that was my first reaction), but in fact it could be the word enabling because PHP is an integral part of Mac OS X Snow Leopard and we just need to enable it as you’ll see soon.

Here we go. Follow these steps:

1 - Enabling the Web Server
PHP works hand in hand with a webserver. Mac OS already comes with Apache web server and so we just need to enable it. To do so, open System Preferences in the Dock. Then click the 'Sharing' icon in the Internet & Network section. Check the ‘Web Sharing’ box.

Web Sharing option under the Sharing configuration in System Preferences
Figure 1 - Web Sharing option under the Sharing configuration in System Preferences

Now type this address in your browser: http://localhost/. You should get a message that reads: It works!

2 - Enabling PHP
PHP also comes bundled in Mac OS, but it’s disabled by default. To enable it we need to edit a hidden system file located in this path: /private/etc/apache2/httpd.conf.

I used BBEdit text editor to edit such a file (note that I marked the box Show hidden items in the screenshot below):

Editing a hidden file with BBEdit
Figure 2 - Editing the hidden system file httpd.conf with BBEdit

Now within that file search for:

libexec/apache2/libphp5.so

Delete the character # in the start of the line so that that entire line should now read:

LoadModule php5_module          libexec/apache2/libphp5.so

Save the file.

3 - Testing the installation
There’s nothing better to test the PHP installation than using its own information. To accomplish this, write a one liner simple .php file named test.php with this content:

<?php phpinfo() ?>

Place this file inside your personal website folder. Mine is located in this path:

/Users/leniel/Sites/test.php

Now let’s test this page by typing its address in the browser:

http://192.168.1.103/~leniel/test.php

As you see, the address points to my personal website as seen in Figure 1.

When you run this simple .php page you should get something like this:

Testing PHP installation with its own configuration’s information
Figure 3 - Testing PHP installation with its own configuration’s information

If your PHP installation is OK, the test page will display PHP's information. If it displays the page code, you need to restart the Apache server.

You can restart Apache by entering the following in Terminal:

sudo apachectl restart

Try to reload the page again. Everything should work.

Well done!. Now you can play with PHP on your Mac computer and write some neat codez. :)

Caveat
When I tried to restart Apache server I got the following error:

ulimit: open files: cannot modify limit: Invalid argument

I resorted to this solution: Mac OS X 10.6.5 broke my apachectl

Do you need the services of a computer engineer/consultant?

This post is to offer consulting services in the area of computer engineering with a tendency toward software development. Whatever fits the bill is also of my interest.

During the rest of 2010 and the start of 2011 I plan to work as a freelance developer.

Next year I want to get back to studying with a Master's degree. Though probably not an online masters.

What I want to do in the meantime...
I'm willing to work from home in a home office arrangement. Something that won't take up all my day. I prefer to have control over my work and time. So, I'm offering consulting services for whatever need you may have regarding your presence on the internet.

I can help you leverage your business putting you online. I can build your website and configure Google Analytics and AdSense if you're also interested in these services.

I can assist you with problem solving and technical issues.

Although I'm a native Brazilian, technology standards and English are my super power when it comes to software development.

If you think that outsourcing your development is rewarding, don't think twice. You'll get a great result with the work I do.

My specialties
ASP.NET MVC/P
C++, C#, Java, Objective-C, JavaScript
CSS, jQuery
LINQ, Entity Framework (EF), N/Hibernate, NoSQL
WCF, WebServices
Oracle, SQL Server, MySQL
Visual Studio, Eclipse, PL/SQL Developer
IIS, Tomcat
iPhone

I'm a rapid learner. This way if you need something done using any other technology, drop me a line and I'll consider it.

Note
I already have the tools necessary to implement any solution based on the above technologies.
Feel free to contact me using the link at the top of this page for further discussion.

My references
This blog
CV/Resume
StackOverflow profile
LinkedIn profile

Sincerely,
Leniel Macaferi
johnleniel