I have a vb.net web app, and I need to give my users the facility to download a ms-word .doc file. This file needs to be created dynamically, and should contain some bold text and a table.
I've come across this code, which builds a .doc file, and lets you download it:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFileName As String = "GenerateDocument" + ".doc"
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName)
Dim strHTMLContent As StringBuilder = New StringBuilder()
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Charset = ""
HttpContext.Current.Response.ContentType = "application/msword"
strHTMLContent.Append("<p align='Center'>MY CONTENT GOES HERE</p>".ToString())
HttpContext.Current.Response.Write(strHTMLContent)
HttpContext.Current.Response.End()
HttpContext.Current.Response.Flush()
End Sub
...but I don't know how to make the text bold, or create a table. I'm sure there's a better way.
Sorry to answer my own question, but I've just come across this: http://www.codeproject.com/KB/office/Wordyna.aspx
It works perfectly for me, because it allows HTML input. So tables are a doddle.
Public Sub Page_Load(sender as Object, e as EventArgs)
'build the content for the dynamic Word document
'in HTML alongwith some Office specific style properties.
Dim strBody As New System.Text.StringBuilder("")
strBody.Append("<html " & _
"xmlns:o='urn:schemas-microsoft-com:office:office' " & _
"xmlns:w='urn:schemas-microsoft-com:office:word'" & _
"xmlns='http://www.w3.org/TR/REC-html40'>" & _
"<head><title>Time</title>")
'The setting specifies document's view after it is downloaded as Print
'instead of the default Web Layout
strBody.Append("<!--[if gte mso 9]>" & _
"<xml>" & _
"<w:WordDocument>" & _
"<w:View>Print</w:View>" & _
"<w:Zoom>90</w:Zoom>" & _
"<w:DoNotOptimizeForBrowser/>" & _
"</w:WordDocument>" & _
"</xml>" & _
"<![endif]-->")
strBody.Append("<style>" & _
"<!-- /* Style Definitions */" & _
"#page Section1" & _
" {size:8.5in 11.0in; " & _
" margin:1.0in 1.25in 1.0in 1.25in ; " & _
" mso-header-margin:.5in; " & _
" mso-footer-margin:.5in; mso-paper-source:0;}" & _
" div.Section1" & _
" {page:Section1;}" & _
"-->" & _
"</style></head>")
strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" & _
"<div class=Section1>" & _
"<h1>Time and tide wait for none</h1>" & _
"<p style='color:red'><I>" & _
DateTime.Now & "</I></p>" & _
"</div>" & _
"<div>" & _
"<table border=1>" & _
"<tr>" & _
"<td>1</td>" & _
"<td>2</td>" & _
"<td>3</td>" & _
"</tr>" & _
"<tr>" & _
"<td>a</td>" & _
"<td>b</td>" & _
"<td>c</td>" & _
"</tr>" & _
"</table>" & _
"</div>" & _
"</body></html>")
'Force this content to be downloaded
'as a Word document with the name of your choice
Response.AppendHeader("Content-Type", "application/msword")
Response.AppendHeader ("Content-disposition", _
"attachment; filename=myword.doc")
Response.Write(strBody)
End Sub
Related
I have a sub to upload file. How do I restrict the filetype that can be uploaded? I don't want the user to be able to upload .exe, .dll, .ini files. Right now any files can be uploaded.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.HasFile Then
Try
FileUpload1.SaveAs("C:\Uploads\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpload1.PostedFile.ContentLength & "<br>" & _
"Content type: " & _
FileUpload1.PostedFile.ContentType & "<br>" & _
"Location Saved: C:\Uploads\" & _
FileUpload1.FileName
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End Sub
If FileUpload1.HasFile Then
Try
if FileUpload1.FileName.ToLower().Contains(".exe") or FileUpload1.FileName.ToLower().Contains(".dll") or FileUpload1.FileName.ToLower().Contains(".ini")
' show your alert here stating this type of files are not allowed
return
End if
FileUpload1.SaveAs("C:\Uploads\" & _
FileUpload1.FileName)
Label1.Text = "File name: " & _
FileUpload1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpload1.PostedFile.ContentLength & "<br>" & _
"Content type: " & _
FileUpload1.PostedFile.ContentType & "<br>" & _
"Location Saved: C:\Uploads\" & _
FileUpload1.FileName
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
But, I would suggest you client side check will be better too.
I have created a Master page. And I have created a default page named default.aspx The defult aspx file has all of the standard content and ID's. In the ID I made a div tag to hold content for the dynamic page.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Default.aspx.vb" Inherits="P03_S02.Link1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="DynPage" runat="server"></div>
</asp:Content>
This is all good. So by using SQL server express that comes with Visual Studio 2012 I created a table with data in it. The entitys in the table is
ProductID
Name
Price
Quantity
Now in the default.aspx.vb page I completed the following code.
Imports System.Data
Imports System.Data.SqlClient
Public Class Catelog
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim Connection As SqlConnection
Dim Command As SqlCommand
Dim Reader As SqlDataReader
Connection = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Products.mdf;Integrated Security=True")
Dim CommandString As String
CommandString = "SELECT * FROM Product"
Command = New SqlCommand(CommandString)
Command.CommandType = CommandType.Text
Command.Connection = Connection
Command.Connection.Open()
Command.ExecuteNonQuery()
Reader = Command.ExecuteReader(CommandBehavior.CloseConnection)
Dim ProductList As String
If Reader.HasRows Then
ProductList &= "<table width=""100%"">"
ProductList &= " <tr bgcolor=""#00CCFF"">"
ProductList &= "<td><b>ID</b></td>"
ProductList &= "<td><b>Product</b></td>"
ProductList &= "<td><b>Price</b></td>"
ProductList &= "<td><b>Quantity</b></td>"
ProductList &= "</tr>"
While Reader.Read
Dim newProduct As String
ProductList &= "<tr>"
ProductList &= "<td>" & Reader("ProductID") & "</td>" & _
"<td>" & "" & Reader("Name") & "" & "</td>" & _
"<td>" & Reader("Price") & "</td>" & _
"<td>" & Reader("Quantity") & "</td>"
ProductList &= "</tr>"
End While
ProductList &= "</table>"
End If
Catelog.InnerHtml = ProductList
Command.Connection.Close()
' Command.Dispose()
Connection.Dispose()
ProductCatelog.InnerHtml = ProductList
End If
End Sub
End Class
As you can see the table will display all data form the table. In the while loop I make each name in the table hyperlinks to another apsx file named Link1.
I used the same code as above but changed a few things in Link1.aspx.vb
Added:
Dim ProductID As String
ProductID = Request.QueryString("ProdID").ToString()'problem possible here
Changed the Display of data:
Dim ProductList As String
If Reader.HasRows Then
ProductList &= "<table width=""100%"">"
ProductList &= " <tr bgcolor=""#00CCFF"">"
ProductList &= "<td><b>Product</b></td>"
ProductList &= "<td><b>Price</b></td>"
ProductList &= "<td><b>Quantity</b></td>"
ProductList &= "</tr>"
While Reader.Read
Dim newProduct As String
ProductList &= "<tr>"
ProductList &= "<td>" & Reader("Name") & "</td>" & _
"<td>" & Reader("Price") & "</td>" & _
"<td>" & Reader("Quantity") & "</td>"
ProductList &= "</tr>"
End While
ProductList &= "</table>"
End If
Used the following to display only one record:
Dim CommandString As String
CommandString = "SELECT * FROM Product where ProductID =" & ProductID
My goal is if you click on a name it will link it to Link1.aspx and display only information about that name (Info in table). That does not happen because the program crashes. I have used all my basic debugging knowledge.
In default.aspx.vb you have :
"<td>" & "" & Reader("Name") & "" & "</td>" & _
passing name as ProdID
for ProdID you are passing Name and in link1.aspx.vb you are querying like:
Dim ProductID As String
ProductID = Request.QueryString("ProdID").ToString()'problem possible here
and later:
Dim CommandString As String
CommandString = "SELECT * FROM Product where ProductID =" & ProductID
expecting ProdID, not Name.
So, in default.aspx.vb you should change the line to:
<td>" & "<a href=""Link1.aspx?ProdID=""" & Reader("ProdID").ToString() & ">" &
Firstly, look up SqlParameters, because you've just opened your code up to SQL injection by passing parameters in the QueryString.
To address your question, I think the problem lies with this line:
"<td>" & "" & Reader("Name") & "" & "</td>" & _
You are closing your double-quote too soon and the productId isn't being put inside the href.
I'd rewrite it like this:
"<td>" & "" & Reader("Name") & "" & "</td>" & _
Subtle difference, but it should make it work.
Finally, always do a null/empty string check on the QueryString before you call .ToString(). Compare your QueryString entry using String.IsNullOrWhiteSpace(), and then only continue processing when String.IsNullOrWhiteSpace() returns false.
I am using visual developer 2012 and have a simple form to upload the file to the server and then enter the name of the file into another table. For whatever reason it runs twice and enter the values twice in the second table:
Protected Sub BtnUploadImg_Click(sender As Object, e As EventArgs) Handles BtnUploadImg.Click
If IsPostBack Then
' Dim CurrentPath As String = Server.MapPath("C:\DSimages\")
If FileUpLoad1.HasFile = True Then
Try
FileUpLoad1.SaveAs("C:\DSimages\" & _
FileUpLoad1.FileName)
Label1.Text = "File name: " & _
FileUpLoad1.PostedFile.FileName & "<br>" & _
"File Size: " & _
FileUpLoad1.PostedFile.ContentLength & " kb<br>" & _
"Content type: " & _
FileUpLoad1.PostedFile.ContentType
ImageDataSource.InsertParameters("ImgName").DefaultValue = FileUpLoad1.PostedFile.FileName
Catch ex As Exception
Label1.Text = "ERROR: " & ex.Message.ToString()
End Try
Else
Label1.Text = "You have not specified a file."
End If
End If
ImageDataSource.Insert()
FileUpLoad1.PostedFile.InputStream.Dispose()
End Sub
Do you have the same code under the page load event? The postback will fire both events, so if you do it will run twice.
I have the following procedure, which works fine. The only part that I am having an issue with is when the CompNames list has more than 1 record. I am trying to use String.Join with vbCrLf but it doesnt work.
Anyone have any ideas or an alternative I could use.
Public Sub gvTeamList_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim TeamID As Integer
If e.Row.RowType = DataControlRowType.DataRow Then
TeamID = DataBinder.Eval(e.Row.DataItem, "TeamID")
Dim sSQL As String
sSQL = "SELECT C.CompetitionName, CTT.TeamID " & _
"FROM tblCompetition C " & _
"left join tblCompetitionToTeam CTT on C.CompetitionID = CTT.CompetitionID " & _
"left join tblTeam T on CTT.TeamID = T.TeamID " & _
"where CTT.TeamID = " & TeamID
Dim dr = DataClass.GetDataReader(sSQL)
Dim bRows As Boolean = dr.HasRows
Dim CompNames As New List(Of String)
While dr.Read
CompNames.Add(dr("CompetitionName"))
End While
Dim Name As String
If CompNames.Count > 0 Then
For Each Name In CompNames
e.Row.Cells(5).Text = String.Join(vbCrLf, CompNames.ToArray)
Next
End If
'e.Row.Cells(5).Text =
e.Row.Cells(5).ForeColor = Drawing.Color.Yellow
e.Row.Cells(5).BackColor = Drawing.Color.DarkBlue
dr.Close()
End If
End Sub
I have also tried Environment.NewLine and that doesnt work either
It appears you are using a WebForms application. In HTML, a line return generally has no effect because whitespace is ignored (unless it's embedded in certain tags). You want to use <br /> to generate a line break:
e.Row.Cells(5).Text = String.Join("<br />", CompNames.ToArray)
Also, you don't need the For Each loop, because String.Join enumerates the entire array in a single call. It's redundant to run this once for each Name in CompNames.
ScriptManager scrmgr = (ScriptManager)this.Master.FindControl("scrmgr");
scrmgr.SetFocus(txtSearch);
this is my coding ,it works all browser.but my problem is chrome display with selection if textbox has any value..
i want just remove the selection.......
I think there is no better solution than code your own setFocus function. The simpliest cross-browser method to remove the selection is to store the text temporarily, clear the value and set it again afterwards. Then call the js-function focus on the input-control.
I think this VB.Net Code helps to get the idea(I dont know if you prefer c#):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
setFocusOnControl(Me.TextBox1)
End Sub
Public Sub setFocusOnControl(ByVal ctrl As Control)
Dim script As String = "" & vbCrLf & _
"var control = document.getElementById('" & ctrl.ClientID & "');" & vbCrLf & _
"var temptext = control.value;" & vbCrLf & _
"control.value='';" & vbCrLf & _
"control.value=temptext;" & vbCrLf & _
"control.focus();" & vbCrLf & _
"" & vbCrLf
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "setFocusOnControlScript", script, True)
End Sub