• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 387
  • Last Modified:

.Net Writing to File

I am attempting my hand at building a Data Context Code Generator for myself.

Everything does what it is supposed to do, with one small exception.

I am using StringBuilder to piece together the strings for the files to generate, and it seems that no-matter what I try, when I write the StringBuilder.ToString() to a *.vb file and then try to open it in VS 2010 I get the following:

"The line endings in the following file are not consistent..."

I have tried StringBuilder.AppendLine, StringBuilder.Append (with adding the following to the ends of the lines Environment.NewLine, vbNewLine, vbCr, vbLf, vbCrLf, vbCr & vbLf), and still they come up with that message

an example would be:
Dim _Tmp As New StringBuilder
_Tmp.AppendLine("Function HelloWorld() As String")
_Tmp.AppendLine("Return ""Hello World""")
_Tmp.AppendLine("End Function")
Using _SW As New IO.StreamWriter(Common.ContextPath & "\FileName.vb")
     With _SW
        .Write(_Tmp.ToString())
        .Close()
     End With
End Using

Open in new window


or:
Dim _Tmp As New StringBuilder
_Tmp.Append("Function HelloWorld() As String" & vbCrLf)
_Tmp.Append("Return ""Hello World""" & vbCrLf)
_Tmp.Append("End Function" & vbCrLf)
Using _SW As New IO.StreamWriter(Common.ContextPath & "\FileName.vb")
     With _SW
        .Write(_Tmp.ToString())
        .Close()
     End With
End Using

Open in new window

0
kevp75
Asked:
kevp75
  • 6
  • 2
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try adding each line to a List(Of String) instead.  Then use ToArray() on it and pass that to System.IO.File.WriteAllLines().
0
 
nepaluzCommented:
I'd go this way ..
        Dim _Tmp As New List(Of String)
        _Tmp.Add("Function HelloWorld() As String")
        _Tmp.Add("Return ""Hello World""")
        _Tmp.Add("End Function")
        File.WriteAllLines(Common.ContextPath & "\FileName.vb", _Tmp.ToArray)

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Lol....
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
kevp75Author Commented:
well...  that definately helps, however...

i need to be able to do some string replacements on some of the strings to get written

(only reason why I used the stringbuilder in the first place...lol)

Dim _Tmp As New StringBuilder
_Tmp.Append("Function HelloWorld$TRUENAME$() As String" & vbCrLf)
_Tmp.Append("Return ""Hello World""" & vbCrLf)
_Tmp.Append("End Function" & vbCrLf)
Using _SW As New IO.StreamWriter(Common.ContextPath & "\FileName.vb")
     With _SW
        .Write(_Tmp.ToString().Replace("$TRUENAME$", "TheTrueName"))
        .Close()
     End With
End Using

Open in new window

0
 
kevp75Author Commented:
here's the deal...  although I didn;t want to have to show this, here's the real work
 
Imports System.Data.SqlClient

Public Class ContextObjects

    Public Property TableViewIDs As ArrayList
    Public Property ErrorMessage As String

    Public Function Create() As Boolean
        Dim _Ret As Boolean = True
        Try
            Dim _TmpStr As String = String.Empty, _TmpTyping As New Text.StringBuilder, _TmpMethod As New Text.StringBuilder
            Dim _TmpQry As String = String.Empty
            If TableViewIDs IsNot Nothing Then
                For Each item In TableViewIDs
                    Using objConn As New SqlConnection(Common.ConnectionString())
                        Using objCmd As New SqlCommand("Select OBJECT_NAME(c.OBJECT_ID) TableName, c.name AS ColumnName, " & _
                                                       "t.name AS TypeName, (Select name From sys.schemas Where schema_id = (Select uid From sys.sysobjects Where id = c.object_id)) AS SchemaName " & _
                                                        "FROM sys.columns AS c " & _
                                                        "JOIN sys.types AS t ON c.user_type_id=t.user_type_id " & _
                                                        "Where c.OBJECT_ID = (" & item & ") " & _
                                                        "ORDER BY ColumnName", objConn)
                            objCmd.CommandType = CommandType.Text
                            objCmd.CommandTimeout = 0
                            objCmd.Connection.Open()
                            objCmd.Prepare()
                            Using objDT As New DataTable()
                                Using objDA As New SqlDataAdapter
                                    objDA.SelectCommand = objCmd
                                    objDA.Fill(objDT)
                                    If objDT IsNot Nothing And objDT.Rows.Count > 0 Then
                                        Dim _TblName As String = objDT.Rows(0)(0)
                                        Dim _SchemaName As String = objDT(0)(3)
                                        Dim _FullName = _SchemaName & "_" & _TblName
                                        _TmpMethod.Append("Public Function Get" & _FullName & "() As IList(Of " & _FullName & "ContextTyping)" & Environment.NewLine)
                                        _TmpMethod.Append("Try" & Environment.NewLine)
                                        _TmpMethod.Append("    If _SC AndAlso _Cache.GetCacheItem(Of IList)(""" & _FullName & """ & _CID) IsNot Nothing Then" & Environment.NewLine)
                                        _TmpMethod.Append("        Return _Cache.GetCacheItem(Of IList)(""" & _FullName & """ & _CID)" & Environment.NewLine)
                                        _TmpMethod.Append("    Else" & Environment.NewLine)
                                        _TmpMethod.Append("        Using db As New DataAccess" & Environment.NewLine)
                                        _TmpMethod.Append("            With db" & Environment.NewLine)
                                        _TmpMethod.Append("                .QueryType = DataCommon.CommandType.InlineSql" & Environment.NewLine)
                                        _TmpMethod.Append("                .Query = $Query$" & Environment.NewLine)
                                        _TmpMethod.Append("                Using _Results = .GetResults()" & Environment.NewLine)
                                        _TmpMethod.Append("                    If _Results IsNot Nothing Then" & Environment.NewLine)
                                        _TmpMethod.Append("                        _Qry = (From row In _Results.Cast(Of DbDataRecord)()" & Environment.NewLine)
                                        _TmpMethod.Append("                                Select New " & _FullName & "ContextTyping() With {" & Environment.NewLine)
                                        _TmpQry = "SELECT "
                                        For i As Long = 0 To objDT.Rows.Count - 1
                                            _TmpTyping.Append("Public Property " & objDT.Rows(i)(1) & " As " & ConvertDataType(objDT.Rows(i)(2)) & Environment.NewLine)
                                            If Not (i = objDT.Rows.Count - 1) Then
                                                _TmpQry += objDT.Rows(i)(1) & ", "
                                                _TmpMethod.Append("                                    ." & objDT.Rows(i)(1) & " = DataCommon.IsNull(Of " & ConvertDataType(objDT.Rows(i)(2)) & ")(row, " & i & ", " & DataTypeDefaults(objDT.Rows(i)(2)) & ")," & Environment.NewLine)
                                            Else
                                                _TmpQry += objDT.Rows(i)(1)
                                                _TmpMethod.Append("                                    ." & objDT.Rows(i)(1) & " = DataCommon.IsNull(Of " & ConvertDataType(objDT.Rows(i)(2)) & ")(row, " & i & ", " & DataTypeDefaults(objDT.Rows(i)(2)) & ")" & Environment.NewLine)
                                            End If
                                        Next
                                        _TmpQry += " FROM [" & _SchemaName & "].[" & _TblName & "]"
                                        _TmpMethod.Append("                                }).ToList()" & Environment.NewLine)
                                        _TmpMethod.Append("                    Else" & Environment.NewLine)
                                        _TmpMethod.Append("                        _Qry = Nothing" & Environment.NewLine)
                                        _TmpMethod.Append("                    End If" & Environment.NewLine)
                                        _TmpMethod.Append("                End Using" & Environment.NewLine)
                                        _TmpMethod.Append("                If _SC AndAlso _Qry IsNot Nothing Then" & Environment.NewLine)
                                        _TmpMethod.Append("                    _Cache.SetCacheItem(_Qry, """ & _FullName & """ & _CID)" & Environment.NewLine)
                                        _TmpMethod.Append("                End If" & Environment.NewLine)
                                        _TmpMethod.Append("                Return _Qry" & Environment.NewLine)
                                        _TmpMethod.Append("            End With" & Environment.NewLine)
                                        _TmpMethod.Append("        End Using" & Environment.NewLine)
                                        _TmpMethod.Append("    End If" & Environment.NewLine)
                                        _TmpMethod.Append("Catch ex As Exception" & Environment.NewLine)
                                        _TmpMethod.Append(" ' Make sure to put in some error catching stuff here" & Environment.NewLine)
                                        _TmpMethod.Append("End Try" & Environment.NewLine)
                                        _TmpMethod.Append("End Function" & Environment.NewLine).Replace("$Query$", Chr(34) & _TmpQry & Chr(34))
                                        Dim _X1 As XDocument = XDocument.Load(Common.ApplicationPath & "\Templates\Context.xml", LoadOptions.PreserveWhitespace)
                                        If _X1 IsNot Nothing Then
                                            Dim _Qry1 = (From n In _X1...<Class>
                                                         Select n).ToList()
                                            Using _SW As New IO.StreamWriter(Common.ContextPath & "\DataAccessLayer\Context\" & _FullName & "Context.vb")
                                                With _SW
                                                    .Write(_Qry1.Item(0).Value.Replace("$TableName$", _FullName).Replace("$ContextMethods$", _TmpMethod.ToString()).Replace("$ContextTypingProperties$", _TmpTyping.ToString()))
                                                    .Close()
                                                End With
                                            End Using
                                            _TmpMethod.Clear()
                                            _TmpTyping.Clear()
                                            _TmpQry = String.Empty
                                            _TmpStr = String.Empty
                                            _Qry1 = Nothing
                                            _X1 = Nothing
                                        End If
                                        _Ret = True
                                    Else
                                        ErrorMessage = "There were no result."
                                        _Ret = False
                                    End If
                                End Using
                                objCmd.Parameters.Clear()
                                objCmd.Connection.Close()
                                objConn.Close()
                            End Using
                        End Using
                    End Using
                Next
            End If
        Catch sEx As SqlException
            ErrorMessage = sEx.Message
            _Ret = False
        Catch ex As Exception
            ErrorMessage = ex.Message
            _Ret = False
        End Try
        Return _Ret
    End Function

    Private Function ConvertDataType(ByVal _DBType As String) As String
        Select Case _DBType.ToLower()
            Case "bigint"
                Return "Long"
            Case "int"
                Return "Integer"
            Case "tinyint", "smallint"
                Return "Small"
            Case "nvarchar", "varchar", "char", "nchar", "ntext", "text"
                Return "String"
            Case "bit"
                Return "Boolean"
            Case "money", "smallmoney", "numeric", "decimal"
                Return "Decimal"
            Case "xml"
                Return "XElement"
            Case "datetime", "date", "time", "timestamp", "datetime2", "smalldatetime"
                Return "DateTime"
            Case "uniqueidentifier"
                Return "System.Guid"
            Case "float"
                Return "Double"
            Case "real"
                Return "Single"
            Case "varbinary", "binary", "nvarbinary"
                Return "Byte"
            Case Else
                Return "Object"
        End Select
    End Function

    Private Function DataTypeDefaults(ByVal _DBType As String) As String
        Select Case _DBType.ToLower()
            Case "bigint", "int", "tinyint", "smallint"
                Return "0"
            Case "nvarchar", "varchar", "char", "nchar", "ntext", "text"
                Return "String.Empty"
            Case "bit"
                Return "False"
            Case "money", "smallmoney", "numeric", "decimal"
                Return "0.0"
            Case "xml"
                Return "Nothing"
            Case "datetime", "date", "time", "timestamp", "datetime2", "smalldatetime"
                Return "DateTime.Now()"
            Case "uniqueidentifier"
                Return "Nothing"
            Case "float"
                Return "0D"
            Case "real"
                Return "0"
            Case "varbinary", "binary", "nvarbinary"
                Return "Nothing"
            Case Else
                Return "Nothing"
        End Select
    End Function

End Class

Open in new window


and here's context.xml
 
<?xml version="1.0" encoding="utf-8" ?>
<Class>
  <![CDATA[Public Class $TableName$Context
    Implements IDisposable

#Region "Properties"

    Public WriteOnly Property ShouldCache() As Boolean
        Set(ByVal value As Boolean)
            _SC = value
        End Set
    End Property
    Private _SC As Boolean = False

    Public WriteOnly Property CacheID() As String
        Set(ByVal value As String)
            _CID = value
        End Set
    End Property
    Private _CID As String

    Private _Cache As New CustomCache

    Private _Qry

#End Region

  $ContextMethods$

#Region "IDisposable Support"
    Private disposedValue As Boolean ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
            End If
            _Qry = Nothing
        End If
        Me.disposedValue = True
    End Sub

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

Public Class $TableName$ContextTyping

    $ContextTypingProperties$

End Class
]]>
</Class>

Open in new window

0
 
kevp75Author Commented:
ok.   so opening one of the generated .vb files shows me that i am doing the stringbuilding correclty, and the issue is actually stemming from the XML file.

the code in  the .vb file that is generated shows with all the proper line endings, while the XML lines all show on 1 line...
0
 
kevp75Author Commented:
fixed it

had to change this line:
.Write(_Qry1.Item(0).Value.Replace("$TableName$", _FullName).Replace("$ContextMethods$", _TmpMethod.ToString()).Replace("$ContextTypingProperties$", _TmpTyping.ToString()))

to:
.Write(_Qry1.Item(0).Value.Replace(vbLf, Chr(13) & Chr(10)).Replace("$TableName$", _FullName).Replace("$ContextMethods$", _TmpMethod.ToString()).Replace("$ContextTypingProperties$", _TmpTyping.ToString()))
0
 
kevp75Author Commented:
if y'all can help me come up with a better way to do it, then the points go to you
0
 
kevp75Author Commented:
answered for myself
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 6
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now