Copyright text in asp.net view pages - asp.net

Folks,
Looking for help from the community.
I have to add copyright text in all aspx/ascx/master pages on the top.
The sample copyright text is as follows -
<!-- © 2014 xyz company .. .. . .. ........ ........
.............................
-->
This copyright text needs to be added as comment on the file.
When I try to add this copyright text using powershell/macro, my page encoding gets changed to ANSI. Which intern will trouble or say troubles while merging/checking-in the file. The issue is '©' character.
Option Strict Off
Option Explicit Off
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Public Module RecordingModule
Sub IterateFiles()
Dim solution As Solution =
DTE.Solution
For Each prj As Project In solution.Projects
IterateProjectFiles(prj.ProjectItems)
Next
End Sub
Private Sub IterateProjectFiles(ByVal prjItms As ProjectItems)
For Each file As ProjectItem In prjItms
If file.SubProject IsNot Nothing Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
ElseIf file.ProjectItems IsNot Nothing AndAlso file.ProjectItems.Count > 0 Then
AddHeaderToItem(file)
IterateProjectFiles(file.ProjectItems)
Else
AddHeaderToItem(file)
End If
Next
End Sub
Private Sub AddHeaderToItem(ByVal file As ProjectItem)
DTE.ExecuteCommand("view.SolutionExplorer")
If file.Name.EndsWith(".aspx") OrElse file.Name.EndsWith(".ascx") OrElse file.Name.EndsWith(".Master") Then
file.Open()
file.Document.Activate()
AddHeader()
file.Document.Save()
file.Document.Close()
End If
End Sub
Private Sub AddHeader()
Dim cmtHeader As String = "<!-- "
Dim cmtCopyright As String = "Copyright © 2014 xyz company"
Dim cmtFooter As String = " -->"
Dim cmt = "//"
DTE.UndoContext.Open("Header Comment")
Dim ts As TextSelection = CType(DTE.ActiveDocument.Selection, TextSelection)
ts.StartOfDocument()
ts.Text = String.Format(cmtHeader, cmt)
ts.NewLine()
ts.Text = String.Format(cmtCopyright)
ts.NewLine()
ts.Text = String.Format(cmtFooter)
ts.NewLine()
DTE.UndoContext.Close()
End Sub
End Module
Above please file macro code above.
Adding to this, these files have different character encoding - utf-8 and utf-8 with BOM. So I should be able to retain the encoding too.
Please let me know you need more information.

Looks like issue is ©. So I will have to replace this with (c). This is tested OK.

Related

Count all files in folder and subfolder with VB6

In VB6, I am using a Webbrowser form to display all files and subfolders as icons in the style of Windows Explorer. On the form, I display a count of all files in the main folder and all subfolders. This is my code so far, though haven't been able to find any information about counting subfolders.
Private Sub Load_Form()
Dim myPathName as String
Dim iTotalCount as Long
some stuff here ....
WebBrowser1.Navigate myPathName
WebBrowser1.Document.CurrentViewMode = 5 'medium icons
iTotalCount = FileCount(myPathName)
lblLabel.Caption = "Total Files = " & iTotalCount
more stuff here ....
End Sub
Public Function FileCount(myPathName as String) as Long
Dim FSO as New FileSystemObject
Dim fld as Folder
If FSO.FolderExists(myPathName) Then
Set fld = FSO.GetFolder(myPathName)
FileCount = fld.Files.Count
End If
End Function
This StackOverFlow question is similar, though for vb.net (which I don't know). I'd appreciate someone pointing me in the right direction. Many thanks.

Overload File Function VB.NET

I am trying to create an onclick function through ASP front end to check if a file exists, if not create it and write textbox text to it, currently getting an error on the below code saying that I cannot overload the file function, is there a better way of doing this?
UPDATE
The issue is the file is still open when trying to write to it which is throwing the error.
Please see below code:
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:Documents\Visual Studio 2013\Projects\SomeProject\Templates\" & FileName.Text & ".txt"
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
File.Create(txtFile)
File.WriteAllText(eTemplate.Text)
End If
End Sub
I have also tried:
If File.Exists(txtFile) Then
Response.Write("A file of that name already exists.")
Else
System.IO.File.Create(txtFile)
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
You're right on the money, it is because it needs to be closed first.
I created a file stream instance first, created the file, closed it and then wrote to it. Put the below code in yours or write it out, but remember to correct the file path.
Protected Sub Create_Click(sender As Object, e As EventArgs)
Dim txtFile As String = "E:\wherever\" & FileName.Text & ".txt"
If System.IO.File.Exists(txtFile) Then
Dim message As String = "A file by this name already exists, choose another or update the existing file."
Else
Dim fs As FileStream = File.Create(txtFile)
fs.Close()
Dim sw As New StreamWriter(txtFile, True)
sw.Write(eTemplate.Text)
sw.Close()
End If
End Sub

Auto generated code flagging errors in VB.Net?

I have a VB.Net project in visual studio 2010 intended to let a user upload a video and then stick it in a DB. The file is called "Media/Test.aspx.vb".
When I tried to run the code to debug, tons of errors were generated for a file called App_Web_nkhy2w0y.0.vb
I couldn't locate this file anywhere, and I certainly didn't write it, so I double clicked on the error and it opened a file with about 350 lines of (apparently) auto-generated code, and I have no clue what I did to cause it to do this. Nor do I have any idea how to fix it.
I'll admit I'm new to VB.Net, but I've never seen anything like this online so I'm in the dark.
My original code is below for the code-behind file that handles nothing more than a fileupload control, button, and label in the actual page.
Imports System.IO
Imports System.Data.SqlClient
Imports System.Data
Partial Class Media_Test
Inherits System.Web.UI.UserControl
Protected Sub TryMe_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TryMe.Click
Dim connection As SqlConnection
'check the file
Dim buffer As Byte()
If testFile.HasFile AndAlso testFile.PostedFile IsNot Nothing AndAlso testFile.PostedFile.FileName <> "" Then
Dim file As HttpPostedFile = testFile.PostedFile
'retrieve the HttpPostedFile object
buffer = New Byte(file.ContentLength - 1) {}
Dim bytesReaded As Integer = file.InputStream.Read(buffer, 0, testFile.PostedFile.ContentLength)
'the HttpPostedFile has InputStream porperty (using System.IO;)
'which can read the stream to the buffer object,
'the first parameter is the array of bytes to store in,
'the second parameter is the zero index (of specific byte)
'where to start storing in the buffer,
'the third parameter is the number of bytes
'you want to read (do u care about this?)
If bytesReaded > 0 Then
Try
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connection = New SqlConnection(connectionString)
Dim cmd As New SqlCommand("INSERT INTO Videos (Video, Video_Name, Video_Size)" & " VALUES (#video, #videoName, #videoSize)", connection)
cmd.Parameters.Add("#video", SqlDbType.VarBinary, buffer.Length).Value = buffer
cmd.Parameters.Add("#videoName", SqlDbType.VarChar).Value = testFile.FileName
cmd.Parameters.Add("#videoSize", SqlDbType.BigInt).Value = file.ContentLength
Using connection
connection.Open()
Dim i As Integer = cmd.ExecuteNonQuery()
Label1.Text = "uploaded, " & i.ToString() & " rows affected"
End Using
Catch ex As Exception
Label1.Text = ex.Message.ToString()
End Try
End If
Else
Label1.Text = "Choose a valid video file"
End If
End Sub
End Class
And the top of the generated page is:
#ExternalChecksum("C:\Users\handcm\Documents\Visual Studio 2010\WebSites\APPS\Media\Test.aspx","{406ea660-64cf-4c82-b6f0-42d48172a799}","F31F20662F14B4894B6FBF58215628CB")
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.296
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
I can post the entire file if need be, but could someone shine some light on what's going on here? I have no clue how to debug a file I didn't write or have never seen.
Edit 2: I checked the "'InitializeCulture' is not a member of 'ASP.media_test_aspx" error and it usually is a discrepancy between the class being inherited on the aspx page not being the correct as in the aspx.vb file. However, in this case, there isn't a discrepancy as it's the correct file.
Edit: Some of the error messages I am getting:
Error 4 'GetWrappedFileDependencies' is not a member of 'ASP.media_test_aspx'. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 103
Error 2 Class 'media_test_aspx' must implement 'ReadOnly Property IsReusable As Boolean' for interface 'System.Web.IHttpHandler'. Implementing property must have matching 'ReadOnly' or 'WriteOnly' specifiers. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 84
Error 10 'ProcessRequest' is not a member of 'Media_Test'. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\apps\f1b28c0f\bab8f810\App_Web_nkhy2w0y.0.vb 342
Error 1 'InitializeCulture' is not a member of 'ASP.media_test_aspx'. C:\Users\handcm\Documents\Visual Studio 2010\WebSites\APPS\Media\Test.aspx 1
I don't even know what the last one is referring to, as there is definitely not an "Initialize Culture" on the page.

Sending CSV created on the fly back to client for download

I'm converting a bunch of FOXPRO / FOXWEB apps to ASP.NET.
The underlying DB is still foxpro (for the moment).
I am passing a table to some VB.NET code that I want to have converted to a CSV file and sent back to the client for download. And it works! Sort of ... It works sometimes, but at other times, instead of asking me if I want to download the CSV file, it just spews the file to the browser window.
On the asp side, I am passing the response object, the table and the csv file name.
<%
Dim xls_fn As String = "test01.csv"
'OLEDB call to fill up 'tbl' ... this works.
sendTableAsCSVtoClient(response, tbl, xls_fn)
%>
In the file clsCommon.vb, I have the following code:
Option Explicit On
'Option Strict On
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.Page
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Diagnostics
Imports System.Data
Imports System.Data.OleDb
Public Class clsCommon
Inherits Page
Public Shared Function enq(ByVal str As String) As String
Dim dq As String
dq = """"
Return dq & str & dq
End Function
' some other functions and subs defined in here ... blah blah blah
' ...
Public Shared Function sendTableAsCSVtoClient(ByVal resp As HttpResponse, ByVal sqlTable As DataTable, ByVal xls_fn As String) As Boolean
Dim r As DataRow
Dim c As DataColumn
Dim sep As String = ","
Dim FileExtension As String
Dim lcFileNameONLY As String
Dim i As Integer
Dim dq As String = """"
FileExtension = UCase(Path.GetExtension(xls_fn))
lcFileNameONLY = UCase(Path.GetFileNameWithoutExtension(xls_fn))
resp.Clear()
resp.ClearContent()
resp.ClearHeaders()
resp.ContentType = "application/vnd.ms-excel"
resp.AddHeader("Content-Disposition", "inline; filename=" & lcFileNameONLY & ".csv")
For Each c In sqlTable.Columns
resp.Write(UCase(c.ColumnName) & sep)
Next
resp.Write(vbCrLf)
For Each r In sqlTable.Rows
For i = 0 To sqlTable.Columns.Count - 1
resp.Write(enq(r(i)) & sep)
Next
resp.Write(vbCrLf)
Next
resp.End()
Return True
End Function
End Class
What's causing this?
How do I get around it?
I'm guessing it doesn't really matter that the source of the data is a table.
Note that the file is created on the fly and never exists on the file system of the server.
tx,
tff
Instead of using a Content-Disposition header that is Inline, use Attachment - this will always prompt for a download.
Change the following line from:
resp.AddHeader("Content-Disposition", "inline; filename=" & lcFileNameONLY & ".csv")
To
resp.AddHeader("Content-Disposition", "attachment; filename=" & lcFileNameONLY & ".csv")
See this and this for examples.
The inline type means that the browser is free to render it inline (within the browser), if in knows how to.
And see this SO question, asking why inline sometimes prompts for downloads (the exact opposite of your question...).
The issue is your Content-disposition header. It should be "attachment" instead of "inline".
You may also want to set the content type to be "text/csv"instead of "application/vnd.ms-excel". This way you're more accurate, and if they prefer to use something else for CSV it should work better. However for an in-house app perhaps vnd.ms-excel might work better?
I agree with the Oded and chmullig that you should change the Content-Disposition, but I also recommend using the buffer and finishing the response with a flush:
resp.Clear()
resp.Buffer = true
'build csv
resp.Flush()
resp.Close()
I believe a call to .End() throws a ThreadAbortException to stop execution which can cause issues depending on how you handle your exceptions. See here for more info

Reading, parsing and posting data from a .csv file into a SQL database asp.net

I have the following data that basically I only need a few bits of information from:
Resource:X - Y;Z - Å;Type:(all) From Date:
07/12/2010 - To Date 07/12/2010 Sort
by:Time Include Referring
source/physician:No Footer:Default
Criteria:None
","Appointments","X,
Y","ZAssociates","Monday, July 12,
2010","Time","Patient Name","Patient
ID","Appt. Type","Ref. Source/
Physician","Phone","Type","DOB
","Z, X","Y","7/12/2010
12:00:00AM","Time","Patient
Name","Patient ID","Appt.
Type","Phone","Type","DOB "," 7:30
[snip]
The only things I need from this are:
Patients Name
Drs Name
Patients Phone Number
Appt Time
Appt Date
and the rest of the information I can discard. A customer uploads this as a .csv file (even though it really isn't as you can see) and I'd like to parse the needed information and post that to my SQL database and discard the rest. I think I can do this with a dataset but I've never built that before. The fields from the customer will always be the same and the fields I will need will always be the same.
Also, the date time has to be in the format of yyyy/mm/dd:hhmm and the phone number always has to have 512 as a prefix. Here is the code I currently have for my site:
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim SaveLocation = "\\xxxWEB3\wwwroot\Webfile1\Reminders\Doug_Ancil\doug.csv"
If UploadFile(SaveLocation) Then
'the file was uploaded: now try saving it to the database
SaveToDatabase(SaveLocation)
End If
End Sub
Private Function UploadFile(ByVal SavePath As String) As Boolean
Dim fileWasUploaded As Boolean = False 'indicates whether or not the file was uploaded
'Checking if the file upload control contains a file
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
Try
'checking if it was .txt file BEFORE UPLOADING IT!
'You used to upload it first...but the file could be a virus
If File1.FileName = ("doug.csv") = False Then
'The file is not the expected type...do not upload it
'just post the validation message
message.Text = "Sorry, thats not the correct file."
message2.Text = "Please locate and upload 'doug.csv'"
Else
'The file is a .txt file
'checking to see if the file exists already
'If it does exist Deleting the existing one so that the new one can be created
If IO.File.Exists(SavePath) Then
IO.File.Delete(SavePath)
End If
'Now upload the file (save it to your server)
File1.PostedFile.SaveAs(SavePath)
'After saving it check to see if it exists
If File.Exists(SavePath) Then
'Upload was sucessful
message.Text = "Thank you for your submission."
fileWasUploaded = True
Else
'the file was not saved
message.Text = "Unable to save the file."
End If
End If
Catch Exc As Exception
'We encountered a problem
message.Text = "Your file was not in the correct format. Please contact Customer Service at xxxx-xxxx-xxxx."
End Try
Else
'No file was selected for uploading
message.Text = "Please select a file to upload."
End If
Return fileWasUploaded
End Function
Private Sub SaveToDatabase(ByVal SavePath As String)
Try
Dim sqlQueryText As String = _
"BULK INSERT dialerresults " + _
"FROM '" & SavePath & "' " + _
"WITH ( FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n' )"
' and bulk import the data:
'If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
'Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
Dim connection As String = "data source=10.2.1.40;initial catalog=IVRDialer;uid=xxxx;password=xxxxx;"
Using con As New SqlConnection(connection)
con.Open()
' execute the bulk import
Using cmd As New SqlCommand(sqlQueryText, con)
cmd.ExecuteNonQuery()
End Using
End Using
'Else
'message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
'End If
Catch ex As Exception
message.Text = "Your file was not in the correct format. Please contact Customer Service at xxxxxxx."
End Try
End Sub
End Class
Thank you,
Doug
Personally, I'd use a library like FileHelpers to parse/load the data then whatever my typical means of data access for this app is to update it.

Resources