Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Sunday, May 22, 2011

Request.ServerVariables, Another LINQ way

I recently came across this blog, by using an extension method with sample codes on how to retrieve the value from Request.ServerVariables using LINQ.

Here is my modification of the method, which is much more shorter, using LINQ to to retrieve the server variables:

Dim d As IEnumerable(Of System.Collections.Generic.KeyValuePair(Of String, String)) = _
From c In System.Web.HttpContext.Current.Request.ServerVariables _
Let s = System.Web.HttpContext.Current.Request.ServerVariables(c) _
Select New System.Collections.Generic.KeyValuePair(Of String, String)(c, s)

After that, bind it to GridView:

GridView1.DataSource = d
GridView1.Bind()

This will give you all the values from Request.ServerVariables.

Request.ServerVariables, Another LINQ way | My Code Snippet

Thursday, September 30, 2010

Getlines Count In A File - How To Do It In VB.Net And Linq

The follow combination of VB.Net and LINQ sample code, to count the number of rows in an input file, by using IO.File.ReadLines, which return Type System.Collection.Generic.IEnumerable(Of String), in .Net Framework 4.


To get the number of lines of a file.
Private Function GetLinesCount(ByVal FileName As String) As Integer 
    If Not File.Exists(FileName) Then 
        Return 0
        Exit Function
    End If
 

    Dim lines = (From l In IO.File.ReadLines(FileName) _
                           
Select l)
                           

    Dim d As Integer = lines.Count

    lines =Nothing
    Return
d
End Function

To skip blank line from count
Private Function GetLinesCount(ByVal FileName As String) As Integer 
    If Not File.Exists(FileName) Then 
        Return 0
        Exit Function
    End If
 

    Dim lines = (From l In IO.File.ReadLines(FileName) Where Not l.Trim.Length = 0 _
                           
Select l)
                           

    Dim d As Integer = lines.Count

    lines =Nothing
    Return
d
End Function
Permanent link

Wednesday, September 1, 2010

VB.NET - How To Extend A Custom Method to Error Provider For Field Validation


The concept is very simple, instead of coding the Error Provider Control to validate field one by one; we add custom functionality to Error Provider that can be call without creating a new derived type.

For example
From:
If String.IsNullOrEmpty(Textbox1.Text.Trim) Then
            ErrorProvider1.SetError(Textbox1, “The field cannot be empty!”)
Else
            ErrorProvider1.SetError(Textbox1,Nothing)
End If

If String.IsNullOrEmpty(Textbox2.Text.Trim) Then
            ErrorProvider1.SetError(Textbox2, “The field cannot be empty!”)
Else
            ErrorProvider1.SetError(Textbox2,Nothing)
End If

To:
ErrorProvider1.Validate(TextBox1, “This field cannot be empty!”)
ErrorProvider1.Validate(TextBox2, “This field cannot be blank!”)
If ErrorPrivider1.HasError Then
            MessageBox.Show(ErrorProvider.GetErrorMessages())
‘ Error routine here
End If


Step one: Create a new module
Imports System.Runtime.CompilerServices
Imports System.Text

Namespace ErrorProviderExtension
            Module ErrorExtension
                       
            <Extension()> _
            Public Function Validate( ByVal Epd As ErrorProvider, _
                  ByVal Control As Control, _
                  Optional ByVal ErrorMessage As String = “Field cannot be empty!”)  As Boolean
                          If String.IsNullOrEmpty(Control.Text.Trim) Then
                                      Epd.SetError(Control, ErrorMessage)
                                      Return False
                                      Exit Function
                          End If
                                   
                          Epd.SetError(Control, Nothing)
                          Return True
             End Function

            <Extension()> _
            Public Function HasErrors(ByVal Epd As ErrorProvider) As Boolean
                        Dim err e Nullable(Of Integer) = (From e In Epd.ContainerControl.Controls _
                                                                                 Let msg = Provider.GetError(e) _
                                                                                 Where msg.Length > 0 _
                                                                                 Select e).Count
                        If err.GetValueOrDefault(0) > 0 Then
                                    Return True
                        Else
                                    Return False
                        End If
            End Function

            <Extension()> _
            Public Function GetErrorMessages(ByVal Epd As ErrorProvider) As String
                        Dim sb As New StringBuilder
                                  
                        If Epd.ContainerControl Is Nothing Then
                                    Return Nothing
                                    Exit Function
                        End If

                        Dim err = From e In Epd.ContainerControl.Controls _
                                          Let message = Epd.GetError(e) _
                                          Where message.Length > 0 _
                                          Select message

                        If Not IsNothing(err) Then
                                  Dim i As Integer = 1
                                  For Each emsg As String In err
                                            sb.AppendLine(String.Format(“{0}: {1}”, i, emsg.ToString))
                                             i += 1
                                  Next
                                  sb.AppendLine(“Please clear all the errors before continue!”)
                                  Return sb.ToString
                                  Exit Function
                       End If
                                   
                       Return Nothing
            End Function

            End Module
End Namespace

Next, create a new Windows®Form; drag an ErrorProvider, two TextBox and one Button onto it, then
Imports rootnamespace.ErrorProviderExtension

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
             ErrorProvider1.Validate(TextBox1, “TextBox1 cannot be blank!”)
             ErrorProvider1.Validate(TextBox2, “TextBox2 cannot be blank!”)

             If ErrorProvider1.HasError Then
                 MessageBox.Show(ErrorProvider1.GetErrorMessages)
                 Exit Sub
             End If

            ‘Continue here if not error
            End Sub

Note: Please refer to MSDN for supported version and methods.