Azure Powershell

This was useful

http://michaelwasham.com/2012/06/08/automating-windows-azure-virtual-machines-with-powershell/

When I installed Powershell I think I downloaded a publishsettings file. I copied this to c:\Temp and renamed it without spaces. Then as per above I used:

Import-AzurePublishSettingsFile ‘c:\temp\<publishsettingsfilename.publishsettings>’

Everything then worked including:

Get-AzureSubscription

Get-AzureStorage

 

To store a script use notepad and change the file extension to .ps1

Error

File ps1 cannot be loaded because running scripts is disabled on this system

Solution

http://support.microsoft.com/kb/2411920

To resolve this issue, follow these steps:

  1. Run the Windows Azure Active Directory Module for Windows PowerShell as an admin. To do this, click Start, click All Programs, click Windows Azure Active Directory, right-click Windows Azure Active Directory Module for Windows PowerShell, and then click Run as administrator.
  2. Set the execution policy to Unrestricted. To do this, type the following cmdlet, and then press Enter:
    Set-ExecutionPolicy Unrestricted
  3. Run the Windows PowerShell cmdlets that you want.
  4. Set the execution policy to Restricted. To do this, type the following cmdlet, and then press Enter:

    Set-ExecutionPolicy Restricted

 

Alternatively

  1. Open mmc.exe
  2. Add snap-in for Group Policy – local computer
  3. Computer configuration
  4. Administrative templates
  5. Windows components
  6. Windows Powershell
  7. Turn on Script Execution
  8. Right-click Edit
  9. Enabled
  10. Execution policy bottom LHS = Allow Local Scripts and remote Signed Scripts

After finish disable it.

 

http://blog.whatsupduck.net/2010/09/issues-with-configuring-powershell.html

How to build help documentation using Sandcastle – XML comments

After building XML Comments / Documentation and viewing these in a browser it may be useful to create documentation. Microsoft no longer develop a tool, but a tool Sandcastle they initially developed has continued.

This is some of my experience:

In addition to the normal Sandcastle, I installed the Sandcastle Visual Studio integration package.

Sandcastle have large documentation, but I found the basic steps were:

  1. Open Visual Studio
  2. Add New Project > Documentation > Sandcastle Help File Builder Project
  3. Add Documentation Sources – Reference to the project you want to document
  4. Build the project
  5. To view your new help file
    1. Use Menu > View > View Help File
    2. Or Open the Folder Location and open the Help folder
  6. Find the file ContentLayout.content
    1. Change the title from [TODO]
  7. You may get a lot of warnings and lots of ‘Red’ ‘missing documentation’
    1. To suppress these use Properties > Missing Tags and uncheck warning
    2. Or to use it to find missing documentation, uncheck
  8. All seems good so far.

See also

Sandcastle

XML Documentation

MSDN

ASP.Net How do I call a code behind method from an image

Following was html

<a href="CatalogueByList.aspx?VehicleTypeID=3" target="_self">
<img id="CatalogueCVImage" style="border-style: none; height: 94px; width: 172px; margin: 20px;" alt="Automotive Catalogue" src="Resources/ebc-catcommercial-button.jpg" />
</a>

Following is code behind call to a method from an image

<asp:ImageButton
runat="server"
id="CatalogueCar"
ImageUrl="Resources/home-auto.jpg"
AlternateText="Automotive Catalogue"
CssClass="myImage"
style="border-style:none; height: 94px; width: 172px;margin: 20px"
OnClick="OpenCatalogueAutomotive"
/>

Then code behind as:

Protected Sub OpenCatalogueAutomotive(ByVal sender As Object, ByVal e As EventArgs)
ViewState("VehicleTypeID") = 1
Response.Redirect("CatalogueByList.aspx?VehicleTypeID=1")
End Sub

End

How to consume a web service in code directly

As well as using a wizard it is possible to access web services using code. These are the steps.

  1. Open a Visual Studio Command Prompt
  2. Navigate to a suitable directory e.g. c:\Temp
  3. Use WSDL. Examples
    C# is default language
    wsdl http: //  …myservice.asmx
    For VB use
    wsdl /language:vb http://.. myservice.asmx
    Your service might be .svc
  4. Press return and the wsdl program should write out a file for your consumption
  5. This creates a web service proxy, which will talk to the service.
  6. In your project create a folder say named Service
  7. Add in your new file
  8. Add reference to System.Web.Services
  9. Add code similar to:

myService MyService1 = new myService()

var result = myService.myMethod();

To create a batch file to do this automatically

Thanks to:

http://stackoverflow.com/questions/5879076/how-to-create-a-batch-file-for-visual-studio-command-prompt

call “C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat” x86
wsdl /language:vb /out:MyServiceName.vb http:// … myservice.svc
pause

Why does the consumed service return arrays when I specified a List(of T)

WCF tries hard to not create services which are .Net dependent. So by default the return of List(Of T) will return an array.

If you add a service using the .Net UI, then there is an option:

Configure Service Reference > Always Generate Message Contracts > Collection Type > Change to what you want, which may be a System.Collections.Generic.List.

There is a similar option with svcutil and probably wsdl, but I have not used this yet.

The End.

Using System.Linq.Dynamic in VB.Net

Dynamic Linq

Was trying to using dynamic filter as I would do with datasets. Sometimes you may want to build the query at runtime. Steps are:

  1. Use NuGet to install System.Linq.Dynamic
  2. At top of class Imports System.Linq.Dynamic
  3. Use code as in example below:
Dim queryString1 = "Title = @0"
FilmsList = FilmsList.AsQueryable.Where(queryString1, "Casablanca").ToList

Dim queryString2 = "Title.Contains(@0)"
FilmsList = FilmsList.AsQueryable.Where(queryString2, "a").ToList

Dim queryString3 = "Title = ""Casablanca"""
FilmsList = FilmsList.AsQueryable.Where(queryString3).ToList
FilmDataGrid.ItemsSource = FilmsList

Error 1: Character literal must contain exactly one character

Solution 1: Use double quotes when constructing predicate in code e.g. Dim myFilter = String.Concat( “Title = “””,myTitle,””””)

End.

WPF DataGrid Get Current Row

Data Grid – Get Current Row. E.g. For Jump to Details – Data Grid Button Click

<DataGrid.Columns>
<DataGridTemplateColumn Header="Details" Width="80">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="JumpButtonColumn" Content="{Binding Path=AdviceNoteNo}" Click="JumpButtonColumn_Click"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>>

And the Code

private void JumpButtonColumn_Click(object sender, RoutedEventArgs e)
{
if (invoiceDataGrid.CurrentColumn != null && invoiceDataGrid.CurrentColumn.DisplayIndex == 0)
{
Invoice myInvoice = ((FrameworkElement)sender).DataContext as Invoice;
Jump(myInvoice.InvoiceNo);
}
};

or

Private Sub JumpButtonColumn_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
   If AdviceNoteDataGrid.CurrentColumn IsNot Nothing AndAlso AdviceNoteDataGrid.CurrentColumn.DisplayIndex = 0 Then
       Dim myAdviceNote As AdviceNote = CType((CType(sender, FrameworkElement)).DataContext, AdviceNote)
       Jump(myAdviceNote.AdviceNoteNo)
   End If
End Sub

End

VSTO Visual Studio Tools for Office

Post is a placeholder for my VSTO sample code

Quick VSTO notes:

After adding a ribbon and a button to refer to code in “ThisAddIn.vb” use Globals.ThisAddIn.GetCode

In ThisAddIn.vb to get the work sheet
Dim worksheet As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet

How do I align a range and make other format changes?

        With worksheet.Range("A2:Y2")
            .VerticalAlignment = Excel.XlVAlign.xlVAlignCenter
            .WrapText = True
            .ColumnWidth *= 2
            .RowHeight *= 3
        End With

.

Links

Walkthrough: Complex data binding in an application level project

http://msdn.microsoft.com/en-us/library/cc668212(v=vs.100).aspx

This worked fine:

    Private Sub SetListObjectAndBinding()
        Using ta As New myTableAdapters.myTableAdapter
            ta.Fill(myDS.myTable)
        End Using

        Dim ExtendedWorksheet = Globals.Factory.GetVstoObject(worksheet)
        Dim cell As Excel.Range = ExtendedWorksheet.Range("$A$1:$B$10", System.Type.Missing)
        myListObject = ExtendedWorksheet.Controls.AddListObject(cell, "list1")

        myItemBindingSource = New System.Windows.Forms.BindingSource
        myItemBindingSource.DataSource = myDS.MyTable

        myItemListObject.AutoSetDataBoundColumnHeaders = True
        myItemListObject.SetDataBinding(Me.vehicleItemBindingSource, "", "Field1", "Field2", "Field3")
    End Sub

Then normal Excel editing and a subsequent dataset update method works a treat.
The following post suggested that the ListObject has a ChangedEvent

http://social.msdn.microsoft.com/Forums/vstudio/en-US/252d6c46-a012-4278-a652-8175693c962a/how-do-i-detect-the-cell-data-change-on-the-excel-grid?forum=vsto

How do I working with the ListObject

How do I change Column Headers and other properties in a ListObject?

You cannot change the column header if the following is True

Also the locked will work when the worksheet.Protect and Unprotect, but don’t change any cells when Protect is on.

        VehicleItemListObject.AutoSetDataBoundColumnHeaders = False

        For Each col As Excel.ListColumn In VehicleItemListObject.ListColumns
            myRange = col.DataBodyRange
            If col.Index < FirstWriteColumn Then
                myRange.Locked = True
                myRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Drawing.Color.LightGray)
            Else
                myRange.Locked = False
            End If
            'Select Case col.Name
            '    Case "YearFrom"
            '        col.Name = "Year From"
            'End Select
            If col.Name.StartsWith("Year") AndAlso col.Name <> "Year" Then
                col.Name = col.Name.Replace("Year", "Year ")
            End If
            If col.Name.Length > 14 Then
                myRange = worksheet.Columns(col.Index)
                myRange.ColumnWidth *= 1.5
            End If
        Next

How do I turn off Auto Filter after loading a ListObject?

VehicleItemListObject.ShowAutoFilter = False

Why am I using VSTO?

A problem with taking a de-normalised spreadsheet and normalising it is that the new UI will likely be parent row with multiple children. This means the user will now only be able to edit one set of children at a time without doing further work. To resolve this I am trying a pivot view of the normalised data which may then be exported to Excel, which can then be re-saved back to the data.

End

WPF EntityFramework DataGrid ComboBox

There may be several ways of doing this:

    <UserControl.Resources>
        <CollectionViewSource x:Key="originatorViewSource" d:DesignSource="{d:DesignInstance my:Originator, CreateList=True}" />
        <CollectionViewSource x:Key="customerLookup" />
    </UserControl.Resources>
                    <DataGridComboBoxColumn x:Name="cboCustomer"
                                            Width="200"
                                            Header="Customer"
                                            ItemsSource="{Binding Source={StaticResource customerLookup}}"
                                            SelectedValueBinding="{Binding Path=CustomerID}"
                                            SelectedValuePath="ID"
                                            DisplayMemberPath="Customer1">
                    </DataGridComboBoxColumn>

        private void LoadComboBox()
        {
            try
            {
                SalesContext contextCustomer = new SalesContext();
                var customerList = from c in contextCustomer.Customers
                                   orderby c.Customer1
                                   select new { ID = c.ID, Customer1 = c.Customer1 };

                CollectionViewSource CustomerViewSource = (CollectionViewSource)this.Resources["customerLookup"];
                CustomerViewSource.Source = customerList.ToList();
                //cboCustomer.ItemsSource = customerList.ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 

End

WPF Quick Reminders

Windows Forms Integration

Dim myControl1 = New WpfControlLibrary.CustomControl1
 myControl1.Content = "Hello World"
Me.ElementHost1.Child = myControl1

Docking

You may want HorizontalAlignment or VerticalAlignment = “Stretch”

DataBinding

Imports System.Data.Entity

private AccountTypeContext _context = new AccountTypeContext();
private CollectionViewSource myCollectionViewSource;
//Next in Loaded. If in user control then:
// Do not load your data at design time.
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{ }
 myCollectionViewSource = (CollectionViewSource)this.Resources["accountTypeViewSource"];
_context.AccountTypes.Load();
myCollectionViewSource.Source = _context.AccountTypes.Local;

DataBinding – BindingNavigator Functions

        private void MoveFirstButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToFirst();
        }
        private void MovePreviousButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToPrevious();
        }
        private void MoveNextButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToNext();
        }
        private void MoveLastButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToLast();
        }
//


It may be necessary to use
myDataGrid.ScrollIntoView(myDataGrid.SelectedItem);

 

DataBinding – Filter

With acknowledgment to:

http://www.chateau-logic.com/content/wpf-entity-framework-listbox-datagrid-filtering-using-collectionviewsource-collectionview

and

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.WINDOWS.DATA.COLLECTIONVIEWSOURCE.FILTER);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true

In _Loaded

       myCollectionViewSource.Filter += new FilterEventHandler(FilterTextBoxLike);
In Code - assuming you have a text box called FilterTextBox
        #region Filter
        bool FilterClearing;
        private void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)        {
            try             {
                if (FilterClearing == false)                    {
                        RefreshList();                    }
            }
            catch (Exception ex)            {
                MessageBox.Show(ex.Message);    
            }
        }

        private void RefreshList()
        {
            myCollectionViewSource.View.Refresh();
        }

        private void FilterTextBoxLike(object sender, FilterEventArgs e)
        {
            AccountType at = e.Item as AccountType;

            if (at.AccountType1.ToLower().Contains(FilterTextBox.Text.ToLower()))
            {
                e.Accepted = true;
            }
            else
            {
                e.Accepted = false;
            }
        }

        private void ClearFilterButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
		FilterClearing = true;
               FilterTextBox.Text = "";
		RefreshList();
            }
            catch (Exception ex)
            {
		MessageBox.Show(ex.Message);                
            }
            FilterClearing = false;
        }

        #endregion

.

Data Grid – Styles

 

DatePicker as UK style date

Two actions seem to be required

Imports System.Globalization
Imports System.Threading

Namespace My

Partial Friend Class MyApplication

Private Sub MyApplication_Startup(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
Dim ci = New CultureInfo(Thread.CurrentThread.CurrentCulture.Name)
ci.DateTimeFormat.ShortDatePattern = “dd-MMM-yyyy”
Thread.CurrentThread.CurrentCulture = ci
End Sub

End Class

End Namespace

<DatePicker Name=”DateReportedTextBox” Text=”{Binding Path=DateReported, StringFormat={}{0:dd-MMM-yyyy}}” />


End

Database Unit Test

 

Cool – Easy – Very Useful