Getting error “Some or all identity references could not be translated
Getting error in 8th line
Dim FolderPath As String = "D:\Account\HA\" 'Specify the folder here
Dim UserAccount As String = mailid.ToString() & "\" & pwd
Dim objDirectoryInfo As DirectoryInfo = Nothing
Dim objDirectorySecurity As DirectorySecurity = Nothing
Dim objRule As FileSystemAccessRule = Nothing
objDirectoryInfo = New DirectoryInfo(FolderPath)
objDirectorySecurity = objDirectoryInfo.GetAccessControl
objRule = New FileSystemAccessRule(UserAccount, FileSystemRights.ReadPermissions, AccessControlType.Allow)
objDirectorySecurity.AddAccessRule(objRule)
objDirectoryInfo.SetAccessControl(objDirectorySecurity)
Try these changes I have made up for you...
Public Sub AddDirectorySecurity(ByVal FolderPath As String, ByVal Account As String, ByVal Rights As FileSystemRights, ByVal ControlType As AccessControlType)
' Create a new DirectoryInfoobject.
Dim objDirectoryInfo As New DirectoryInfo(FolderPath)
' Get a DirectorySecurity object that represents the current security settings.
Dim objDirectorySecurity As DirectorySecurity = objDirectoryInfo.GetAccessControl()
' Add the FileSystemAccessRule to the security settings.
objDirectorySecurity .AddAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))
' Set the new access settings.
objDirectoryInfo .SetAccessControl(dSecurity)
End Sub
Give this a shot and let me know how it works out for you?
Thanks!
Related
I'm trying to get the full path minus the filename from a path in vb.net. I'm using a textbox and a browse button to get the full path, but I want to save just the directories.
How do I get just the directories and sub-directories?
Example file name:
c:\Users\jsmith\Desktop\file.aspx
Desired result:
c:\Users\jsmith\Desktop\
Protected Sub btnBackupFolderName_Click(sender As Object, e As EventArgs) Handles btnBackupFolderName.Click
' Call ShowDialog.
Dim result As DialogResult = openFD.ShowDialog()
' Test result.
If result = Windows.Forms.DialogResult.OK Then
Dim FileNameText As String = openFD.FileName.ToString()
Dim backupFolderName = Path.GetFileName(Path.GetDirectoryName(FileNameText)) 'this just gives me 'Desktop'
txtBackupFolder.Text = di.ToString 'backupFolderName
End If
End Sub
Thank you for your help!
Get the full path of the file and then use GetDirectoryName() to retrieve the folder-path, like this:
Dim openFD As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = openFD.ShowDialog()
If result = DialogResult.OK Then
Dim FileNameText As String = openFD.FileName.ToString()
' This gets the folder-path, sans filename.
txtBackupFolder.Text = Path.GetDirectoryName(openFD.FileName)
End If
I'm trying to set up my program to connect to my FTP and download files directly from my server. This what I have so far. I don't know what I'm doing wrong, or where I'm going wrong, because no matter how I code it either says "End Expected" or "Method can't handle etc due to signatures not being compatible"
I don't know what I'm doing wrong, any help would be greatly appreciated.
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
(ByVal downloadpath As String, ByVal ftpuri As String, ByVal ftpusername As String, ByVal ftppassword As String)
'Create a WebClient.
Dim request As New WebClient()
' Confirm the Network credentials based on the user name and password passed in.
request.Credentials = New Net.NetworkCredential("Username", "Password")
'Read the file data into a Byte array
Dim bytes() As Byte = request.DownloadData("ftp://ftp.yourwebsitename/file.extension")
Try
' Create a FileStream to read the file into
Dim DownloadStream As FileStream = IO.File.Create("C:\Local\Test.zip")
' Stream this data into the file
DownloadStream.Write(bytes, 0, bytes.Length)
' Close the FileStream
DownloadStream.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
MessageBox.Show("Process Complete")
End Sub
You probably pasted an existing method inside a Button.Click handler by mistake.
Rebuilding what was probably the original method is almost enough.
Note that this FTP procedure is a quite basic. You can rely on it only when downloading from a known remote resource. Also, as it it, it doesn't allow to show the download progress or even to cancel it.
Maybe take a look at the WebClient.DownloadDataAsync method, which allows to easily implement a progress bar and cancel the download procedure, when needed.
Also, if you're interested, in this SO question, you can find some notes and a sample Form, which can be included in a Project, to test some features of the FtpWebRequest.
Private Sub Button16_Click(sender As Object, e As EventArgs) Handles Button16.Click
Button16.Enabled = False
DownloadFile("C:\Local\Test.zip", "ftp://ftp.example.com/file.ext", "[username]", "[password]")
Button16.Enabled = True
End Sub
Private Sub DownloadFile(destinationPath As String, ftpResource As String, ftpUsername As String, ftpPassword As String)
Dim client As New WebClient()
client.Credentials = New NetworkCredential(ftpUsername, ftpPassword)
Try
Dim dataBytes() As Byte = client.DownloadData(ftpResource)
If dataBytes.Length > 0 Then
File.WriteAllBytes(destinationPath, dataBytes)
MessageBox.Show("Download Complete")
Else
MessageBox.Show("Download failed")
End If
Catch ex As WebException
MessageBox.Show(ex.Message)
Catch ex As IoException
MessageBox.Show(ex.Message)
End Try
End Sub
Here is a Console solution. Compile this into a exe file, and run it by double-clicking the executable or get a scheduler (i.e., Windos Task Scheduler) to open and run the file (it runs as soon as it opens).
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Linq
Imports System.Text
Imports System.Net
Imports System.IO
Namespace ConsoleApplication1
Class Program
Private Shared Sub Main(ParamArray ByVal args() As String)
If args.Any Then
' Do code that references args
Dim dt As DateTime = DateTime.Today.AddDays(-1)
Dim date As String = String.Format("{0:yyyyMMdd}", dt)
Dim p As Program = New Program
p.getFTPFile(("raw_CA_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_EM_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_GLB_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_US_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
Else
' Do code that depends on no input arguments.
Dim dt As DateTime = DateTime.Today.AddDays(-1)
Dim date As String = String.Format("{0:yyyyMMdd}", dt)
Dim p As Program = New Program
p.getFTPFile(("raw_CA_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_EM_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_GLB_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
p.getFTPFile(("raw_US_" _
+ (date + ".txt")))
' match a certain pattern in the name of the file
End If
End Sub
Private Sub getFTPFile(ByVal FTPFile As String)
FTPSettings.IP = "000.000.100.000"
FTPSettings.UserID = "your_id"
FTPSettings.Password = "your_password"
Dim reqFTP As FtpWebRequest = Nothing
Dim ftpStream As Stream = Nothing
Try
Dim outputStream As FileStream = New FileStream(("C:\Downloads\AFL_Files\" + FTPFile), FileMode.Create)
reqFTP = CType(FtpWebRequest.Create(("ftp://something#ftp.corp.com/your_path/" + FTPFile)),FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = true
reqFTP.Credentials = New NetworkCredential(FTPSettings.UserID, FTPSettings.Password)
Dim response As FtpWebResponse = CType(reqFTP.GetResponse,FtpWebResponse)
ftpStream = response.GetResponseStream
Dim cl As Long = response.ContentLength
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer() As Byte = New Byte((bufferSize) - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While (readCount > 0)
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
ftpStream.Close
outputStream.Close
response.Close
Catch ex As Exception
If (Not (ftpStream) Is Nothing) Then
ftpStream.Close
ftpStream.Dispose
End If
Throw New Exception(ex.Message.ToString)
End Try
End Sub
Public Class FTPSettings
Public Shared Property IP As String
Get
End Get
Set
End Set
End Property
Public Shared Property UserID As String
Get
End Get
Set
End Set
End Property
Public Shared Property Password As String
Get
End Get
Set
End Set
End Property
End Class
End Class
End Namespace
I'm trying to send an activation email and have the user activate their account by clicking on the link provided. I have been tweaking it based on open source code I've been looking at online, however it has recently stopped sending the email without giving any errors. Here is the sign up form with the send email function:
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports System.Data
Imports System.Configuration
Imports System.Net.Mail
Imports System.Net
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Public Class WebForm1
Inherits System.Web.UI.Page
Dim boolCar As Object
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If txtEmailAddress.Text.Trim.EndsWith("#umary.edu") Or txtPassword.Text.Trim = txtRetypePassword.Text.Trim Then
Dim con As New SqlConnection
Dim cmdEmail As New SqlCommand
Dim cmdRegistration As New SqlCommand
Dim EmailCount As Integer = 0
Try
con.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
con.Open()
cmdEmail = New SqlCommand("SELECT COUNT(UMaryEmail) As EmailCount FROM RegisteredUsers WHERE UMaryEmail='" & txtEmailAddress.Text.Trim & "'", con)
EmailCount = cmdEmail.ExecuteScalar()
If EmailCount = 0 Then
' Declare database input variables
Dim userId As Integer = 0
Dim firstName As String = txtFirstName.Text
Dim lastName As String = txtLastName.Text
Dim hometown1 As String = txtHometown1.Text
Dim state1 As String = txtState1.Text
Dim zip1 As String = txtZipCode1.Text
Dim hometown2 As String = txtHometown2.Text
Dim state2 As String = txtState2.Text
Dim zip2 As String = txtZipCode2.Text
Dim phoneNum As String = txtPhoneNumber.Text
Dim emailAddress As String = txtEmailAddress.Text
Dim password As String = txtPassword.Text
Dim boolCar As Boolean = False
Dim boolUmary As Boolean = False
If radYesNo.SelectedIndex = 0 Then
boolCar = True
Else
boolCar = False
End If
' Define the command using parameterized query
cmdRegistration = New SqlCommand("INSERT INTO RegisteredUsers(FirstName, LastName, Hometown1, State1, ZIP1, Hometown2, State2, ZIP2, PhoneNum, UMaryEmail, Password, Car) VALUES (#txtFirstName, #txtLastName, #txtHometown1, #txtState1, #txtZipCode1, #txtHometown2, #txtState2, #txtZipCode2, #txtPhoneNumber, #txtEmailAddress, #txtPassword, #RadYesNo)", con)
' Define the SQL parameter '
cmdRegistration.Parameters.AddWithValue("#txtFirstName", txtFirstName.Text)
cmdRegistration.Parameters.AddWithValue("#txtLastName", txtLastName.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown1", txtHometown1.Text)
cmdRegistration.Parameters.AddWithValue("#txtState1", txtState1.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode1", txtZipCode1.Text)
cmdRegistration.Parameters.AddWithValue("#txtHometown2", txtHometown2.Text)
cmdRegistration.Parameters.AddWithValue("#txtState2", txtState2.Text)
cmdRegistration.Parameters.AddWithValue("#txtZipCode2", txtZipCode2.Text)
cmdRegistration.Parameters.AddWithValue("#txtPhoneNumber", txtPhoneNumber.Text)
cmdRegistration.Parameters.AddWithValue("#txtEmailAddress", txtEmailAddress.Text)
cmdRegistration.Parameters.AddWithValue("#txtPassword", txtPassword.Text)
cmdRegistration.Parameters.AddWithValue("#RadYesNo", boolCar)
cmdRegistration.ExecuteNonQuery()
SendActivationEmail(userId)
Response.Redirect("RegistrationSuccess.aspx")
Else
' Duplicate Email Exist Error Message
MsgBox("Email address already supplied.")
End If
' Catch ex As Exception (Not needed)
' Error Executing One Of The SQL Statements
Finally
con.close()
End Try
Else
' Throw Error Message
MsgBox("Email input error")
End If
End Sub
Private Sub SendActivationEmail(userId As Integer)
Dim sqlString As String = "Server=SERVERNAME;Database=StudentGov;UId=sa;Password=Password1;"
Dim ActivationCode As String = Guid.NewGuid().ToString()
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
Using con As New SqlConnection(sqlString)
Using sqlCmd As New SqlCommand("UPDATE RegisteredUsers SET UserId = '" + userId.ToString + "', ActivationCode = '" + ActivationCode.ToString + "' WHERE UMaryEmail='" + txtEmailAddress.Text + "';")
Using sda As New SqlDataAdapter()
sqlCmd.CommandType = CommandType.Text
sqlCmd.Parameters.AddWithValue("#UserId", userId)
sqlCmd.Parameters.AddWithValue("#ActivationCode", ActivationCode)
sqlCmd.Connection = con
con.Open()
sqlCmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
Using mm As New MailMessage("****#outlook.com", txtEmailAddress.Text)
mm.Subject = "Account Activation"
Dim body As String = "Hello " + txtFirstName.Text.Trim() + ","
body += "<br /><br />Please click the following link to activate your account"
body += "<br /><a href='" & ActivationUrl & "'>Click here to activate your account.</a>"
body += "<br /><br />Thanks"
mm.Body = body
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "smtp.live.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential("****#outlook.com", "****")
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
Try
smtp.Send(mm)
Catch ex As Exception
MsgBox("Email was not sent")
End Try
End Using
End Sub
Private Function FetchUserId(emailAddress As String) As String
Dim cmd As New SqlCommand()
Dim con As New SqlConnection("Data Source=SERVERNAME;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
cmd = New SqlCommand("SELECT UserId FROM RegisteredUsers WHERE UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#txtEmailAddress", emailAddress)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim userId As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return userId
End Function
End Class
And here is the AccountActivation page:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class ActivateAccount
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ActivateMyAccount()
End If
End Sub
Private Sub ActivateMyAccount()
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con.ConnectionString = "Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1"
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail"))) Then
'approve account by setting Is_Approved to 1 i.e. True in the sql server table
cmd = New SqlCommand("UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress", con)
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("UMaryEmail"))
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
con.Close()
cmd.Dispose()
End Try
End Sub
End Class
As you may be able to tell already, I am flummoxed. With no error messages I'm receiving, I don't know why the SendActivationEmail function is no longer working. Someone help please! :(
Hi FlummoxedUser are you sure that have you checked your code as well ????
Take a look here :
Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
I think is better use httputility.urlEncode/Decode for this stuff where it use it to filter only the result of each function or single variable.
Second one take care at your code above
this is in your page :
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("UMaryEmail")))
where have you found "UmaryEmail" key in your querystring parameters?????
Check it and you will solve your issue but check also in cmd and so on in activation page or you will make some issues :)
I hope it help you and if it solves your issue mark this as answer.
UPDATE :
> Dim ActivationUrl As String = Server.HtmlEncode("http://localhost:63774/ActivateAccount.aspx?userId=" & FetchUserId(txtEmailAddress.ToString) & "&txtEmailAddress=" & txtEmailAddress.ToString & "&ActivationCode=" & ActivationCode.ToString)
with this task you create yout activation link which will be something like
http://localhost:63774/ActivateAccount.aspx?userId=1&txtEmailAddress=email#pippo&ActivationCode=123456
Now what's append when click on that link server handle request and create a collection data which include all the keys within your querystring
In effect you can use request.QueryString to check/retrieve values from each keys. So you can use as you did request.Querystring("keyname") to get the value for that particular parameter BUT in your case you check for a key which are not passed into the link. Pay attention that you have setup only 3 keys which are
UserID
txtEmailAddress
ActivationCode
there's no "UMaryEmail" key in request query string
Also another important stuff NEVER PASS IN QUERY STRING DATABASE FIELD :) use fantasy name or shortname which not reflect database field
example :
UserID => uid
ActivatioCode = token,acd,cd or anything you want
txtEmailAddress= email, em or any other name
Now activation page issue when you try to check your value use an if statement where check for userid key and UMaryEmail where userid could be matched coz it exist in query string but UmaryEmail is not into the request.querystring you have not provided it so if fails and nothing has been shown in page.
Here your Activation Sub revisited with some comments to better understand :
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("Userid") AndAlso Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("UserId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
.Parameters.AddWithValue("#UserId", Request.QueryString("UserId"))
.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
Else
Response.Write("<h1>invalid activation links!!</h1>")
End If
End Sub
If your query is right it should work at first shot :)
Take a try and let me know and if it solve your issue please mark it as answer
UPDATE 2:
Your actual code is :
Dim ActivationUrl As String = Server.HtmlEncode("localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.ToString)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.ToString) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
But is all wrong let me explain:
Declar your variable : Dim ActivationUrl as string it is ok
Then built url so :
="http://localhost:63774/ActivateAccount.aspx?userId=" & HttpUtility.UrlEncode(FetchUserId(txtEmailAddress.text.tostring)) & "&txtEmailAddress=" & HttpUtility.UrlEncode(txtEmailAddress.text.tostring) & "&ActivationCode=" & HttpUtility.UrlEncode(ActivationCode.ToString))
Where take a look to piece of code which is your : 'HttpUtility.UrlEncode(txtEmailAddress.ToString)' in this manner you are passing a value system type object which is a textbox to pass textbox value you need to access to its .Text property like txtEmailAddress .Text
Change as per my code above and it will work (if your procedure is right)
**UPDATE CODE 3 **
Change your code with this.§be carefull don't change anything copy and paste all ActivateMyAccount Sub and delete your old one
Private Sub ActivateMyAccount()
'Checking you keys in querystring
If Request.QueryString.AllKeys.Contains("userId") And Request.QueryString.AllKeys.Contains("txtEmailAddress") Then
'here we assume that keys exist and so we can proceed with rest
If (Not String.IsNullOrEmpty(Request.QueryString("userId"))) And (Not String.IsNullOrEmpty(Request.QueryString("txtEmailAddress"))) Then
'no we can proceed to make other stuff
'Another stuff place you connection string within connection string section in webconfig in order to make a simple request like this one :
'classic example for create a connection with web config file
' Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("yourconnectionstringname").ToString)
Using con As New SqlConnection("Data Source=CISWEB\UMCISSQL2008;Initial Catalog=StudentGov;User ID=sa;Password=Password1")
If con.State = ConnectionState.Closed Then con.Open()
Dim sqlQuery As String = "UPDATE RegisteredUsers SET AccountActivated=1 WHERE UserId=#UserId AND UMaryEmail=#txtEmailAddress"
Using cmd As New SqlCommand(sqlQuery, con)
Try
With cmd
cmd.Parameters.AddWithValue("#UserId", Request.QueryString("userId"))
cmd.Parameters.AddWithValue("#txtEmailAddress", Request.QueryString("txtEmailAddress"))
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='SignIn.aspx'>Sign in</a> now! ")
End With
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('We apologize but something is gone wrong;our techs are checking the issue.Best regards etc etc etc');", True)
End Try
End Using
End Using
Else
Response.Write("<h1>invalid activation links!! bad query string</h1>")
End If
Else
Response.Write("<h1>invalid activation links!! bad not string</h1>")
End If
End Sub
i want to read the metadata (such as author, keywords, etc.) of the Word, Excel file by asp.net (vb). How can I do that ?
is there any sample, reference site ?
i found the following code online, but it return error for the 2nd statement (" Dim excelbook As New Microsoft.Office.Interop.Excel.Workbook ")
Public Sub ReadExcel(ExcelFileName As String)
Dim Wapp As New Microsoft.Office.Interop.Excel.Application
Dim excelbook As New Microsoft.Office.Interop.Excel.Workbook
If Wapp Is Nothing Then
Wapp = New Microsoft.Office.Interop.Excel.Application
End If
If excelbook Is Nothing Then
excelbook = New Microsoft.Office.Interop.Excel.Workbook
Else
excelbook.Close()
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
here is the example for the same. Or you can download from https://dl.dropbox.com/u/79986486/StackOverFlow9684368.zip {Temporary}
You can use openXML with C# or VB.Net to achive this.
Hope this helps.
Quoting from Social.MSDN
You can access the values using DSOFile (works for a whole bunch of different fileTypes), or more simply, you can access these properties like this in VBA
Sub Macro1()
'
' Macro1 Macro
'
Dim mWorkbook As Workbook
Set mWorkbook = Application.Workbooks(1)
mWorkbook.BuiltinDocumentProperties("Author").Value = "the Author"
mWorkbook.BuiltinDocumentProperties("Title").Value = "the Title"
mWorkbook.BuiltinDocumentProperties("Subject").Value = "the Subject"
End Sub
I have a problem with FileUpload, when I select a file from the local machine, it will not bring the real path of the file, it will use the path for the project files and assume the file I am selecting is there, any ideas?
Example:
File name is "Q.JPG" and is in "C:\"
when I browse to "C:\" and select "Q.JPG" and click open, I get the following Error
Could not find file 'C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\q.jpg'.
So when I fire up the code for Uploading the file to FTP for example, it will return an error because file doesn't exist
HTML side:
<asp:FileUpload ID="FU" runat="server" Height="24px" />
Below is the VB code:
Protected Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
If FU.PostedFile IsNot Nothing AndAlso FU.PostedFile.FileName <> "" Then
Dim MaxSize As Integer = FU.PostedFile.ContentLength
If MaxSize > "2097152" Then
lblUpload.Text = "The file size cannot exceed 2 MB"
btnSave.Focus()
GoTo 99
End If
'--------------------------
' set up request...
Dim LocFile As String = FU.PostedFile.FileName
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://myftp.com/" & LocFile), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("username", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes(FU.PostedFile.FileName)
' upload file...
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()
'--------------------------
lblUpload.Text = "Uploaded"
btnSave.Focus()
Else
lblUpload.Text = "Choose a file to upload"
btnSave.Focus()
End If
99: 'Do Nothing
End Sub
The problem is you're trying to read in the PostedFile as a local file (on the web server), not from the HttpPostedFile object attached to the FileUploader.
Try:
Dim objFileStream As System.IO.Stream = FU.PostedFile.InputStream
Dim bFile(objFileStream.Length) As Byte
objFileStream.Read(bFile, 0, objFileStream.Length)
I tried something, and it worked..
FU.SaveAs("C:\" & FU.FileName)
'--------------------------
' set up request...
Dim LocFile As String = FU.PostedFile.FileName
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("MyFTP.com" & LocFile), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("username", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
It worked.. simply saved the file from FU (FileUpload) to C:\ and then setting the address to always start at C:\