My application will search ms office document such as word, excel, etc in folder and then read the tag in metadata.
But my function will hang/stop when the function try to open a password protected (need password) file.
How can I detect the file had been password protected? If yes, I skip this file and proceed on next file.
'Read Word metadata
Public Sub ReadWord(WordFileName As String)
Dim Wapp As New Microsoft.Office.Interop.Word.Application
Dim docWord As New Microsoft.Office.Interop.Word.Document
If Wapp Is Nothing Then
Wapp = New Microsoft.Office.Interop.Word.Application
End If
If docWord Is Nothing Then
docWord = New Microsoft.Office.Interop.Word.Document
Else
docWord.Close()
End If
docWord = Wapp.Documents.Open(WordFileName)
Dim _BuiltInProperties As Object = docWord.BuiltInDocumentProperties
If Not _BuiltInProperties Is Nothing Then
word_keyword = _BuiltInProperties("Keywords").Value
End If
If Not docWord Is Nothing Then
docWord.Close()
End If
If Not Wapp Is Nothing Then
Wapp.Quit()
End If
End Sub
'Read Excel metadata
Public Sub ReadExcel(ExcelFileName As String)
Dim Wapp As New Microsoft.Office.Interop.Excel.Application
Dim excelbook As Microsoft.Office.Interop.Excel.Workbook
If Wapp Is Nothing Then
Wapp = New Microsoft.Office.Interop.Excel.Application
End If
excelbook = Wapp.Workbooks.Open(ExcelFileName)
Dim _BuiltInProperties As Object = excelbook.BuiltinDocumentProperties
If Not _BuiltInProperties Is Nothing Then
excel_keyword = _BuiltInProperties("Keywords").Value
End If
If Not excelbook Is Nothing Then
excelbook.Close()
End If
If Not Wapp Is Nothing Then
Wapp.Quit()
End If
End Sub
Related
I've developed a VB.Net App using Visual studio 2015 on my Laptop which will print a rdlc local report for each selected row from a Gridview control directly to my laptop's default printer (which is a network printer) using the Microsoft code for 'walkthrough: Printing a Local Report without Preview' (and runs successfully on my local IIS express). When I deploy this App to a virtual company windows 2012 server that has IIS8 running, it no longer sees the default printer on my laptop (and tries to use the default printer on the windows 2012 server). I've searched the web to no success. I assume it's possible because when I use the reportviewer control in other apps I've developed and deployed on the Windows 2012 server, it can see the list of printers from my local laptop. Any ideas?
Here's the relevant VB code I'm using now...
Imports System.Management
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WebForms
Partial Class _Default
Inherits System.Web.UI.Page
Implements IDisposable
Private m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Public Shared ViewID As String
Public Shared UserID As String
Public Shared StampID As String
Public Shared GridViewQry As String
Public Shared OpenCntr As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sqlConnection2 As New SqlConnection("DataSource=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
Response.Cache.SetNoStore()
OpenCntr = OpenCntr + 1
ViewID = Request.QueryString("ViewID")
If ViewID = "" Then
Response.Redirect("http://AOXWEBAPP1.SCOTT.COM/login/login.aspx")
Else
UserID = Request.QueryString("UserID")
StampID = Request.QueryString("StampID")
End If
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=1 WHERE Printed = 1"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
If OpenCntr = 1 Then
GridViewQry = "SELECT [Printed], [Customer], [AssySN], [Dte], [AssyPartNbr], [Operator], [PrintDate] FROM [Super_FinalChk] ORDER BY [Dte]"
End If
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
If (superfinalchk.Tables.Count > 0) Then
PrintATRs.DataSource = superfinalchk
If Not IsPostBack Then
PrintATRs.DataBind()
End If
Else
TextBox1.Text = "Unable to Connect to Database"
End If
' TextBox1.Text = DefaultPrinterName()
End Sub
' Routine to provide to the report renderer, in order to
' save an image for each page of the report.
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream()
m_streams.Add(stream)
Return stream
End Function
' Export the given report as an EMF (Enhanced Metafile) file.
Private Sub Export(ByVal report As LocalReport)
Dim deviceInfo As String = "<DeviceInfo>" &
"<OutputFormat>EMF</OutputFormat>" &
"<PageWidth>8.5in</PageWidth>" &
"<PageHeight>11in</PageHeight>" &
"<MarginTop>0.25in</MarginTop>" &
"<MarginLeft>0.50in</MarginLeft>" &
"<MarginRight>0.50in</MarginRight>" &
"<MarginBottom>0.25in</MarginBottom>" &
"</DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
End Sub
' Handler for PrintPageEvents
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX),
ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY),
ev.PageBounds.Width,
ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
Private Sub PrintRep()
If m_streams Is Nothing OrElse m_streams.Count = 0 Then
Throw New Exception("Error: no stream to print.")
End If
Dim printDoc As New PrintDocument()
If Not printDoc.PrinterSettings.IsValid Then
**
It FAILS HERE!!!!
**
Throw New Exception("Error: cannot find the printer.")
Else
AddHandler printDoc.PrintPage, AddressOf PrintPage
m_currentPageIndex = 0
printDoc.Print()
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If m_streams IsNot Nothing Then
For Each stream As Stream In m_streams
stream.Close()
Next
m_streams = Nothing
End If
End Sub
Private Function LoadSuperFinalChkVwData(AssySN As String) As DataTable
Dim sqlConnection1 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim querystring As String = "SELECT * FROM dbo.Super_FinalChkVw WHERE AssySN = '" & AssySN & "'"
Dim adapter As New SqlDataAdapter(querystring, sqlConnection1)
Dim superfinalchkvw As New DataSet("DataSet1")
adapter.Fill(superfinalchkvw, "Super_FinalChkVw")
Return superfinalchkvw.Tables(0)
End Function
Protected Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
Dim report As New LocalReport()
Dim sqlConnection2 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Dim cudate As DateTime
Dim AssySN As String
Dim cntr As Integer = 0
Dim SelectCount As Integer = 0
cudate = DateTime.Now
cmd2.Parameters.AddWithValue("#cudate", cudate)
For Each row As GridViewRow In PrintATRs.Rows
cntr = cntr + 1
Dim cb As CheckBox = DirectCast(row.FindControl("checkbox3"), CheckBox)
AssySN = row.Cells(3).Text
If cb.Checked Then
SelectCount = SelectCount + 1
report.ReportPath = "..\..\Manufacture\Superiox\ATR.rdlc"
report.DataSources.Clear()
report.DataSources.Add(New ReportDataSource("DataSet1", LoadSuperFinalChkVwData(AssySN)))
Export(report)
PrintRep()
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=0, Printed=1, PrintDate=#cudate WHERE AssySN = '" & AssySN & "';"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
End If
Next
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
PrintATRs.DataSource = superfinalchk
PrintATRs.DataBind()
If SelectCount > 0 Then
TextBox1.Text = "Reports Have Been Printed!"
Else
TextBox1.Text = "Please Select Reports to Print!"
End If
End Sub
I am processing PDF/JPG/GIF files using HTTP Handler.
A popup receives a btnId in query string and detects the file extension then calls the handler with btnId and processes the request.
Files are physical stored on server with file names in DB.
When there is an issue with the file like file not found or some error I want an alert to be displayed and opened window to be closed which is not working right now.
I know the reason and that is I am writing the alert into response which will eventually land in either object tag or Image tag.
Can some one please suggest how can this be achieved. Help will be appreciated. Thanks!!!
Public Class ViewHelpContent
Inherits System.Web.UI.Page
'Method that dynamically decides based on file extension which file viewer to render
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim embed As String = String.Empty
Dim count As Integer
Dim fileName As String = String.Empty
Dim extension As String = String.Empty
Try
If Not IsPostBack Then
If Not Request.QueryString("btnId") Is Nothing Then
Dim btnId As String = Request.QueryString("btnId").ToString()
count = GetFileAttachedToButton(btnId, fileName)
extension = Path.GetExtension(fileName)
If extension.ToLower() = ".pdf" Then
embed = "<object id=""objPDFViewer"" data=""{0}{1}"" type=""application/pdf"">"
embed &= "If you are unable to view file, you can download from here"
embed &= " or there is no file available to be viewed."
embed &= "</object>"
ElseIf extension.ToLower() = ".jpeg" OrElse extension.ToLower() = ".jpg" OrElse extension.ToLower() = ".gif" Then
embed = "<img id=""objImgViewer"" src=""{0}{1}"" alt=""No file is available to be viewed."" />"
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('No help content uploaded for this button.');", True)
Return
End If
helpContent.Text = String.Format(embed, ResolveUrl("~/ProcessHelpContent.ashx?btnId="), btnId)
End If
End If
Catch ex As Exception
ExceptionHandler.LogError(ex)
JSHelper.ShowSystemError(Me)
End Try
End Sub
End Class
Public Class ProcessHelpContent
Implements System.Web.IHttpHandler
'Sub that processes the help request and generates the requested content based on button Id
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim btnId As String = String.Empty
Dim fileName As String = String.Empty
Dim contentType As String = String.Empty
Dim outputDir As String = String.Empty
Dim count As Integer
Dim strPath As FileInfo = Nothing
Dim extension As String = String.Empty
Try
If Not context.Request.QueryString("btnId") Is Nothing Then
btnId = context.Request.QueryString("btnId").ToString()
outputDir = ConfigurationManager.AppSettings("HelpContentFilesFolder")
count = GetFileAttachedToButton(btnId, fileName)
strPath = New FileInfo(outputDir & fileName)
If Not String.IsNullOrWhiteSpace(fileName) Then
If File.Exists(strPath.FullName) Then
extension = Path.GetExtension(strPath.FullName)
If context.Request.QueryString("download") = "1" Then
context.Response.AppendHeader("Content-Disposition", Convert.ToString("attachment; filename=") & fileName)
End If
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
If extension.ToLower() = ".pdf" Then
context.Response.ContentType = "application/pdf"
ElseIf extension.ToLower() = ".jpg" OrElse extension.ToLower() = ".jpeg" Then
context.Response.ContentType = "image/jpeg"
ElseIf extension.ToLower() = ".gif" Then
context.Response.ContentType = "image/gif"
End If
context.Response.TransmitFile(strPath.FullName)
context.Response.Flush()
Else
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End If
Else
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End If
End If
Catch ex As Exception
ExceptionHandler.LogError(ex)
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End Try
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
code snippet for my image upload:
'Read the file and convert it to Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype based on File Extension
Select Case ext
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
End Select
If Not contenttype Is String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
cmd.Parameters.Add("#imgName", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#contentType", SqlDbType.VarChar).Value = contenttype
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes
Else
cmd.Parameters.Add("#imgName", SqlDbType.VarChar).Value = DBNull.Value
cmd.Parameters.Add("#contentType", SqlDbType.VarChar).Value = DBNull.Value
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = DBNull.Value
End If
con.Open()
cmd.ExecuteNonQuery()
con.Close()
preview image:
Protected Sub preview_btn_Click(sender As Object, e As EventArgs) Handles preview_btn.Click
Session("ImageBytes") = FileUpload1.FileBytes
Image1.ImageUrl = "~/Handler1.ashx"
preview_btn.BackColor = Drawing.Color.Lime
preview_btn.ForeColor = Drawing.Color.White
Image1.BorderColor = Drawing.Color.Lime
End Sub
Handler1.ashx
<%# WebHandler Language="VB" Class="Handler1" %>
Imports System
Imports System.Web
Public Class Handler1 : Implements System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
If (context.Session("ImageBytes")) IsNot Nothing Then
Dim image As Byte() = DirectCast(context.Session("ImageBytes"), Byte())
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(image)
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
The preview image works but whenever I invoke the preview image button, the FileUpload control get reset.
So from the FileUpload control's point of view, it is as if the user did not select any image in the first place.
I tried storing the value of FileUpload1.PostedFile.FileName in some variable first and then manually set back its value but FileUpload1.PostedFile.FileName appears to be read-only, which makes sense from a security perspective.
So workaround for this?
For a quick solution, I would do the following:
Preview - Save the posted file in session. Set the Image1 image url to handler.
Handler - Get the posted file from session. Write image to response.
Upload - Check if file exists in FileUpload1, get it. If not, get it
from session. Save image. Clear session.
Here's the code I would use:
EDIT : Changed the code to fix issue with larger (> 50kb) images
aspx.vb
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
'Disabled DB operations for test
'Read the file and convert it to Byte Array
Dim filePath As String = String.Empty
Dim filename As String = String.Empty
Dim ext As String = String.Empty
Dim contenttype As String = String.Empty
Dim bytes As Byte()
If FileUpload1.HasFile Then
filePath = FileUpload1.PostedFile.FileName
Else
If (Session("MyFile") IsNot Nothing AndAlso Session("MyFileName") IsNot Nothing) Then
filePath = Session("MyFileName").ToString()
bytes = DirectCast(Session("MyFile"), Byte())
End If
End If
filename = Path.GetFileName(filePath)
ext = Path.GetExtension(filename)
'Set the contenttype based on File Extension
Select Case ext
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
End Select
If Not contenttype Is String.Empty Then
If FileUpload1.HasFile Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
bytes = br.ReadBytes(fs.Length)
End If
'insert the file into database
cmd.Parameters.Add("#imgName", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#contentType", SqlDbType.VarChar).Value = contenttype
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = bytes
Else
cmd.Parameters.Add("#imgName", SqlDbType.VarChar).Value = DBNull.Value
cmd.Parameters.Add("#contentType", SqlDbType.VarChar).Value = DBNull.Value
cmd.Parameters.Add("#data", SqlDbType.Binary).Value = DBNull.Value
End If
con.Open()
cmd.ExecuteNonQuery()
con.Close()
'Cleanup
Session("MyFile") = Nothing
Session("MyFileName") = Nothing
End Sub
Protected Sub preview_btn_Click(sender As Object, e As EventArgs) Handles preview_btn.Click
If FileUpload1.PostedFile IsNot Nothing Then
Dim file As HttpPostedFile = FileUpload1.PostedFile
Dim data As Byte() = New [Byte](file.ContentLength - 1) {}
file.InputStream.Read(data, 0, file.ContentLength)
Session("MyFile") = data
Session("MyFileName") = FileUpload1.PostedFile.FileName
Image1.ImageUrl = "~/Handler1.ashx"
preview_btn.BackColor = Drawing.Color.Lime
preview_btn.ForeColor = Drawing.Color.White
Image1.BorderColor = Drawing.Color.Lime
End If
End Sub
Handler1.ashx
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
If (context.Session("MyFile")) IsNot Nothing Then
Dim storedImage = TryCast(context.Session("MyFile"), Byte())
If storedImage IsNot Nothing Then
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(storedImage)
End If
End If
End Sub
Hope it helps!
I followed a tutorial an ran the below code without any errors. The file "uploads", however no data is inserted into my SQL Server table.
Data should be inserted into the content table.
Content Table:
Document.aspx
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Documents
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click
Dim filePath As String = FileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
Can anyone tell me what's going on ?
EDIT: Debug Breakpoint # InsertUpdateData(cmd) :
SqlDbType.Binary Binary {1} System.Data.SqlDbType
+ bytes {Length=4136752} Byte()
+ cmd {System.Data.SqlClient.SqlCommand} System.Data.SqlClient.SqlCommand
+ cmd.Parameters {System.Data.SqlClient.SqlParameterCollection} System.Data.SqlClient.SqlParameterCollection
I have created empty database and added table content just like you have and I used code almost the same as you and it worked fine.
Again, if no exception occurs, please check your connection string and see whether the rows been added to the table in the db specified in connection string.
Here is my code (which is working fine), a bit modified from yours:
Imports System.Data.SqlClient
Imports System.IO
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnTest1.Click
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = "filename"
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = "jpg"
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim conn As New SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
I add sample of SQL to test on DB:
INSERT INTO [master_db].[dbo].[content]
([content_name]
,[content_type]
,[content_file])
VALUES
('test'
,'png'
,0x111111111111111)
SELECT * FROM [master_db].[dbo].[content]
I came across this post looking looking for an example. I used the example code you posted and had the same problem. I found and resolved the following issues and got it working:
I created the db table as pictured. content_type of nchar(5) was the first problem since you were inserting something like "application/vnd.ms-word" which was too big.
The next error was because I had not defined the content_id to be an identity column and since it wasn't listed in the insert statement it failed.
Next I had an error as my db user didn't have insert privileges.
The biggest problem is that the return message was always a success message because even though the InsertUpdateData function was catching errors it was not notifying the calling code. This made me think things were okay. doh! Using a breakpoint on the ExecuteNonQuery allowed me to see the errors.
Hope that helps the next person that stops by....
I am using wicked code sqlsitemapprovider or it's VB version. Most of the things are going OK! But when I wanted to hide some of the nodes from appearing on menu while staying shown on sitemappath I cannot figure it out. I tried to change the sqlsitemapprovider code but was unsuccessfull. I have found David Sussman's (from sp.net) answer. but it was for a .sitemap file. So how can I manage to do the same with the sql sitemap provider mentioned above.
I added a column named visible to my SiteMap table it's type is bit and then I have done these changes (Sorry for such long code):
Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Web.Configuration
Imports System.Collections.Generic
Imports System.Configuration.Provider
Imports System.Security.Permissions
Imports System.Data.Common
Imports System.Data
Imports System.Web.Caching
''' <summary>
''' Summary description for SqlSiteMapProvider
''' </summary>
<SqlClientPermission(SecurityAction.Demand, Unrestricted:=True)> _
Public Class SqlSiteMapProvider
Inherits StaticSiteMapProvider
Private Const _errmsg1 As String = "Basamak no bulunamadı"
Private Const _errmsg2 As String = "Çift Basamak No"
Private Const _errmsg3 As String = "Üst Basamak Bulunamadı"
Private Const _errmsg4 As String = "Hatalı Üst Basamak"
Private Const _errmsg5 As String = "Bağlantı dizesi bulunamadı veya boş"
Private Const _errmsg6 As String = "Bağlantı dizesi bulunamadı"
Private Const _errmsg7 As String = "Bağlantı dizesi boş"
Private Const _errmsg8 As String = "Hatalı sqlCacheDependency"
Private Const _cacheDependencyName As String = "__SiteMapCacheDependency"
Private _connect As String
'Database connection string
Private _database As String, _table As String
'Database info for SQL Server 7/2000 cache dependency
Private _2005dependency As Boolean = False
'Database info for SQL Server 2005 cache dependency
Private _indexID As Integer, _indexTitle As Integer, _indexUrl As Integer, _indexDesc As Integer, _indexRoles As Integer, _indexParent As Integer, _indexvisible As Boolean
Private _nodes As New Dictionary(Of Integer, SiteMapNode)(16)
Private ReadOnly _lock As New Object()
Private _root As SiteMapNode
'Added...Declare an arraylist to hold all the roles this menu item applies to
Public roles As New ArrayList
Public Overloads Overrides Sub Initialize(ByVal name As String, ByVal config As NameValueCollection)
'Verify that config isn't null
If config Is Nothing Then
Throw New ArgumentNullException("config")
End If
'Assign the provider a default name if it doesn't have one
If [String].IsNullOrEmpty(Name) Then
Name = "SqlSiteMapProvider"
End If
' Add a default "description" attribute to config if the
' attribute doesnt exist or is empty
If String.IsNullOrEmpty(config("description")) Then
config.Remove("description")
config.Add("description", "SQL site map provider")
End If
' Call the base class's Initialize method
MyBase.Initialize(Name, config)
' Initialize _connect
Dim connect As String = config("connectionStringName")
If [String].IsNullOrEmpty(connect) Then
Throw New ProviderException(_errmsg5)
End If
config.Remove("connectionStringName")
If WebConfigurationManager.ConnectionStrings(connect) Is Nothing Then
Throw New ProviderException(_errmsg6)
End If
_connect = WebConfigurationManager.ConnectionStrings(connect).ConnectionString
If [String].IsNullOrEmpty(_connect) Then
Throw New ProviderException(_errmsg7)
End If
' Initialize SQL cache dependency info
Dim dependency As String = config("sqlCacheDependency")
If Not [String].IsNullOrEmpty(dependency) Then
If [String].Equals(dependency, "CommandNotification", StringComparison.InvariantCultureIgnoreCase) Then
SqlDependency.Start(_connect)
_2005dependency = True
Else
' If not "CommandNotification", then extract database and table names
Dim info As String() = dependency.Split(New Char() {":"c})
If info.Length <> 2 Then
Throw New ProviderException(_errmsg8)
End If
_database = info(0)
_table = info(1)
End If
config.Remove("sqlCacheDependency")
End If
' SiteMapProvider processes the securityTrimmingEnabled
' attribute but fails to remove it. Remove it now so we can
' check for unrecognized configuration attributes.
If config("securityTrimmingEnabled") IsNot Nothing Then
config.Remove("securityTrimmingEnabled")
End If
' Throw an exception if unrecognized attributes remain
If config.Count > 0 Then
Dim attr As String = config.GetKey(0)
If Not [String].IsNullOrEmpty(attr) Then
Throw New ProviderException("Unrecognized attribute: " + attr)
End If
End If
End Sub
Public Overloads Overrides Function BuildSiteMap() As SiteMapNode
SyncLock _lock
' Return immediately if this method has been called before
If _root IsNot Nothing Then
Return _root
End If
' Query the database for site map nodes
Dim connection As New SqlConnection(_connect)
Try
Dim command As New SqlCommand("proc_GetSiteMap", connection)
command.CommandType = CommandType.StoredProcedure
' Create a SQL cache dependency if requested
Dim dependency As SqlCacheDependency = Nothing
If _2005dependency Then
dependency = New SqlCacheDependency(command)
ElseIf Not [String].IsNullOrEmpty(_database) AndAlso Not String.IsNullOrEmpty(_table) Then
dependency = New SqlCacheDependency(_database, _table)
End If
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
_indexID = reader.GetOrdinal("ID")
_indexUrl = reader.GetOrdinal("Url")
_indexTitle = reader.GetOrdinal("Title")
_indexDesc = reader.GetOrdinal("Description")
_indexRoles = reader.GetOrdinal("Roles")
_indexParent = reader.GetOrdinal("Parent")
_indexvisible = reader.GetOrdinal("visible")
If reader.Read() Then
' Create the root SiteMapNode and add it to the site map
_root = CreateSiteMapNodeFromDataReader(reader)
AddNode(_root, Nothing)
' Build a tree of SiteMapNodes underneath the root node
While reader.Read()
' Create another site map node and add it to the site map
Dim node As SiteMapNode = CreateSiteMapNodeFromDataReader(reader)
AddNode(node, GetParentNodeFromDataReader(reader))
End While
' Use the SQL cache dependency
If dependency IsNot Nothing Then
HttpRuntime.Cache.Insert(_cacheDependencyName, New Object(), dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, _
New CacheItemRemovedCallback(AddressOf OnSiteMapChanged))
End If
End If
Finally
connection.Close()
End Try
' Return the root SiteMapNode
Return _root
End SyncLock
End Function
Protected Overloads Overrides Function GetRootNodeCore() As SiteMapNode
SyncLock _lock
BuildSiteMap()
Return _root
End SyncLock
End Function
' Helper methods
Private Function CreateSiteMapNodeFromDataReader(ByVal reader As DbDataReader) As SiteMapNode
' Make sure the node ID is present
If reader.IsDBNull(_indexID) Then
Throw New ProviderException(_errmsg1)
End If
' Get the node ID from the DataReader
Dim id As Integer = reader.GetInt32(_indexID)
' Make sure the node ID is unique
If _nodes.ContainsKey(id) Then
Throw New ProviderException(_errmsg2)
End If
' Get title, URL, description, and roles from the DataReader
Dim title As String = IIf(reader.IsDBNull(_indexTitle), Nothing, reader.GetString(_indexTitle).Trim())
'Dim url As String = IIf(reader.IsDBNull(_indexUrl), Nothing, reader.GetString(_indexUrl).Trim())
'Dim url As String = ReplaceNullRefs(reader, _indexUrl)
Dim url As String = String.Empty
If Not (reader.IsDBNull(_indexUrl)) Then
url = reader.GetString(_indexUrl).Trim()
Else
url = ""
End If
'Eliminated...see http://weblogs.asp.net/psteele/archive/2003/10/09/31250.aspx
'Dim description As String = IIf(reader.IsDBNull(_indexDesc), Nothing, reader.GetString(_indexDesc).Trim())
'Added line below and 'ReplaceNUllRefs' func
Dim description As String = ReplaceNullRefs(reader, _indexDesc)
'Changed variable name from 'roles' to 'rolesN' and added line 230 to dump all roles into an arrayList
Dim rolesN As String = IIf(reader.IsDBNull(_indexRoles), Nothing, reader.GetString(_indexRoles).Trim())
Dim rolelist As String() = Nothing
If Not [String].IsNullOrEmpty(rolesN) Then
rolelist = rolesN.Split(New Char() {","c, ";"c}, 512)
End If
roles = ArrayList.Adapter(rolelist)
Dim visible As Boolean = ReplaceNullRefs(reader, _indexvisible)
' Create a SiteMapNode
Dim node As New SiteMapNode(Me, id.ToString(), url, title, description, rolelist, _
Nothing, Nothing, Nothing)
' Record the node in the _nodes dictionary
_nodes.Add(id, node)
' Return the node
Return node
End Function
Private Function ReplaceNullRefs(ByVal rdr As SqlDataReader, ByVal rdrVal As Integer) As String
If Not (rdr.IsDBNull(rdrVal)) Then
Return rdr.GetString(rdrVal)
Else
Return String.Empty
End If
End Function
Private Function GetParentNodeFromDataReader(ByVal reader As DbDataReader) As SiteMapNode
' Make sure the parent ID is present
If reader.IsDBNull(_indexParent) Then
'**** Commented out throw, added exit function ****
Throw New ProviderException(_errmsg3)
'Exit Function
End If
' Get the parent ID from the DataReader
Dim pid As Integer = reader.GetInt32(_indexParent)
' Make sure the parent ID is valid
If Not _nodes.ContainsKey(pid) Then
Throw New ProviderException(_errmsg4)
End If
' Return the parent SiteMapNode
Return _nodes(pid)
End Function
Private Sub OnSiteMapChanged(ByVal key As String, ByVal item As Object, ByVal reason As CacheItemRemovedReason)
SyncLock _lock
If key = _cacheDependencyName AndAlso reason = CacheItemRemovedReason.DependencyChanged Then
' Refresh the site map
Clear()
_nodes.Clear()
_root = Nothing
End If
End SyncLock
End Sub
End Class
and I get this error:
*Özel Durum Ayrıntıları: System.IndexOutOfRangeException: visible
Kaynak Hatası:
Satır 154: _indexRoles = reader.GetOrdinal("Roles")
Satır 155: _indexParent = reader.GetOrdinal("Parent")
Satır 156: _indexvisible = reader.GetOrdinal("visible")
Satır 157:
Satır 158: If reader.Read() Then
Kaynak Dosya: D:\Websites\kaihl\App_Code\SqlSiteMapProvider.vb Satır: 156*
What I want is to tell sqlsitemapprovider to include an attribute within each sitemapnode called visible="true/false". Since this will be an extra attribute for sitemappath and menu (I think) this code would be doing the hiding job in menu not in breadcrumb (according to David Sussman's reply to a similar files .sitemap based thread as I linked above in my question):
Protected Sub Menu1_MenuItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles Menu1.MenuItemDataBound
Dim node As SiteMapNode = CType(e.Item.DataItem, SiteMapNode)
' check for the visible attribute and if false
' remove the node from the parent
' this allows nodes to appear in the SiteMapPath but not show on the menu
If Not String.IsNullOrEmpty(node("visible")) Then
Dim isVisible As Boolean
If Boolean.TryParse(node("visible"), isVisible) Then
If Not isVisible Then
e.Item.Parent.ChildItems.Remove(e.Item)
End If
End If
End If
End Sub
how to achieve this? thank you.
Update: I have found something very close at this page but still unable to deploy the solution.
Dim atts As NameValueCollection = Nothing
Dim attributeString As String = reader("attributes").ToString().Trim()
If Not String.IsNullOrEmpty(attributeString) Then
atts = New NameValueCollection()
Dim attributePairs() As String = attributeString.Split(";")
For Each attributePair As String In atts
Dim attributes() As String = attributePair.Split(":")
If attributes.Length = 2 Then
atts.Add(atts(0), attributes(1))
End If
Next
End If
Dim node As New SiteMapNode(Me, id.ToString(), url, title, description, rolelist, _
atts, Nothing, Nothing)
At last I have found a solution. And it is here. Thanks so much to Kadir ÖZGÜR, Sanjay UTTAM, David Sussman.
Checkout this link. he overides the IsAccessibleToUser property on the SiteMapprovider to selectivly show nodes based on the role of the current user. you caould change the condiftion to suit your needs.