Tuesday, November 23, 2010

LINQ Group By Examples

These are 2 samples of  Group By Examples, one is very simple one but not simplest, second one is little bit intermediate. 

First creating a class to use in the given example

   1: Public Class TestRecord
   2:     Property ID As String
   3:     Property Value As String
   4:     Property RecordDate As Date
   5:  
   6:     Sub New()
   7:  
   8:     End Sub
   9:  
  10:     Sub New(ByVal id As String, ByVal value As String, ByVal recDate As Date)
  11:         Me.ID = id
  12:         Me.Value = value
  13:         Me.RecordDate = recDate
  14:     End Sub
  15: End Class

 

Now, let say use a button and Gridview to present the data on a page.

   1: Protected Sub Button4_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button4.Click
   2:         Dim showSimpleGroup As Boolean = False
   3:  
   4:         Dim lstItems As New List(Of TestRecord)
   5:         lstItems.Add(New TestRecord("1", "100", Now))
   6:         lstItems.Add(New TestRecord("2", "100", Date.MinValue))
   7:         lstItems.Add(New TestRecord("3", "100", #2/2/1980#))
   8:         lstItems.Add(New TestRecord("4", "200", Date.MinValue))
   9:         lstItems.Add(New TestRecord("5", "200", #1/1/2010#))
  10:         lstItems.Add(New TestRecord("6", "300", Now))
  11:  
  12:         If showSimpleGroup Then
  13:             Dim recList = From r In lstItems Group By r.Value Into g = Group Select New With {g, .ID = g.Max(Function(p) p.ID), .Value = g.Max(Function(p) p.Value)}
  14:             Me.gvwTest.DataSource = recList
  15:             Me.gvwTest.DataBind()
  16:         Else
  17:             Dim tempList = From d As TestRecord In lstItems Group By d.Value Into g = Group
  18:                             Select New With {g, .ID = g.Max(Function(d) d.ID), .RecordDate = g.Max(Function(d) IIf(d.RecordDate = Date.MinValue, Now, d.RecordDate))}
  19:  
  20:             If tempList IsNot Nothing AndAlso tempList.Count > 0 Then
  21:                 Dim recList = From r As TestRecord In lstItems Join t In tempList On t.ID Equals r.ID Select r
  22:                 Me.gvwTest.DataSource = recList
  23:                 Me.gvwTest.DataBind()
  24:             End If
  25:         End If
  26:     End Sub

 

The first grouping will display the distinct value excluding Record Date , second one will use the record’s max date to display the record the distinct value.

Friday, November 05, 2010

WCF Service Hosted in Web Farm or Multi-Homed Scenario

If a WCF Service is deployed in a load balanced environment and hosted on multiple Web Servers under IIS, which is accessed on a public domain, WCF WSDL document refers to a the responding machine name which is generally inaccessible on a public domain. So what you should be doing to make it right?

As per Microsoft, this design was initially designed in WCF but later when Microsoft went into Azure or Cloud Computing, this situation became an issue and realized the need to fix this problem. So in order to fix this problem, you need to perform two simple steps

1. Download the following Fix from Microsoft and Install on respective machines

                         http://code.msdn.microsoft.com/KB971842/Release/ProjectReleases.aspx?ReleaseId=3228

2. Add the following sections in behavior section of configuration

   1: <serviceBehaviors>
   2:    <behavior name="<name>">
   3:      <useRequestHeadersForMetadataAddress>
   4:        <defaultPorts>
   5:           <add scheme="http" port="80" />
   6:           <add scheme="https" port="443" />
   7:         </defaultPorts>
   8:       </useRequestHeadersForMetadataAddress>
   9:    </behavior>
  10: </serviceBehaviors>
  11:  
  12:  

For more information, you can checkout the following articles

a. http://support.microsoft.com/kb/980588

b. http://support.microsoft.com/kb/971842

Saturday, October 23, 2010

Using IFRAME in ASP.NET

If you are using an IFRAME in ASP.NET and setting the height and width and not working as per your need. Spent couple of hours trying all possible options and found a very easy solution

1. Remove following line from Page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2. How to Set values Dynamically

<iframe id="Testframe" runat="Server" />

<script language="vb" runat="server">

 
Protected WithEvents frame1 As System.Web.UI.HtmlControls.HtmlGenericControl
  
  Sub Page_Load()
      Dim frame1 As HtmlControl = CType(Me.FindControl("TestFrame"), HtmlControl)
      With frame1
          .Attributes("src") = "TestPage.aspx"
          .Attributes("width") = "100%"
          .Attributes("height") = "100%"
      End With
      
  End Sub
 
</script>

Wednesday, October 20, 2010

Reading/Uploading Image data using base64 string

How will you upload an image from your local drive without using File Upload control or you do not want to click browse button in order to select and upload the image file. Here is an alternate solution. I came across a situation in which I had to upload an Image file from local drive without using server side File Upload control already available in .NET.

 Client Side Code

The following example illustrates a VBScript Client side function using ADODB Stream and MSXML2 DOMDocument Object.

   1: <script language="vbscript" type="text/vbscript">
   2:  
   3:    'fileName can be any file including full path on your local drive
   4:  
   5:     Function PostImageData(ByVal fileName)
   6:        Const fsDoOverwrite     = true  ' Overwrite file with base64 code
   7:        Const fsAsASCII         = false ' Create base64 code file as ASCII file
   8:        Const adTypeBinary      = 1     ' Binary file is encoded
   9:        Dim objXML,objDocElem
  10:        Dim objStream, objFSO
  11:                
  12:        Set objXML = CreateObject("MSXml2.DOMDocument")
  13:        Set objDocElem = objXML.createElement("Base64Data")
  14:  
  15:        On Error Resume Next
  16:        Set objFSO = CreateObject("Scripting.FileSystemObject")
  17:        Set objStream = CreateObject("ADODB.Stream")
  18:        
  19:        If Err.Number = 0 Then
  20:            If objFSO.FileExists(fileName)  Then
  21:                objStream.Type = adTypeBinary
  22:                objStream.Open()
  23:                objStream.LoadFromFile(fileName)
  24:                objDocElem.dataType = "bin.base64"
  25:                objDocElem.nodeTypedValue = objStream.Read()
  26:                frmPageName.txtBase64Data.value = objDocElem.text                                   
  27:                objStream.Close()
  28:                'objFSO.DeleteFile fileName,true 'Delete the Image file if needed
  29:            Else
  30:                MsgBox("Could not find Image file " & fileName)
  31:            End If
  32:          Else
  33:              MsgBox("Your Browser Secuirty Settings currently do not allow image file reading.")
  34:          End If
  35:  
  36:        Set objXML = Nothing
  37:        Set objDocElem = Nothing
  38:        Set objStream = Nothing
  39:        Set objFSO = Nothing
  40:    End function
  41:  
  42:   </script>

 

Note: In order to make this example work you will need to make sure that following options are enabled in IE

  1. Open IE and Go to Tools –> Internet Options –>Security Tab
  2. Select Trusted Sites –> Sites
  3. Type the website you are planning to run this page and click add and then Close.
  4. Now Click on Custom Level button and make the following options are enabled in ActiveX controls and plug-ins

         a. Allow Previously unused ActiveX Controls to run …

         b. Automatic Prompting for ActiveX controls

         c. Binary and script behaviors

         d. Display video and  animation on a webpage that …

         e. Download signed ActiveX controls

         f. Download unsigned ActiveX controls

         g. Initialize and script ActiveX controls not marked as safe …

         h. Only allow approved domains to use ActiveX without …

          i. Run ActiveX controls and plug-ins

          j. Script ActiveX controls marked safe for scripting

 

5. Make sure following options are set to enabled in Miscellaneous section

         a. Access data sources across domains

         b. Allow META REFRESH

         c. Allow scripting of Microsoft web browser control

         d. Allow script-initiated windows without size or position …

6.  After making all the above changes, click on OK then Apply and then OK. Now Close the browser

 

Server Side Code

   1: Private Function ConvertImageFromBase64String() As Image
   2:         Dim NewImageFile As Image = Nothing
   3:         Try
   4:             Dim bytesData As Byte() = System.Convert.FromBase64String(txtBase64Data.Value)
   5:  
   6:             If bytesData.GetUpperBound(0) > 0 Then
   7:                 Using ImageStream As MemoryStream = New MemoryStream(bytesData)
   8:                     NewImageFile = Image.FromStream(ImageStream, True)
   9:                 End Using
  10:                 NewImageFile.Save(SERVER_PATH, System.Drawing.Imaging.ImageFormat.Bmp)
  11:             Else
  12:                 NewImageFile = Nothing
  13:             End If
  14:         Catch ex As Exception
  15:             NewImageFile = Nothing
  16:         End Try
  17:  
  18:         Return NewImageFile
  19:     End Function

 

Now Save or Present the image wherever you want.

Tuesday, October 05, 2010

Ambiguous in the namespace

You can come across ‘ambiguous in the namespace’ error sometime in Visual Studio 2008. Error may look like following

GeneratedCodeAttribute' is ambiguous in the namespace ..  'System.CodeDom.Compiler'.  …   My Project\Resources.Designer

The Real cause is unknown to me, but have faced this challenge and after some research found out and that somehow the some reference path have changed and pointing to GAC. e.g. they were pointing now such as

C:\Windows\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll

Solution: Go in the Project Properties and see if any of the references are pointing to GAC folder, remove each of them one by one and add it again by making sure that the new reference is now pointing to C:\Windows\Microsoft.NET\Framework path.

Saturday, September 18, 2010

HREF in XSLT

You may come across a situation where you might have to embed a static or Dynamic URL with a query string, it becomes tricky, but here is the simple solution

Static URL with Dynamic Querystring

<xsl:if test="(string-length(/Response/ID) > 0)"> 
    <a target="_new"><xsl:attribute name="href">https://www.domain.com/ShowItem.aspx?ID=<xsl:value-of select="/Response/ID"/></xsl:attribute>Show Item</a> 
</xsl:if>

Dynamic URL

<a><xsl:attribute name=”href”><xsl:value-of select=”@url”/></xsl:attribute>Click On the Link</a>

Happy Coding

Saturday, August 28, 2010

Visual Studio Team Foundation Server

FOR VS 2012

First Check the existing workspaces for some "computername" can be queried with this TFS command:

tf.exe workspaces /computer:computername /owner:* /format:detailed /server:serveraddress

You get a list of all workspaces, with the existing mappings. It is the workspace name (behind "Workspace:") and the owner that you need in order to delete the workspace.

Now run this TFS command to remove the workspace "workspacename" for owner "owner":

tf.exe workspace /delete workspacename;owner /server:serveraddress

 

 

FOR VS 2010

Recently came across some issues while upgrading from Visual Source Safe (VSS) 2005 to Visual Studio Team Foundation Server (VSTFS) 2010. Found some workarounds and limitations. I am assuming you are using Visual Studio 2010

On TFS Server Machine

1. If your projects are using .NET framework 3.5 or higher, make sure the respective .NET Framework is installed on the Server

2. Make sure that output folder where TFS will build the projects have write permission

3. If you are using Enterprise Library or any third party tool, they are also installed on the Server.

4.  You may get an error during Build of the project about “Microsoft.WebApplication.targets“, to resolve this issue C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets from local (development) machine which had VS 2010 already installed.

5. If you have some components or dlls for which you do not any installer or they can not be installed in GAC but they are referred in your projects, One way to fix this issue is to copy that dll in to into C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0

Some informative links

http://msdn.microsoft.com/en-us/library/bb668981.aspx

http://www.attrice.info/cm/tfs/

http://blogs.microsoft.co.il/blogs/eranruso/archive/2010/01/25/how-to-configure-build-services-to-a-specific-tfs-2010-collection.aspx

 

On Development Machine

How to Find your workspaces?

Go to Visual Studio Command Prompt, and use one of the following commands

C:\tf works

In order to delete any of the workspace, you can use following command

C:\>tf workspace /delete /server:BUILDSERVER WORKSPACENAME;OWNERNAMEpaces /owner:*

Important: Make sure that the TFS still has the same collectionname and path. If you or administrator deleted a collection directly from TFS you will not be able to delete or clear your old workspace. Microsoft should have provided a way to address this problem.

How to Delete a Collection?

1. Go to Command Prompt

2. Go to C:\Program Files\Microsoft Team Foundation Server 2010\Tools

3. Type C:\TFSConfig Collection /delete /collectionName:[COLLECTION NAME]"

Note: Delete does not delete from TFS, but just marks the item as deleted, in order to fully delete it, you will have to destroy it

 

How to Destroy?

1. Go to Command Prompt the

2. Go to C:\Program Files\Microsoft Team Foundation Server 2010\Tools

3. tf destroy $/<PATH_OF_THE_FOLDER_OR_OBJECT> /collection:[COLLECTION_NAME_WITH_HTTP_ADDRESS]

For more info visit following link

http://msdn.microsoft.com/en-us/library/bb386005.aspx

 

Friday, April 30, 2010

Error: A potentially dangerous Request.Form value

Just came across this error when I upgraded my Blog from .NET 3.5 to .NET 4.0  - A potentially dangerous Request.Form value was detected from the client .....

Ok, so first I thought may be I missed the Page directives. Checked that and it was there, played around with different settings and configurations, but nothing helped.

But finally the solution was revealed:) and it was very simple as you can see below. In .NET 4.0, Microsoft added another parameter “requestValidationMode” in httpruntime which will stop this error. So open your web.config and add following.

 

Code Snippet
  1. <system.web>
  2.  
  3.      <httpRuntimerequestValidationMode="2.0"/>
  4.  
  5. </system.web>

 

 

Remember if your website is still using .NET 2.0 and getting the same error, make sure that the page directive “ValidateRequest” is set to false.

Code Snippet
  1. <%@ Page Language="C#" MasterPageFile="masterPage.master" AutoEventWireup="true" CodeFile="TestPage.aspx.cs" Inherits="TestPage" ValidateRequest="False" %>

Wednesday, February 17, 2010

Convert Number or Money in Words

Many times we come across the situation of converting a number spelled into words or a monetary value spelled into dollars & cents (or equivalent currency).  I found the following code over internet and changed to fit my need (as we all do) and generalized in such a way that it can be used for either just convert a number to words or monetary value to words. You can add different country code if needed.

 

 1: Public Overloads Shared Function ConvertNumberInWords(ByVal value As String) As String
 2:     Return ConvertNumberInWords(value, "")
 3: End Function
 4:  
 5: Public Overloads Shared Function ConvertNumberInWords(ByVal value As String, ByVal countryCode As String) As String
 6:     Dim majorCurrency As String = String.Empty
 7:     Dim minorCurrency As String = String.Empty
 8:  
 9:     Select Case countryCode.ToUpper()
 10:         Case "GBR"
 11:             majorCurrency = "Pound"
 12:             minorCurrency = "Pence"
 13:         Case "USA", "CAN"
 14:             majorCurrency = "Dollar"
 15:             minorCurrency = "Cent"
 16:     End Select
 17:  
 18:     value = value.Replace(",", "").Replace("$", "")
 19:     value = value.TrimStart(CChar("0"))
 20:  
 21:     Dim decimalCount As Int32 = 0
 22:     For x As Int32 = 0 To value.Length - 1
 23:         If value(x).ToString = "." Then
 24:             decimalCount += 1
 25:             If decimalCount > 1 Then Throw New ArgumentException("Only monetary values are accepted")
 26:         End If
 27:  
 28:         If Not (Char.IsDigit(value(x)) Or value(x).ToString = ".") And Not (x = 0 And value(x).ToString = "-") Then
 29:             Throw New ArgumentException("Only monetary values are accepted")
 30:         End If
 31:     Next
 32:  
 33:     Dim returnValue As String = ""
 34:     Dim parts() As String = value.Split(CChar("."))
 35:  
 36:     If parts.Length > 1 Then
 37:         parts(1) = parts(1).Substring(0, 2).ToCharArray 'Truncates -- doesn't round.   
 38:     End If
 39:  
 40:     Dim IsNegative As Boolean = parts(0).Contains("-")
 41:     If parts(0).Replace("-", "").Length > 18 Then
 42:         Throw New ArgumentException("Maximum value is $999,999,999,999,999,999.99")
 43:     End If
 44:  
 45:     If IsNegative Then
 46:         parts(0) = parts(0).Replace("-", "")
 47:         returnValue &= "Minus "
 48:     End If
 49:  
 50:     If parts(0).Length > 15 Then
 51:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(0, 3)) & "Quadrillion "
 52:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(3, 3)) & "Trillion "
 53:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(6, 3)) & "Billion "
 54:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(9, 3)) & "Million "
 55:         returnValue &= HundredsText(parts(0).PadLeft(18, CChar("0")).Substring(12, 3)) & "Thousand "
 56:     ElseIf parts(0).Length > 12 Then
 57:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(0, 3)) & "Trillion "
 58:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(3, 3)) & "Billion "
 59:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(6, 3)) & "Million "
 60:         returnValue &= HundredsText(parts(0).PadLeft(15, CChar("0")).Substring(9, 3)) & "Thousand "
 61:     ElseIf parts(0).Length > 9 Then
 62:         returnValue &= HundredsText(parts(0).PadLeft(12, CChar("0")).Substring(0, 3)) & "Billion "
 63:         returnValue &= HundredsText(parts(0).PadLeft(12, CChar("0")).Substring(3, 3)) & "Million "
 64:         returnValue &= HundredsText(parts(0).PadLeft(12, CChar("0")).Substring(6, 3)) & "Thousand "
 65:     ElseIf parts(0).Length > 6 Then
 66:         returnValue &= HundredsText(parts(0).PadLeft(9, CChar("0")).Substring(0, 3)) & "Million "
 67:         returnValue &= HundredsText(parts(0).PadLeft(9, CChar("0")).Substring(3, 3)) & "Thousand "
 68:     ElseIf parts(0).Length > 3 Then
 69:         returnValue &= HundredsText(parts(0).PadLeft(6, CChar("0")).Substring(0, 3)) & "Thousand "
 70:     End If
 71:  
 72:     Dim hundreds As String = parts(0).PadLeft(3, CChar("0"))
 73:     hundreds = hundreds.Substring(hundreds.Length - 3, 3)
 74:  
 75:     If CInt(hundreds) <> 0 Then
 76:         If CInt(hundreds) < 100 AndAlso parts.Length > 1 Then returnValue &= " "
 77:         returnValue &= HundredsText(hundreds) & majorCurrency
 78:         If CInt(hundreds) <> 1 Then returnValue &= IIf(majorCurrency.Length > 0, majorCurrency & "s", "").ToString()
 79:         If parts.Length > 1 AndAlso CInt(parts(1)) <> 0 Then returnValue &= " and "
 80:     Else
 81:         returnValue &= IIf(majorCurrency.Length > 0, " No " & majorCurrency & "s", "").ToString()
 82:         If parts.Length > 1 AndAlso CInt(parts(1)) <> 0 Then returnValue &= " and "
 83:     End If
 84:  
 85:     If parts.Length = 2 Then
 86:         If CInt(parts(1)) <> 0 Then
 87:             returnValue &= HundredsText(parts(1).PadLeft(3, CChar("0")))
 88:             returnValue &= minorCurrency
 89:             If CInt(parts(1)) <> 1 Then returnValue &= IIf(minorCurrency.Length > 0, "s", "").ToString()
 90:         End If
 91:     End If
 92:  
 93:     Return returnValue
 94:  
 95: End Function
 96:  
 97: Private Shared Function HundredsText(ByVal value As String) As String
 98:     Dim Tens As String() = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
 99:     Dim Ones As String() = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
 100:  
 101:     Dim returnValue As String = ""
 102:     Dim IsSingleDigit As Boolean = True
 103:  
 104:     If CInt(value(0).ToString) <> 0 Then
 105:         returnValue &= Ones(CInt(value(0).ToString) - 1) & " Hundred "
 106:         IsSingleDigit = False
 107:     End If
 108:  
 109:     If CInt(value(1).ToString) > 1 Then
 110:         returnValue &= Tens(CInt(value(1).ToString) - 1) & " "
 111:         If CInt(value(2).ToString) <> 0 Then
 112:             returnValue &= Ones(CInt(value(2).ToString) - 1) & " "
 113:         End If
 114:     ElseIf CInt(value(1).ToString) = 1 Then
 115:         returnValue &= Ones(CInt(value(1).ToString & value(2).ToString) - 1) & " "
 116:     Else
 117:         If CInt(value(2).ToString) <> 0 Then
 118:             If Not IsSingleDigit Then
 119:                 returnValue &= "and "
 120:             End If
 121:             returnValue &= Ones(CInt(value(2).ToString) - 1) & " "
 122:         End If
 123:     End If
 124:  
 125:     Return returnValue
 126:  
 127: End Function