Wednesday, February 13, 2013

Deploying a Lightswitch app in a 2 Tier scenario

Welcome back everybody!

After struggling a little bit with Lightswitch deployment, I would like to share straight steps that I noted down during the process in the past days trying to get it done.

Development Scenario
Visual Studio 2012
Ligthswitch C# app
Deployment mode: Desktop

Production Scenario
We will have a server (for testing purposes I created a Windows 7 VM) where the Database is going to be hosted in a SQL Server Express instance.  The app will be installed in this server that will act as a client also, and in other network computers (clients).

Creating the deployment package
1.      Go to the Solution Explorer and double click the properties node of the project.
2.      Click on the Application Type tab and click the Publish button.
3.      Follow the Wizard paying attention to:
a.       Application Type: Desktop
b.      The application will be hosted locally
c.       Select the path where you want VS to drop the output (installation files) and select the option "Create a script file to install and configure the database"
d.      Write a default connection string for now (if you already know what it should be like, write it). Something like this should do (replace ChosenDatabaseName with the name you will give to your database):
Server=localhost\SQLEXPRESS; Database=ChosenDatabaseName; Integrated Security=true;
e.       Check the "Generate the SQL database script and specify the name to the database"
f.       Select what is most appropriate for you with the prerequisites
g.      Specify a certificate if you have it
h.      Publish
4.      Go to the output folder and grab the generated files. Copy them to the server

Configuring the Server
1.      Install the prerequisites (at least, .Net Framework 4 has to be installed. This, you will have to, or won’t have to, depending on the OS you are targetting)
2.      Install the latest Silverlight version
3.      Download MS Sql Server 2008 R2 Express
5.      Install them
6.      Put the Sql files that were included in the output in C:\ and execute them. For example, to create the database, you would move the MyApp.sql file from the path were you placed the output to C:\, open a command line window and type the following:
sqlcmd  -S  ServerName\SQLEXPRESS  -i  C:\MyApp.sql
Wait until the process finishes.
7.       Now, if you did not write the actual connection string in the publishing wizard, modify it in the web.config file that is found among the output files inside the Application Files folder. The connection strings section should look something like this:
<connectionStrings>
    <add name="_IntrinsicData" connectionString="Server=ServerName\SQLEXPRESS;Database=DatabaseName;Integrated Security=true;" />
</connectionStrings>
8.      Execute the Setup file.

If you configure the web.config like shown above and then execute the setup in any other machine connected to the same network, now you have your scenario clients-server scenario implemented (make sure your Server is reachable from the clients).

Final Words
Visual Studio Lightswitch is a great tool that saves you a lot of time and makes it easier to write business applications, but deploying your app can be a little bit tricky, especially the first time. As always, please feel free to write your comments, doubts, suggestions, concerns, whatever you want =D (if it is related of course). Hope it helps.

Thanks for reading :)

Wednesday, May 23, 2012

Cannot Write to the Registry Key


Welcome back to my blog!

I've been very busy with some projects that I almost forgot I have a blog :-S
Maybe I will share some stuff in future posts about the WP7 and Windows 8 projects I've been working on.

But for today, just one small tip for writing in the Windows Registry.
RegistryKey windowsRegKey = Registry.LocalMachine.OpenSubKey("pathToTheWantedSubKey");

If you then want to add a sub key, or a value, and write something like this
windowsRegKey Registry.LocalMachine.OpenSubKey("nameOfMyNewSubkey");
you will get an error saying something like "Cannot Write to the Registry Key".

First thing that comes to mind is if the application is running under administrator privileges... this is also needed, but is not the only point. Whenever you open a Registry Subkey use the overloaded method, and pass a true to specify that you will edit it. Something like this:
RegistryKey windowsRegKey = Registry.LocalMachine.OpenSubKey(ShutdownEventTrackerSubkey, true);

Hope it was helpful. As always, feel free to leave any comment, question or suggestion. Thanks for reading!

Thursday, January 5, 2012

Silverlight Overlay Notification


Welcome back to my blog!

This is the first post of 2012, so just before getting started, I'd like to wish you a happy new year.

Introduction

This time I want to share something very simple for Silverlight. I do not like applications that continuosly bother me with popup messages to make me aware that something happened. I do not like a message box coming up saying "Changes were saved succesfully" right after pressing the save button. I want to keep working or doing some other stuff without being interrupted. I would like to be told that it worked if it allows me to keep going, and of course, I want to know if something went wrong.

You know during Christmas a lot of messages full of best wishes are going around . I sent one of those to one friend and after a while an Overlay Notification appeared at the bottom of my Galaxy's screen saying "Message received by [contact]". Then I realized that this is the kind of notification that I, as an user, like. Therefore, is the kind of notification, that I, as a developer, would like to use henceforth (unless until I find something better :-D ).

The Code

Let us create a User Control. Our control will be the already mentioned Overlay Notification. We'll make it appear and disappear after a while without user interaction. This could be the XAML code:

<UserControl x:Class="SilverlightTestApp.Controls.OverlayNotification"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <UserControl.Resources>
        <Storyboard x:Name="ShowMessage" Completed="ShowMessage_Completed">
            <DoubleAnimation
            Duration="00:00:06"
            From="0.00"
            To="1.00"
            AutoReverse="True"
            Storyboard.TargetName="Popup"
            Storyboard.TargetProperty="Opacity"/>            
        </Storyboard>        
    </UserControl.Resources>
    
    <Grid x:Name="LayoutRoot" Background="White" HorizontalAlignment="Center" >
        <Border BorderBrush="Black" BorderThickness="1" MinWidth="150" MaxWidth="550" MaxHeight="75"
                   CornerRadius="4" Background="Transparent" Visibility="Collapsed" Opacity="0" x:Name="Popup">
            <TextBlock x:Name="lblMessage" HorizontalAlignment="Center" TextWrapping="Wrap" MaxWidth="400" MaxHeight="75"></TextBlock>
        </Border>
    </Grid>    

</UserControl>


We have a Storyboard that will be triggered whenever we want to show the Notification. It will last 6 seconds (plus another 6 because of the AutoReverse=true). And will change the Opacity of our notification area to give the impression that it fades in and out.

Then we have a Border with rounded corners. We'll have to make it visible whenever we want to show the message and hide it when the Storyboard is done. Inside of this Border we will have a Textblock where our message will be displayed.

Let's take a look at the code behind:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SilverlightTestApp.Controls
{
    public partial class OverlayNotification : UserControl
    {
        private string _message;
        public string Message
        {
            get
            {
                return _message;
            }
            set
            {
                _message = value;
                lblMessage.Text = value;
                Popup.Visibility = Visibility.Visible;
                ShowMessage.Begin();
            }
        }

        private System.Windows.Media.Color _color;
        public System.Windows.Media.Color Color
        {
            get
            {
                return _color;
            }
            set
            {
                _color = value;
                var newBrush = new SolidColorBrush();
                newBrush.Color = value;
                lblMessage.Foreground = newBrush;
            }
        }

        public OverlayNotification()
        {
            InitializeComponent();
        }

        private void ShowMessage_Completed(object sender, System.EventArgs e)
        {
            Popup.Visibility = Visibility.Collapsed;
        }
    }
}

We will expose at least the Message property (we also have the Color property for the font). Notice that everytime we set the Message property we update the Textblock's text, make the Border visible and trigger the Storyboard. Also noticed that we handle the Storyboard's completed event to hide the Border.

To use it, just add this new User Control into the view where you want to use it in the same way that you would place a Textbox or any other control:

<my:OverlayNotification x:Name="myOverlayNotification"/>

Then, whenever you want to show a Notification, just set the Message property with the message you want to display:

 myOverlayNotification.Color = Colors.Red;
 myOverlayNotification.Message = "This is a test notification";

Final Comments

Feel free to play around with it modifying the layout and appeareance of the control in the XAML or adding more properties to be able to customize it more, for example, adding a BackgroundColor property. Please share your changes in the comments so everybody can learn or use your improvements.
This is just a simple example, but you could also adapt it to use it with the MVVM pattern.

As always, thank you very much for reading. Leave any comment, concern, question or suggestion that you may have.

Hope it helps!






Wednesday, November 30, 2011

Missed Reconcile after Gated Check-in


If you work with Visual Studio Team Foundation Server and are using Gated Check-ins, after the build is done in the server you receive a nice Message Box with a nice Reconcile button.

Sometimes it happens that you close or miss that message… and then what? Your files are still checked out, the projects you added are with the yellow cross besides them in the Solution Explorer, etc.

Ok, never mind. Just go to the Team Explorer, open the Builds node and double click the corresponding build definition (if you know it) or just All Build Definitions. Use the filter that appears in the top of the opened tab to find the builds you recently triggered.

Once you find the one you're looking for, right click it and click on Reconcile Workspace in the Context Menu.



Now you are able to follow the same steps as if you wouldn't have missed the Message Box after the Gated Check-in with the Reconcile button.

As always, feel free to leave any comment, suggestion or question that you may have.

Hope that helps!

Monday, November 21, 2011

There appears to be a discrepancy between the solution's source control information about some project(s) and the information in the project file(s)


TFS Source Control discrepancy

Recently we had a problem at work with the TFS. It was down for almost 3 hours. The TFS team sent us and email saying that we should connect to a new server from Visual Studio. So we did.

After connecting to the new one I saw some project files in my pending changes that I did not checked-out. I tried to make an Undo and receive the following error:



"There appears to be a discrepancy between the solution's source control information about some project(s) and the information in the project file(s)"

Open the project file (with notepad, or unloading the project and right clicking it and selecting Edit) and look for the node <SccAuxPath> and see the value it has. Now, right click the project file again in the Solution Explorer (if you unloaded it, reload it) and click on View History. Double click in the last one that was ok, so you will see the file's code and you can now look for the same node. You will see a different value in the Server's project file than the one you have in the Local's project file.

The only thing you should do is align them. Use the same value for them. Probably it is best to update the Server's file with the new value of the Server's address (your Local file version would probably have the new Server's address).

Another option you have is to set in both "SAK" (without "") in every Scc starting node (there should be 4). "SAK" is, shortly explained, a flag that tells Visual Studio that the project is under Source Control and the real bindings are persisted in the mssccprj.scc files.

"...csproj.vspscc could not be found in your workspace or you do not have permission to access it."

Together with the other error I faced this one. In order to be able to solve this the first thing is to check if the user under whom you are running VS has permissions enought. If the user does, then you have a problem with your Workspace. The only thing that worked in my case was re-creating it. Make sure you check-in all the changes you want to keep  before deleting your current Workspace. You can create the new one with the same name and in the same location.

As always, please feel free to leave any comment, suggestion or question you may have. Hope this helps!

Thanks for reading!

Wednesday, November 16, 2011

Open, Modify and Save an Xml

Welcome back to my blog!

Introduction

This time I will be sharing something simple, that sometimes is needed and usually everybody tends to take more steps than needed.

We will be opening an Xml file, modifying it and saving the changes. Let's assume the following scenario to understand the example (I know is a dummy scenario that won't probably happen, but it is enough to get the point):

We have an Xml file with Customers. Every child node will have a single customer with its information in its attributes. Let's imagine that the attributes we have are Id, Name and Email. We will update the email address for a given customer.

The Code



private  void ChangeCustomerEmailAddress(string filename, int customerId, string newEmailAddress){

            bool changeMade = false; //Flag to check if changes were made and we need to save them

            var xmlFile = new XmlDocument();
            try
            {
                xmlFile.Load(filename);
                XmlNode rootXmlNode = xmlFile.DocumentElement;
                if (rootXmlNode != null)
                {
                    foreach (XmlNode childNode in rootXmlNode)
                    {
                        if (string.Equals(childNode.Name, "Customer"))  //Change Customer with your ChildNode Name
                        {
                            foreach (XmlAttribute attribute in childNode.Attributes)
                            {

int currentCustomerId = 0;

                                if (string.Equals(attribute.Name, "Id"))
                                {
                                       currentCustomerId = attribute.Value;
                                }

                                if (string.Equals(attribute.Name, "Email")  && currentCustomerId == customerId )
                                {
                                        attribute.Value = newEmailAddress;
                                        changeMade = true;
                                        break;
                                 }

                            }                            

                        }
                    }
                }

                if (changeMade)
                {
                    xmlFile.Save(filename);
                }

            }
            catch (XmlException ex)
            {
                // Your error handling logic goes here.
            }

}

Understanding the code

We have a method that receives the whole path to the Xml file we want to modify, the customer ID and the new email address.

We create a new instance of the XmlDocument class and load the document into memory. We loop through the nodes and look into the attributes. When we find the Id attribute, we save its value into a variable (currentCustomerId), so when we reach the Email attribute, if the current customer is the one we want to modify, then we set the current attribute(Email)'s value with the new email address and we exit the loop.

Final words

It is that simple to modify an Xml on the fly in just one step. I hope it helps. Please note this is only a sample code. Feel free to leave any comments, questions, suggestions or whatever your concern is. 

Once again, thanks for reading!

Friday, August 26, 2011

WCF The remote server returned an error 415

Welcome back everybody!

This time I just want to share a small tip. Working with a Silverlight-enabled WCF Service I got the following error after making a few changes: The remote server returned an error 415 (obviously the error message was way much longer). The weird thing is that there were no errors when compiling.

I started googling to find out how to solve it, but no suggestion worked for me. So I went backwards upon what I've done.

The WCF service uses a custom type defined in a class. I just added a few new properties to the class and realized that one looked like this:

Public Property propertyName As Nullable

I just forgot to specify the type. So if you get this error, go backwards to the last thing you've done and check that you did not misspell anything and that you specified all the types correctly. So, solution in my case:

Public Property propertyName as Nullable (Of Date)

Hope it helps!