Showing posts with label Lightswitch. Show all posts
Showing posts with label Lightswitch. Show all posts

Monday, January 21, 2013

Using a custom edit screen in Lightswitch 2012 instead of the default modal dialog window

When you add a new Details Screen and check the ‘Use as default Details screen’, it will be used as edit screen by the Search Data screen, but not by the Editable grid screen.

In the Editable grid screen you need to write code behind the Edit button to open the Edit Details screen.

However instead of explicitly opening the Edit Details Screen by name, you can use the entities default screen property.

Instead of writing

partial void gridEditSelected_Execute()
{

Application.ShowCreateNewCustomerEdit(this.Customers.SelectedItem.Id);
}

Write this


partial void gridEditSelected_Execute()
{


this.Application.ShowDefaultScreen(this.Articles.SelectedItem);
}


This tip came from Justin Anderson on one of the Lightswitch msdn fora.

Monday, December 03, 2012

View a SQL Server Reporting Services Report in LightSwitch

Sql server Reporting Services report

This article on MSDN gives a rudimentary but working solution on how to view a SQL Server Reporting Services Report in LightSwitch. The solution works for both Lightswitch apps: web app or desktop app.

Update

Yann Duran wrote an interesting article: Add a Web Page URL to LightSwitch's Navigation Menu

Sunday, December 02, 2012

XtraReports for LightSwitch does not group on Date fields – convert date to string makes it work

This week I had to create a complex report with 3 group levels and further sorting on 4 detail fields. The problem was that the 3rd group field was a date field, and the report never grouped on the date field, but created a new group with the same data field with each detail line. To exclude an obvious mistake: The dates do not contain any time data, they are purely dates.

E.g In the Northwind database you have a Categories, Products, Sales. The report would be grouped on Category name, Product name, Salesdate. The detail would be sorted on 3 other numerical fields.

The project is written in VS 2010 with LightSwitch 2011 and DevExpress XtraReports 11.1.

This is the result I would like to see

  • Beverages
    • Chai
      • 2010-01-12
        • 12,00 13,20 10,00
        • 12,00 15,01 12,00
        • 13,00 13,25 12,12
      • 2010-01-13

The problem was that the report never came out like that, instead

This is what I saw in the XtraReports print preview

  • Beverages
    • Chai
      • 2010-01-12
        • 12,00 13,20 10,00
      • 2010-01-12
        • 12,00 15,01 12,00
      • 2010-01-12
        • 13,00 13,25 12,12
      • 2010-01-13

Of course, my subtotals for the day (not shown here) were completely wrong too.

Solution: add computed property to convert date into string, the group on computed property

After checking the dates do not contain any hour information (and they did not). After having tried setting all kinds of combinations in the group and sorting properties, I decided to take another approach. In the Lightswitch datasource that served as the LightSwitchDataSource for the report, I added a computed field to convert the date field into a string like yyyyMMdd.

Here is an example of the Method for the computed property groupSalesdate:

partial void groupSalesdate_Compute(ref string result)
{
result = this.Salesdate.ToString("yyyyMMdd");
}

In my XtraReport designer, I replaced the group field for the 3rd level by the computed field. The field that is displayed can remain as it is , so that the date field can be formatted properly.



The final result is what I needed:




  • Beverages



    • Chai



      • 2010-01-12



        • 12,00 13,20 10,00


        • 12,00 15,01 12,00


        • 13,00 13,25 12,12



      • 2010-01-13









Remark



I have not tried this yet with VS2012 and DeveXpress release for 2012.

Saturday, November 10, 2012

LightSwitch 2011 out of browser app shows completely blank screen after installation

Problem

After a migration of a LightSwitch application with XtraReports to a new web server with Windows 2008 and IIS 7, and after installation of the out of browser application on the clients, the app starts up with a blank screen. No menus or status bar is shown at all.

Solution

Some kind of error must have happened, but no indication at all of what happened. I have read about the blank screen in fora on the internet: it involves setting the basic authentication to false. So I tried to follow the advice, but in the IIS manager for the LightSwitch website there was not even Basic authentication under the authentication options.

  • Basic authentication is not installed on the web server:
    • On the 2008 server, run Server Manager
    • Select Roles / Web Server (IIS), in the Role services pane, add the Basic Authentication role, (along with Windows Authentication)
    • image
  • Restart IIS Manager, select the LightSwitch web site
    • select Authentication, verify that the Basic Authentication is disabled
    • image

After setting Basic Authentication and stopping and starting the web server, I started the client app again, and this time I was shown a Silverlight dialog box with an error message: ‘Could not load file or assembly DevExpress.Xpf.V11.1.LightSwitch.Common.dll…’

To solve the real problem I had to manually copy this file from my development machine to the server under …Inetpub\wwwroot\Myapp\bin

Tuesday, September 25, 2012

Lightswitch error ‘Exception has been thrown by the target of an invocation’

Problem

This error message popped up after the Lightswitch 2011 application was deployed on a new server and when the application was started for the first time. The default screen comes up, but without data in the screen, then the messagebox with the error:

An error occurred while running the screen.
Error details: Exception has been thrown by the target of an invocation.

image

After clicking ‘Close Screen’ a second messagebox pops up with the message:

Invalid operation. Dispatcher has been stopped.

image

The problem in this case is not as much correcting the error, but finding out what the error actually is. To do so we need to turn diagnostics on

DIAGNOSE

To diagnose this kind of error in Lightswitch, diagnostics needs to be enabled. See the MSDN article How to: Enable Diagnostics

Since this problem did not occur on my development computer, but after deployment on the new Windows Server, we can turn the diagnostics on in the server without redeploying the solution. Either way do not forget to switch diagnostics off on the server once the cause of the error has been found.

To enable diagnostics on the server

The diagnostics feature will generate a Trace.axd file in the directory where the app is deployed.

  • Use IIS Manager and connect remotely or log on to the server and start IIS Manager on the server.
  • In the Connections treeview, under <your server>/sites/Default Web site/<your app>
  • In the features view, click on Application Settings
    image
  • In the Application settings pane, change Microsoft.LightSwitch.Trace.Enabled to true,
  • Set …trace.Lavel to Error
  • Set …trace.LocalOnly to false. If you leave this to true then you can only browse on the server to localhost to look at the diagnostics, in my case security settings on the server browser did not allow me to do this. So when set to false I can browse the trace file from the client PC.
  • This is the Applications settings panel after applying the changesimage
  • On the client PC browse to the app to invoke the error once more.
    http://myserver/myapp
  • Then browse to the same URL with the trace file name appended http://myserver/myapp/Trace.axd
    image
  • The last line of the trace log most probably contains the error information (in my case it did). Click on the view details link to open.
    image
  • The error shows that there is a SQLconnection problem.

Solution

finally the solution was that the SQLserver could not be connected from the new app server unless the full domain name was used. I fixed the connection string in visual studio accordingly and all worked fine.

Lightswitch deployment error: MSDEPLOYAGENTSERVICE could not be contacted

Problem

For the first time deployment of a Lightswitch application on a windows 2008 server, I received the following error message in the Visual Studio Error message panel:

Web deployment task failed.(Remote agent (URL http://bebrqsql01/MSDEPLOYAGENTSERVICE) could not be contacted. Make sure the remote agent service is installed and started on the target computer.)

Remote agent (URL http://bebrqsql01/MSDEPLOYAGENTSERVICE) could not be contacted. Make sure the remote agent service is installed and started on the target computer.

The server is a windows 2008 R2 server with IIS services and with the Lightswitch 2011 prerequisites installed as described in Configure a server to host LightSwitch (Visual Studio 2010).

 

Solution

Log on to the target server, check if the Web Deployment Agent service is started, set it to start automatically . After first time Installation server feature IIS Web server role, this service will not have been started. Start the service

image

Another possible cause can be that the username specified in the Publish Output tab of the Lightswitch Publish Application Wizard, does not belong to the local administrators of the Application server. Solve this by adding the user, or the group that he is in, to the local Administrators group on the application server.

Sunday, September 23, 2012

How to update query parameters on Xtrareport

Question

When an Xtrareport report in a Lightswitch project is based upon a query with parameters and new parameters have been added to the query after the report was designed, how do you update the report parameters?

Explanation

In Visual studio in logical view, modify the query to add new parameters.

Save the query and rebuild the project.

Switch to file view

go to Server folder

open the report in design modus

Select the Lightswitch datasource

In the properties panel, Click on the link Update QueryParameters

image

The parameters are now added to the Query Parameter Collection. You can verify this by clicking on the Ellipsis button next to the (Collection) text to open the dialog box with the parameters from the query.

image

Tuesday, September 18, 2012

Out-of-browser Lightswitch app keeps on showing the update to new version page and refuses to start

Problem

At one site I have a Lightswitch out-of-browser app that has been upgraded quite a lot. On one of the pc’s the app detects the latest version and shows the upgrade message to the new version in the browser, but after upgrading and restarting the app it keeps showing the upgrade page requesting the user to make the same upgrade again. At first I thought that the user had not used this app for a while and that the app was being upgraded one version at a time. But the upgrade page was showing the latest version number.

Uninstalling the app via the add / remove feature in the control panel, did not help. The app was reinstalled after browsing to the URL of the app on the server, but even then the upgrade page kept showing up.

Solution

The solution was to remove the app from the Silverlight Application Storage.

In the Windows Start menu go to All Programs / Microsoft Silverlight / Microsoft Silverlight. The configuration window opens.

image

Select the Application Storage tab.

image

Select the URL of your application and click on the Delete… button. A confirmation window opens. Click on Yes to confirm.

image

The app is now deleted from the Application Storage.

Click on the OK button to close the Silverlight Configuration window.

Start the app again. It will show the upgrade window once more and after installation, the latest version should start (in my case anyway).

Thursday, August 16, 2012

XtraReports report viewer error : A control must be selected

Problem

After the upgrade to a new version of XtraReports, the screens to view a report preview show an error message: ‘Report Viewer: A control must be selected.’

image

Solution

In the screen design of the report viewer, see in the rows layout, under Screen command bar,

image

change the control from Custom control to ReportViewer control

image

Wednesday, June 06, 2012

Lightswitch deployment on Win2008R2 server

Before the first time installation of Visual studio Lightswitch 2011 apps on Windows 2008 R2 server, some prerequisites must be met on the server.
An article on MSDN can be found here

Access control in LightSwitch apps

Beth Massi has written an article about access control with  Lightswitch studio 2011 here.

Wednesday, May 30, 2012

How to programmatically modify a foreign key value in a Lightswitch entity

Problem

Sometimes the business requirement of an application is such that a foreign key value in a database record or set of records needs to be changed into another value automatically. E.g. in the AdventureWorks database a selected set of products has to be given a new product subcategory.

In principle this means that the value ProductSubCategoryyId in the Products table needs to be changed from value A to B. In a Lightswitch entity based on the database table, the value of the Id is hidden, instead the entity propagates an instance of the ProductSubCategory entity.

Solution

To change the value of the foreign key programmatically you need to change the SubCategory not the Id.

Example

Suppose we have an editable grid screen base on the AdventureWorks Products and the product that is currently selected needs to have another default SubCategory. A button on the Datagrid command bar has execute code behind to do so.

The trick is to create a new instance of the subcategory with the Id you want and then assign this new instance to the product in question. In the example we want to assign a subcategoryId with value 1 to the selected product.

partial void ModifySubCategory_Execute()
{
    int NewSubCategoryId = 1;
    ProductSubcategory s = DataWorkspace.AdventureWorksData.ProductSubcategories_SingleOrDefault(NewSubCategoryId);
    Product p1 = this.Products.SelectedItem;
    p1.ProductSubcategory = s;
}


Once the data will be saved the SubcategoryId value will be written into the product table.

Sunday, May 13, 2012

Print alternating background colour in detail section of XtraReports for Lightswitch

Problem

The readability of a printed report with text and numbers can be improved by printing the details with and alternating colour, e.g. lines in white background alternate with lines in light grey background.

image

Solution

In a LightSwitch application with an XtraReports report, we can make the colours alternate by creating an EvenStyle and OddStyle in the Styles collection in the properties of the detail section. One of these styles will be given a different background colour from the other.

Prerequisites

The example is based on a view vEmployeeDepartment from the AdventureWorks database. The view has been added to the Datasource of the Lightswitch project. To create a report with grouping see my article about grouping with XtraReports 

How to set alternating background colours

  • In the XtraReports design, select the detail section. Click on the grey Details band.
  • In the properties window, expand the Styles Collection property
    image
  • The EvenStyle, OddStyle properties are displayed. Click on (none) near the EvenStyle.
    image
  • Click on the dropdown arrow, in the dropdown list, select (New)
    image
  • A new style is created with the name xrControlStyle1. Repeat the above step for OddStyle.
    image
  • A 2nd style is created , called xrControlStyle2.
    image
  • Now we have to set the background colour of these styles to a different colour. By default the background of both styles will be transparent. We will only modify the background of the OddStyle to WhiteSmoke. To modify click on (Collection) of the Styles collection, so that a button ‘…’ appears.
    image
  • Click on the button ‘…’. IN the Styles editor dialog window select ‘xrControlStyle2’.
    image
  • In the right-hand panel, click (Not set) near the BackColor property to open a dropdown with colours. Select the WhiteSmoke colour.
    image
  • Click Close.
  • Now the background will be printed in alternating white and WhiteSmoke colour as shown in the start of this article.

Remark

In XtraReports, you have to fit your labels together horizontally, so that there is no white space. Because the details background only shows where there are controls. It is not quite as one would expect. If your labels don’t fit together the alternate colour will not show up.
image

Tuesday, April 24, 2012

LightSwitch hangs while publishing

From the LightSwitch forum, as a reminder for myself, because I have had to fix a similar problem.

“We have identified an issue when packaging an IIS site with "Update existing database" selected.  This reproduces when using a connection string which does not have db admin privileges to generate the script.  Please try again with this permission and let me know if it continues.”

Erik - LightSwitch QA

“I tried that, and it worked for me.  Publish is now successful.

Being new at this, let me tell others like me exactly what I did:

Open SQL Server Management Studio, and connect to the local server, where I have the existing database from having published my package the first time, when publishing the first version of my app.

Go to Security \ Logins

Right click on the user that has admin rights to your database in your live environment.

Click "Properties"

In the Login Properties Page, go to "Server Roles"

Make sure "sysadmin" is selected.

Click OK

Now publish your package using this user and this user's password in your connection string.”

Monday, April 23, 2012

How to print the value of a LightSwitch query parameter on a report with XtraReports

Problem

Last week one of my customers wanted a report with the selected parameter values in the heading of the report, for instance a period with a start date and end date. Because not all data necessarily contains values for the exact same range, like the exact start or end date, it is not always obvious which range the user has selected for the report.

Solution

The query parameters collection is available to the report code on the server side. For each section of the report, like a page header, group header or detail section, there are events that can be triggered, most notably ‘Beforeprint’. In the event code we can read the parameter data and copy that into a label on the report section.

Step by step demonstration

Prerequisites

This example was made with the SQL Server 2008 AdventureWorks database. A LightSwitch project called AdventureWorksLS was created and the Datasource AdventureWorksData has been added to the project. We use the Products table which has a Date field called ‘SellStartDate’. Based on this field we create a report preview that shows products within a certain period of start dates.

Create a query with parameters
  1. Add a new query to the Products entity, right click on Products, Add Query.
    image
  2. In the Query design screen, rename the Query1 to qryProductsBySellStartDate
  3. Add Single filter, Where SellStartDate Is Between @, Add New…
    image
  4. Create Parameter StartDate of type Date (specifically Date and not DateTime)
  5. Continue the filter after ‘and’, @, Add New…
  6. Create parameter EndDate of type Date, the final query design looks like this
    image
  7. Build the project
Create a report based on the query
  1. In project explorer, switch to file view.
  2. right click on the Server project, select Add / New Item…
    image
  3. In the Add new item dialog window, Select XtraReport Class, change the name to ReportProductBySellStartDate.cs, click Add
    image
  4. In the report desing panel, click on the smart tag in the upper left corner, to open the Report Tasks menu, select datasource qryProductsBySellStartDate
    image
  5. The datasource is added and is called ‘lightSwitchDataSource1’ (this name will be used in the code).
  6. Optionally
    1. in the Report Tasks menu select ReportUnit: TenthsOfAMillimeter (can also be set in the reports properties)
    2. in the Properties panel, with the ReportProductBySellStartDate, set paperKind to A4.
  7. From the Field List, drag the ProductId and Name field to the Detail section of the report, reduce the height of the Detail section.
    image
  8. Right click on the design surface (but not on the productid or name label), select Insert Band / Page Header
    image
  9. A new header band appears above the Detail section.
    image
  10. From the Toolbox, DX.11.1: report controls, drag the XRlabel onto the PageHeader band. In the properties panel of the xrLabel, change the (Name) to lblStart
    image
  11. Drag another xrlabel onto the Pageheader and rename this to lblEnd.
  12. reduce the height of the Pageheader;
  13. Select the PageHeader band, in the properties pane, click the events button
    image
  14. Double click in the text box next to the BeforePrint event, this generates code for this event
    image
  15. In the code we can now set the text properties of the 2 labels to the value of the 1st and 2nd parameter of the lightSwitchDataSource1 object. The parameter values are of type Date, we cast the value to DateTime and then format this to a short date string, which is then put into the Text property of the label.
    private void PageHeader_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    {
        this.lblStart.Text = ((DateTime) lightSwitchDataSource1.QueryParameters["StartDate"].Value).ToShortDateString();
        this.lblEnd.Text = ((DateTime)lightSwitchDataSource1.QueryParameters["EndDate"].Value).ToShortDateString();
    }

  16. Build the solution


Create a report preview screen in the LS project.


  1. in the solution explorer switch to Logical view.

  2. right click on Screens, Add Screen..
    image

  3. In the Add New Screen dialog, Select a screen template Report Preview Screen, change the screen name to ReportProductsBySellStartDate, click OK
    image

  4. In the AdventureWorks Screen design panel, click on Write Code, select ReportProductsBySellStartDate_Activated, change the name of the Server report to ReportProductBySellStartDate (beware this is without an ‘s’ after Product, excuse me for the lousy names)

  5. Save all and build.

















Debug and test the report


  1. Debug

  2. In the menu select Report products by Sell Start Date

  3. In the Report Products tab, in the StartDate, select the data, click on the month name, this shows a list of months for the current year, click on the year, this shows the years, scroll back, select 1998, select januari, select day 1.

  4. In the EndDate select 31 december 2000. Click Submit. the report preview is shwon with the parameter values in the page header
    image





Conclusion


To give the user a better understanding of the reports he printed, we can easily add additional data on the report, such as the query parameter data.

Thursday, April 19, 2012

Provide a combobox with parameter values in XtraReports for LightSwitch

Problem

When using XtraReports for LightSwitch based on a filtered query, the default behavior for the XtraReports preview screen is to show a textbox in which you can type the value of the parameter. With Date values the XtraReports has a calendar dropdown, but for numeric or string data like identifiers or codes that refer to primary keys in lookup tables, we have to provide some code to build a combobox list to facilitate life for the user.

Prerequisites

This article is a follow-up on my article on how to create a 3 column report.

In this example a report preview screen LabelProductsByCategory was created based on a query qryProductsByCategory with a filter with one integer parameter (CategoryId)

image

The report preview screen uses a numeric up-down control to enter a category Id. Here the user would appreciate an combobox with a list of the names and not the id’s.

image

Solution

The solution I provide is based on the XtraReports tutorial Provide Custom Editors for Report Parameters. Some lines of coding are needed to replace the standard up-down box by a DevExpress ComboBoxEdit control. This control is installed together with the XtraReports controls.

Advantages of the ComboBoxEdit control

This control has properties that can be set improve the user experience, in particular:

  • ItemsSource – can be set to a List of objects
  • ValueMember – will contain the value of the column that contains the value we need for the parameter (in most cases it is an Id column)
  • DisplayMember – will contain the column value that show a human readable text (in most cases the name column)

The code in the example under step 3. will illustrate this.

Example

We need to add code in the preview screen to generate a local list object with values from the categories table that can be used by the ComboBoxEdit control.

  1. In the solution explorer right click on the report preview screen and select View Screen Code.
    image
  2. In the report preview screen code above the namespace,
    1. Add a reference to the DevExpress.Xpf libraries
      using DevExpress.Xpf.Editors;
      using DevExpress.Xpf.Printing;

  3. In the class LabelProductsbyCategory


    1. define a List object in the report preview screen class
    2. define a customize parameters event handler, in here the ComboBoxEdit will be created.
    3. add the address of the event handler to the report preview model
    4. In the Activated event populate the list with the categories entities.


      public partial class LabelProductsByCategory
      {
       
          // 1. define a list object
          List<object> categories;
       
          // 2. define a customize parameter event handler
          void model_CustomizeParameterEditors(object sender, CustomizeParameterEditorsEventArgs e)
          {
              if (e.Parameter.Name == "ProductCategoryID")
              {
                  var editor = new ComboBoxEdit();
                  editor.ItemsSource = categories;
                  editor.ValueMember = "ProductCategoryID";   // this is the column name with the value that will be used 
                  editor.DisplayMember = "Name";  // this is the column name with the text that will be displayed
                  e.Editor = editor;
                  e.BoundDataMember = "EditValue";
              }
          }
       
          public void CustomizeReportPreviewModel(DevExpress.Xpf.Printing.ReportPreviewModel model)
          {
               // 3. add the customize event handler to the model
              model.CustomizeParameterEditors += model_CustomizeParameterEditors;
          }
       
          // 
       
          partial void LabelProductsByCategory_Activated()
          {
              this.ReportTypeName = "LightSwitchApplication.LabelProductByCategory";
       
              // populate the List object
              categories = new List<object>();
              foreach (ProductCategory category in new DataWorkspace().AdventureWorksData.ProductCategories)
              {
                  categories.Add(category);
              }
          }
      }

  4. Save and debug.

    1. When we open the preview screen, click on the ComboBoxEdit control the list with 4 Categories opens.
      image
    2. Select an item, e.g. ‘Clothing’ and click ‘Submit’
      The report is shown with products that belong to the category ‘clothes’
      image

Conclusion


The XtraReports preview screen can be based on a filtered query, the parameters of which are presented automatically in a text box. With a little coding and a ComboBoxEdit control we can then make the selection of the parameter values user-friendlier.

Wednesday, April 18, 2012

Using the summary property of a table to make records more readable

Summary properties are displayed anytime you use the Summary control on a screen or when LightSwitch generates a layout for you that needs to display a description of the entity.

To show the user a better string representation of the records in some tables, we can use a computed column as the summary property of a table. By default summary properties are set to the first string column of an entity. For example whith the BillOfMaterials entity from the AdventureWorks database, the Summary Property will be set to the column UnitMeasureCode.

image

A nicer representation could be the Assembly product name, the assembly product is linked by a foreing key productassemblyId to the BillOf²Materials table. In the entity it is somewhat awkwardly represented as Product1

image

First we will add a computed property that displays the name of the product and then we set this computed field as the Summary Property of the entity.

  1. To add a computed property:
    1. In the BillOfMaterials design, click on the computed property button
      image
    2. Rename property1 to ProductComponent and then click on the Edit method link in the property panel.
      image
    3. Add the line result = Product.name in the Compute method
      partial void ProductComponent_Compute(ref string result)
      {
          // Set result to the desired field value
          if (Product != null)
              result = Product.Name;
      }

  2. To set the computed property as the summary property


    1. Select ‘BillOfMaterial’ in the properties panel choice list (or click on the title BillOfMaterial) in the design window.

    2. Change the summary property to ProductComponent.
      image

  3. To prove everything works as expected, create a List and Details screen


    1. In solution Explorer, Right click on the Screens folder, Add screen

    2. In the Add new screen dialog, select screen template ‘List and details screen’, Screen Data: AdventureWorks…BillOfMaterials, additional data to include is checked. Click OK.
      image

  4. Build and debug the app. The List panel will display the name of the product instead of the Unit Measure code.
    image










Remark


The use of computed property columns as summary column has some disadvantage: The computed column can take some time time to calculate and display, You cannot sort on the computed column either. Fancier solutions can be made with WCF RIA data services on the server side.