Solved

.Net Writing to File

Posted on 2011-09-27
9
350 Views
Last Modified: 2012-05-12
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
Comment
Question by:kevp75
  • 6
  • 2
9 Comments
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36713509
Try adding each line to a List(Of String) instead.  Then use ToArray() on it and pass that to System.IO.File.WriteAllLines().
0
 
LVL 17

Expert Comment

by:nepaluz
ID: 36713531
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 36713536
Lol....
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 25

Author Comment

by:kevp75
ID: 36716377
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
 
LVL 25

Author Comment

by:kevp75
ID: 36716406
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
 
LVL 25

Author Comment

by:kevp75
ID: 36716460
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
 
LVL 25

Accepted Solution

by:
kevp75 earned 0 total points
ID: 36716546
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
 
LVL 25

Author Comment

by:kevp75
ID: 36716549
if y'all can help me come up with a better way to do it, then the points go to you
0
 
LVL 25

Author Closing Comment

by:kevp75
ID: 37005107
answered for myself
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.Net WebRequest Code from JSON curl 9 16
RLDC Reporting in Visual studio 11 16
DataTables + iCheck + pagination Issue 2 23
location of a form 2 14
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question