ASP.Net Forms Authorization

Use

C:\%windir%\Microsoft.NET\Framework\<versionNumber>\aspnet_regsql.exe

to add authorisation schema to an existing database

This will not work with SQL Azure. See

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

which links to

http://archive.msdn.microsoft.com/KB2006191

ASP.Net MVC VB.Net Troubleshooting

Trouble

The connection name ‘ApplicationServices’ was not found in the applications configuration or the connection string is empty

Solution

Go to Project level web.config. Find <membership> change connectionStringName=”ApplicationServices” to “LocalSqlServer”

 

How do I … ASP.Net MVC with VB.Net

How do I … submit text from an input box.

    <form action="" method="post">
   Code starts with: <input type="text" name="MinCode" id="CodeInput" />
    <input type="submit" value="Click Me" /> 
    </form>

and

    <form id="search" action="http://www.google.co.uk/search" method="GET"> 
    <input type="text" name="q" /> 
    <input type="submit" value="Submit" /> 
    </form>

How do I … Register Routes

 routes.MapRoute("Products", "Products/{myCode}", _
              New With {.controller = "Products", .action = "Search"})

How do I … use this route in a controller

        Function Search(name As String) As ActionResult

            Dim myName = RouteData.Values("name")
            Dim myNameFromSignature = name
            Dim result = String.Concat(myName, vbCrLf, name)
            'Return RedirectToAction("Index")
            Dim model As New List(Of ProductsModel)
            InitialiseProductList(model)
            model = model.Where(Function(f) f.Code.ToLower.StartsWith(name)).ToList
            If model.Count = 0 Then
                Return Content(Server.HtmlEncode("No results"))
            End If

            'ViewBag.Name = name
            Return View(model)

        End Function

How do I now call this ASP.Net MVC Search Box

<% Html.BeginForm("Search", "Products")%> 
   <input type="text" name="myCode" /> 
   <input type="submit" name="Submit" /> 
<% Html.EndForm() %>

Confirmed that this works. SRS 18/06/2012. Then did not work 19/06/2012. However following did work.

this example also includes “How do I use @ in ASP.Net MVC including Using.

@Using (Html.BeginForm(“Search”, “Reg90″, FormMethod.Post))
@:<input type=”text” name=”myCode” />
@:<input type=”submit” value=”Click Me 2″ />
End Using

WPF freezes when dragging data source onto a Page or Window

Problem

WPF freezes when dragging data source onto a Page or Window

Possible Solution

Inspect datasource and see if it has a child table underneath it. Does this child expand to show the parent table again. If so then you may be creating an infinite loop when dragging the datasource onto the Page or Window

How do I … create a Custom DataGridViewColumn and DataGridViewCell

Uses may include:

  • Storing extra data in a cell
  • Controlling SortMode for all columns
Public Class DataGridViewPlanColumn
    Inherits DataGridViewTextBoxColumn

    Sub New()
        Me.CellTemplate = New DataGridViewPlanCell
        Me.SortMode = DataGridViewColumnSortMode.NotSortable
    End Sub

End Class

Public Class DataGridViewPlanCell
    Inherits DataGridViewTextBoxCell

    Property WO As Nullable(Of Integer)
End Class

How do I … use Reflection to build a project that will inspect/analyse other assemblies

For instance:

  • My preference is that TableAdapters are not in the component tray of forms, but ideally in a DAL, or if not that good then in a using part of the forms code. I have always struggled to find these. I want a Reflection utility that will find these

Key reflection code snippets to do this are:

How do I … use reflection to load an Assembly at runtime

Dim asm = System.Reflection.Assembly.LoadFrom(AssemblyFileName)

or

Dim asm = System.Reflection.Assembly.GetExecutingAssembly

How do I … loop around forms of a Loaded assembly

ForEach t1 In asm.GetTypes.Where(Function(f) f.IsPublic).Where(Function(f) f.BaseType.Name = “Form”)

Me.ListBox1.Items.Add(String.Concat(t1.Name))

Next

How do I … loop around forms and GetFields

For Each f1 In asm.GetTypes.Where(Function(f) f.IsPublic).Where(Function(f) f.BaseType.Name = “Form”)

For Each prop In f1.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic).Where(Function(f) f.Name.ToLower.Contains(FieldName))

Me.ListBox1.Items.Add(String.Concat(f1.Name, “: “, prop.Name, “: “, prop.FieldType.Name))

Next

Next

 

How do I … move projects to a different collection in VS-TFS

After a few years I got to a point of over 40 projects in one solution. Solution explorer required a vertical scroll bar even before expanding any projects.
Some projects are clearly not relevant to the solution or are abstract. I was keeping them in the solution because I wanted to promote abstraction, so wanted to regularly change these projects. Because they are abstract there is an argument to separate them out and potentially use them elsewhere.

I have taken the plunge. And this article is to record how I have done it.

There are other views and procedures on web.
Also in Microsoft Connect there is a request for this feature to be added.

I found the following to work and seemed easier than the other procedures:

  1. Make sure project is loaded in current solution
  2. VS IDE File > Source Control > Change Source Control
  3. Select project to move > Unbind > OK ( this may be reversed by binding again )
  4. In Solution Explorer remove the project
  5. Save all
  6. In Windows Explorer copy the project to the location of the destination collection
  7. Close Visual Studio if ncessary saving the changes to the solution
  8. Open the destination collection
  9. Add the project.
    • If you miss out step 3 then it will not show as to add to source control
    • If you include step 2 then it will show to add to source control
  10. Check-in optionally with a work item
  11. You could potentially keep the project in the original solution and use > File > Source Control > Add project from Source Control
  12. Or more common delete by:
    • > Source Control Explorer > Selecting the folder > Right-click Delete > Check-in
    • This will not delete it from the local folder > so this may be deleted manaully > you may need to close the current solution

How do I .. use Reflection to get the values of an Enum at runtime

Thanks to:
http://www.vb-helper.com/howto_net_list_enum.html

Module Module1

Sub Main()

ForEach field As System.Reflection.FieldInfoInGetType(TestEnum).GetFields.Where(Function(f) f.IsLiteral)
  ‘Console.WriteLine(field.Name + vbTab + CInt(field.GetValue(Nothing)).ToString)
  Console.WriteLine(CInt(field.GetValue(Nothing)).ToString + ” “ + field.Name)
Next
Console.ReadLine()

End Sub

End Module

Public Enum TestEnum
  Cheese = 1
Wallace
Grommit
Wheelbarrows
End Enum

How do I … identify dataset constraint type that has failed when I get exception: System.Data.ConstraintException: Failed to enable constraints. One or more …

How do I … identify dataset constraint type that has failed when I get exception:

This is a nice trick

System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

Write a test that Fills the requried table. I use a helper class for datasets, but you could change this to put the tableadapter in here.
Then loop through the columns and remove the constraints
Also remove the primary key constraint
Prove that the Fill now works. Then stop turning the constraints off one-by-one until you find the type of constraint.


&lt;TestMethod()&gt; _

Public Sub FillTest()

Dim dsValue As New &lt;datasetname&gt;
Dim target As New &lt;dataset&gt;Helper(dsValue)
For Each col As DataColumn In dsValue.&lt;tablename&gt;.Columns
If col.Ordinal &lt; 10 Then   'Use to reduce possible columns down
col.MaxLength = -1       'Rem in or out to reduce possible constraints. And next line
col.AllowDBNull = True
End If
Next

dsValue.&lt;tablename&gt;.PrimaryKey = Nothing
Dim aList = dsValue.&lt;tablename&gt;.Constraints

Stop
target.Fill

End Sub

 

Optional helper methods

    Private Sub SetAllowDBNULLTrue(dt As DataTable, Optional MinOrdinal As Integer = 0, Optional MaxOrdinal As Nullable(Of Integer) = Nothing)

        If Not MaxOrdinal.HasValue Then MaxOrdinal = dt.Columns.Count

        For Each col As DataColumn In dt.Columns
            If col.Ordinal > MinOrdinal AndAlso col.Ordinal < MaxOrdinal Then   'Use to reduce possible columns down
                If col.AllowDBNull = False Then
                    Debug.Print("Changing column to allow null " + col.ColumnName)
                    col.AllowDBNull = True
                End If
            End If
        Next

    End Sub

    Private Sub SetMaxLengthToMinus1(dt As DataTable, Optional MinOrdinal As Integer = 0, Optional MaxOrdinal As Nullable(Of Integer) = Nothing)

        If Not MaxOrdinal.HasValue Then MaxOrdinal = dt.Columns.Count

        For Each col As DataColumn In dt.Columns
            If col.Ordinal > MinOrdinal AndAlso col.Ordinal < MaxOrdinal Then   'Use to reduce possible columns down
                If col.MaxLength <> -1 Then
                    Debug.Print("Changing column MaxLength to -1 for " + col.ColumnName)
                    col.MaxLength = -1       'Rem in or out to reduce possible constraints. And next line
                End If
            End If
        Next

    End Sub

 

LocalReport set-up and publish

How do I … keep reports in a sub-directory

May be set in code or in ReportViewer control

Dim report as New LocalReport()
report.ReportPath = “Reports\ReportName.rdlc”

How do I … fix Local reports that work in Visual Studio not when published

The errors you may get include:

  • An error occurred during local report processing copy
    The report definition for report ‘..\some_path_to_report\<reportname>.rdlc’ has not been specified
    Could not find file ‘C:\inetpub\wwwroot\some_path_to_report\tse.rdlc’.

When reports are added their default Build Action is Embedded Resource.
To fix this change to Content and choose a copy policy, probably Copy if Newer

How do I … use a report in a referenced project

Add the report as a “Linked” file ( Add existing item > Add as Link )(probably) at the same directory level as in the referenced project
Then on these linked files choose the necesary options as above