Basically I was just playing around with the provided sample of the Protect data and how you can encrypt your text file and what not. I managed to do a bit of modification and this is what i have soo far:
Below is my XAML
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Secure DATA" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Encrypt" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Margin="12,0,12,0" Height="768" VerticalAlignment="Top">
<TextBlock Margin="10,333,22,405" >
<Run Text="Enter your "/>
<Run Text="ACCOUNT PASSWORD:"/>
</TextBlock>
<TextBox x:Name="TBPin" Height="75" Width="444" HorizontalAlignment="Left" Margin="0,355,0,338" InputScope="Number" />
<Button x:Name="BtnStore" Content="Save" Click="BtnStore_Click" Margin="0,585,222,103" FontSize="21.333" FontFamily="Segoe WP SemiLight" RenderTransformOrigin="0.495,0.481" />
<Button x:Name="BtnRetrieve" Content="Load" Click="BtnRetrieve_Click" Margin="221,585,12,103" FontSize="21.333" FontFamily="Segoe WP SemiLight" />
<TextBlock Margin="10,157,22,580" >
<Run Text="Enter your "/>
<Run Text="ACCOUNT NAME"/>
<Run Text=":"/>
</TextBlock>
<TextBox x:Name="AccName" Width="444" HorizontalAlignment="Left" Margin="0,177,0,516" Height="75" InputScope="Chat" Text="LoL" />
<TextBlock Margin="10,244,22,494" >
<Run Text="Enter your "/>
<Run Text="ACCOUNT USERNAME:"/>
</TextBlock>
<TextBox x:Name="AccUser" Height="75" Width="444" HorizontalAlignment="Left" Margin="0,266,0,427" />
<TextBlock Margin="10,423,22,315" Text="Notes about this account:" />
<TextBox x:Name="AccNotes" Width="444" HorizontalAlignment="Left" Margin="0,445,0,170" InputScope="Chat" />
</Grid>
</Grid>
Below is the Code
Imports System
Imports System.Threading
Imports System.Windows.Controls
Imports Microsoft.Phone.Controls
Imports Microsoft.Phone.Shell
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Text
Imports System.Security.Cryptography
Partial Public Class MainPage
Inherits PhoneApplicationPage
Private FilePath As String = "Pinfile"
Public Sub New()
InitializeComponent()
SupportedOrientations = SupportedPageOrientation.Portrait Or SupportedPageOrientation.Landscape
End Sub
Private Sub WritePinToFile(pinData As Byte())
' Create a file in the application's isolated storage.
Dim file As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim writestream As New IsolatedStorageFileStream(AccName.Text, System.IO.FileMode.Create, System.IO.FileAccess.Write, file)
' Write pinData to the file.
Dim writer As Stream = New StreamWriter(writestream).BaseStream
writer.Write(pinData, 0, pinData.Length)
writer.Close()
writestream.Close()
End Sub
Private Function ReadPinFromFile() As Byte()
' Access the file in the application's isolated storage.
Dim file As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Dim readstream As New IsolatedStorageFileStream(AccName.Text, System.IO.FileMode.Open, FileAccess.Read, file)
' Read the PIN from the file.
Dim reader As Stream = New StreamReader(readstream).BaseStream
Dim pinArray As Byte() = New Byte(reader.Length - 1) {}
reader.Read(pinArray, 0, pinArray.Length)
reader.Close()
readstream.Close()
Return pinArray
End Function
Private Sub BtnStore_Click(sender As Object, e As RoutedEventArgs)
' Convert the PIN to a byte[].
Dim PinByte As Byte() = Encoding.UTF8.GetBytes(AccName.Text & vbNewLine & AccUser.Text & vbNewLine & TBPin.Text & vbNewLine & AccNotes.Text)
' Encrypt the PIN by using the Protect() method.
Dim ProtectedPinByte As Byte() = ProtectedData.Protect(PinByte, Nothing)
' Store the encrypted PIN in isolated storage.
Me.WritePinToFile(ProtectedPinByte)
TBPin.Text = ""
End Sub
Private Sub BtnRetrieve_Click(sender As Object, e As RoutedEventArgs)
' Retrieve the PIN from isolated storage.
Dim ProtectedPinByte As Byte() = Me.ReadPinFromFile()
' Decrypt the PIN by using the Unprotect method.
Dim PinByte As Byte() = ProtectedData.Unprotect(ProtectedPinByte, Nothing)
' Convert the PIN from byte to string and display it in the text box.
AccName.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length)
AccUser.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length)
TBPin.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length)
AccNotes.Text = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length)
End Sub
End Class
Soo far I click store and it stores and when I want to load i just type the name i saved the information with and it loads. The problem I'm having is that once i click Load it loads everything in that one textfile into every other textbox. This picture will illustrate my point better: http://puu.sh/5T4mc.png
As you can see it loads everything in one textbox for each and every textbox there is. What I want to do is e.g. For the Username textbox I want the first line only to show, Password textbox I want the 3rd line of that textfile only to show. How can i achieve this?
If possible VB code would be good but C# would also be fine. I could just convert it.
Thanks
Once you get the string, just use Split to retrieve each line, then assign them to the textbox you want. In C# it would be:
var PinByte = ProtectedData.Unprotect(ProtectedPinByte, null);
var content = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length);
var lines = content.Split('\n');
AccName.Text = lines[0]; // Take the first line
TBPin.Text = lines[2]; // Take the third line
// and so on
My VB is rusted, but I believe it would be something like:
Dim ProtectedPinByte As Byte() = Me.ReadPinFromFile()
Dim PinByte As Byte() = ProtectedData.Unprotect(ProtectedPinByte, Nothing)
Dim content As String = Encoding.UTF8.GetString(PinByte, 0, PinByte.Length)
Dim lines As String() = content.Split(vbLf)
AccName.Text = lines(0)
TBPin.Text = lines(2)
Related
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim con As New SqlConnection
Dim img As New Image
con.ConnectionString = ("Initial Catalog=test; Data Source=LAPTOP-DJ6MPGR2\ROOT123;User ID=SA;Password=root;Integrated Security=False;MultipleActiveResultSets=True")
con.Open()
Dim cmd As New SqlCommand("select image from Images ", con)
cmd.Connection = con
Dim dr As SqlDataReader = cmd.ExecuteReader()
If (dr.HasRows) Then
While (dr.Read)
Dim bytes As Byte() = DirectCast(dr("image"), Byte())
Image1.ImageUrl = Convert.ToBase64String(bytes)
End While
End If
con.Close()
End Sub
The following will show how to both upload an image to a SQL Server database as well as how to retrieve and image from the database and display it on an ASP.NET web page.
Create a table in the database:
Create Table Images(Id int IDENTITY(1, 1) Not null,
Image varbinary(max),
Constraint PK_Images_Id PRIMARY KEY(Id));
The SQL Server 'sa' user really shouldn't be used to access the database as this creates a security issue. Instead create a user for your application.
Create a Database User
Open Microsoft SQL Server Management Studio
Expand Security
Right-click Logins
Select New Login
Select SQL Server authentication
Login name: <desired login name> (ex: appUser)
Enter your desired password
Uncheck "User must change password at next login"
Select the desired default database (ex: testDR)
Click OK
Add User to Database
Open Microsoft SQL Server Management Studio
Expand Databases
Expand <desired database> (ex: testDR)
Expand Security
Right-click Users
Select New User...
Enter desired user name (ex: appUser)
For "Login name", Click ...
Click Browse
Select desired user (ex: appUser)
Click OK
Click OK
Leave "Default schema", blank.
Click OK
Grant User Permissions on Table
Open Microsoft SQL Server Management Studio
Expand Databases
Expand <desired database> (ex: testDR)
Expand Tables
Right-click <desired table> (ex: dbo.Images)
Select Properties
Under "Select a page", click Permissions
Click Search
Click Browse
Check desired user (ex: appUser)
Click OK
Click OK
Under Grant, check the following: Delete, Insert, Select, Update
Click OK
Note: "With Grant" allows the user to grant the permissions to another user.
VS 2019:
Create a new project
Open Visual Studio
Click Continue without code
Click File
Select New
Select Project
Select the following:
Click Next
Select the following:
Click Next
Enter desired project name
Click Create
Select the following:
Under Advanced, uncheck Configure for HTTPS
Click Create
Open Solution Explorer
In VS menu, click View
Select Solution Explorer
Add WebForm (name: default.aspx)
In Solution Explorer, right-click <project name>
Select Add
Select New Item...
Select Web Form (name: default.aspx)
Click Add
Add WebForm (name: DisplayImage.aspx)
In Solution Explorer, right-click <project name>
Select Add
Select New Item...
Select Web Form (name: DisplayImage.aspx)
Click Add
Add connection string to Web.config
In Solution Explorer, double-click Web.config
In code below, modify the code within <connectionStrings>...</connectionStrings> for your environment (ie: server, database name, user name, password).
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="testDRConnection" connectionString="Server=.\SQLExpress;Database=testDR;User Id=appUser;Password=myAppPassword;" />
</connectionStrings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
In "default.aspx" we'll add the ability to upload a file to the database. When the upload is complete, we'll use "Display.aspx" to display the last uploaded image.
In Solution Explorer, double-click default.aspx.
default.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="DatabaseGetImage.UploadImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="frmDefault" runat="server">
<div>
<asp:Label ID="LabelFileUpload" for="FileUpload1" runat="server" Text="Label">Upload a File</asp:Label>
<p />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="ButtonUploadFile" runat="server" Text="Upload" OnClick="ButtonUploadFile_Click" />
<p />
<asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
Below is the code that uploads an image to the database.
In Solution Explorer, right-click default.aspx. Select View Code
default.aspx.vb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class UploadImage
Inherits System.Web.UI.Page
'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Function UploadImage(imageBytes As Byte()) As Integer
Dim rowsAffected As Integer = 0
Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
Dim sqlText As String = "INSERT INTO Images(Image) VALUES(#img);"
Using con As SqlConnection = New SqlConnection(connectionStr)
'open
con.Open()
Using cmd As SqlCommand = New SqlCommand(sqlText, con)
'size = -1 is needed to exceed 8000 bytes; it maps to varbinary(max)
cmd.Parameters.Add("#img", SqlDbType.VarBinary, -1).Value = imageBytes
'execute
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
Return rowsAffected
End Function
Protected Sub ButtonUploadFile_Click(sender As Object, e As EventArgs)
If FileUpload1.HasFile() Then
LblMsg.Text = "Filename: " & FileUpload1.FileName & " File bytes: " & FileUpload1.FileBytes.Length
'upload image to database
Dim rowsAffected As Integer = UploadImage(DirectCast(FileUpload1.FileBytes, Byte()))
Response.Redirect("DisplayImage.aspx")
End If
End Sub
End Class
Next, we'll modify "DisplayImage.aspx" so that it will display an image.
In Solution Explorer, double-click DisplayImage.aspx
DisplayImage.aspx
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="DisplayImage.aspx.vb" Inherits="DatabaseGetImage.displayImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
<asp:Image ID="Image1" runat="server" ></asp:Image>
<p />
<asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
</div>
</body>
</html>
The code below retrieves an image from the database and displays it.
In Solution Explorer, right-click DisplayImage.aspx. Select View Code
DisplayImage.aspx.vb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class displayImage
Inherits System.Web.UI.Page
'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim imagesBytes As Byte() = GetImage(id:=1) 'get image with id = 1
If imagesBytes IsNot Nothing Then
'LblMsg.Text = "Base64 String: " & Convert.ToBase64String(imagesBytes)
Image1.ImageUrl = "data:image/jpeg;base64," & Convert.ToBase64String(imagesBytes)
End If
End Sub
Protected Function GetImage(id As Integer) As Byte()
Dim imageBytes As Byte() = Nothing
Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
Dim sqlText As String = "SELECT * from Images where Id = (SELECT max(Id) from Images)"
Try
Using con As SqlConnection = New SqlConnection(connectionStr)
con.Open() 'open
Using cmd As SqlCommand = New SqlCommand(sqlText, con)
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
Using dr As SqlDataReader = cmd.ExecuteReader()
If dr.HasRows Then
While dr.Read()
imageBytes = DirectCast(dr("image"), Byte())
End While
End If
End Using
End Using
End Using
Catch ex As SqlException
'ToDo: add desired code
LblMsg.Text = "Error: " & ex.Message
'Throw
Catch ex As Exception
'ToDo: add desired code
LblMsg.Text = "Error: " & ex.Message
'Throw
End Try
Return imageBytes
End Function
End Class
Resources:
Store Connection String in Web.config
SQL Server Connection Strings
How to display Base64 images in HTML
I have this code to load image from MySql database to picturebox. But it takes about 4-5seconds to load the image.
' this code if for SAVING IMAGE to MySQL database.
Public Function ConvertToBytes(ByVal img As PictureBox) As Byte()
Dim msPic As New MemoryStream
img.Image.Save(msPic, System.Drawing.Imaging.ImageFormat.Bmp)
Dim Mybyte() As Byte = msPic.GetBuffer
Return Mybyte
End Function
' this code if for RETRIEVING IMAGE FROM MySQL database.
sql_connection = New MySqlClient.MySqlConnection(conn.connect)
sql_connection.Open()
Dim arrImage() As Byte
sql_command = New MySqlClient.MySqlCommand("SELECT * FROM tblCatalog WHERE IDCardNo = '" & TEXTBOX1.Text & "'", sql_connection)
sql_command.CommandTimeout = 1000
sql_reader = sql_command.ExecuteReader()
While (sql_reader.Read())
arrImage = sql_reader("Picture")
Dim mstream As New System.IO.MemoryStream(arrImage)
PictureBox3.Refresh()
PictureBox3.Image = Image.FromStream(mstream)
End While
sql_reader.Close()
I place my code into the Timer_tick, I also tried at the button event. But still the result is just the same. Can somebody help me?. I want that when I press enter or click the button, it quickly load the image.
Form button:
<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" />
Code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
What is a simple code to insert a value (generated id) into SQL Server database? When Button1_Click is triggered, generated id should be inserted to tbl_batch.
Should I add anything to web.config (like db connection)?
Using con As SqlConnection = New SqlConnection("Server=localhost\SQLEXPRESS; Database=databasename; User Id=sa; Password=yourpassword;")
Using cmd As SqlCommand = con.CreateCommand()
Using da As New SqlDataAdapter
con.Open()
cmd.CommandText = "insert into ..."
da.SelectCommand = cmd
Dim dt As New DataTable
da.Fill(dt)
End Using
End Using
End Using
You cannot do CRUD operation in web.config file but I have one simple solution for you using SqlDataSource. Follow up below steps and make your stuff happen, just in simple way.
Connection String In my Web.config:
<add name="Conn" connectionString="Server=David-PC;Database=DNN711;uid=sa;pwd=sa123;" providerName="System.Data.SqlClient"/>
ASPX Markup:
<asp:Button ID="Button1" runat="server" Text="GO" onclick="Button1_Click" />
<asp:SqlDataSource ID="sdsInsert" runat="server"
ConnectionString="<%$ ConnectionStrings:Conn %>"
InsertCommand="Insert into tbl_batch (GeneratedID) values (#GeneratedID)"
InsertCommandType="Text"></asp:SqlDataSource>
Button Click Event:
protected void Button1_Click(object sender, EventArgs e)
{
sdsInsert.InsertParameters.Add("GeneratedID", "123");
sdsInsert.Insert();
}
Please let me know if you have any questions.
I'm attempting to write a page to upload a logo onto a SQL database. However, I keep getting access denied errors. When I run the procedure, the following exception is thrown:
System.UnauthorizedAccessException: Access to the path 'C:\Users\ANDY\Pictures\Logo.PNG' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at _Default.SaveToDB(String info) in...
The file: 'C:\Users\ANDY\Pictures\Logo.PNG' is on my client (not the server) and if I grant everyone full control permissions to the file, then it uploads to the remote server successfully.
I cant ask my users to change their permissions to upload files.
during my testing I have tried it on 2 computers:
+My development computer:
-in debug mode in visual studio, it works great
-on the same computer, if I load it into IIS it throws an the exception above requiring permissions to be granted to the local file or folder that I am trying to upload.
+My Production Server:
-The same files uploaded to the production server produce a slightly different error. This time it wants permissions to modify this path on the server: c:\Windows\System32\inetsrv I thought I'd try granting access to this folder to the NetworkService account, however, it appears that this is a protected folder and you cannot modify permissions to folders under System32. you also cannot add the NetworkService account to local Administrators (I know, I know - bad security - but I'm just troubleshooting here).
IIS 6 with SQL server 2008 R2 is hosting the site.
Web page code is as follows:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="TestImageUpload.aspx.vb" Inherits="_Default" MasterPageFile="MasterPage.master"%>
<%# Register Src="sideMenuControl.ascx" TagName="sideMenuControl" TagPrefix="uc1" %>
<asp:Content ID="contentHolder" ContentPlaceHolderID="ContentPlaceHolder" runat="Server">
<div id="mainContent">
<div id="sidecol">
<uc1:sideMenuControl ID="SideMenuControl1" runat="server" />
</div>
<div id="content">
<h1>Upload your company logo here</h1>
<asp:Label ID="Label3" runat="server" Text="Select your Logo File:"></asp:Label>
<br />
<input id="FileUpload1" type="file" runat="server" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Update my Logo" />
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</asp:Content>
VB codefile is as follows:
Imports System.Data
Imports System.Collections.Generic
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports MigrateNationalTrades
Imports System.IO
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.Value <> "" Then
Label1.Text = ""
Label2.Text = "Starting upload of: " + FileUpload1.Value.ToString().Trim()
Dim imageInfo As FileInfo = New FileInfo(FileUpload1.Value.ToString().Trim())
Select Case (imageInfo.Extension.ToUpper())
Case ".JPG" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".JPEG" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".GIF" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".BMP" : SaveToDB(Me.FileUpload1.Value.Trim())
Case ".PNG" : SaveToDB(Me.FileUpload1.Value.Trim())
Case Else
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alertMsg", "<script>alert('Error: Unknown File Type.');</script>")
End Select
Else
Label1.Text = "Please cloose a file and try again"
Label2.Text = "" + FileUpload1.Value.ToString()
End If
End Sub
Private Sub SaveToDB(ByVal info As String)
Dim objconn As SqlConnection
objconn = New SqlConnection(ConfigurationManager.ConnectionStrings("TestConnectionString").ConnectionString)
Dim objCom As SqlCommand
Try
Dim imagestream As FileStream = New FileStream(info, FileMode.Open)
Dim data() As Byte
ReDim data(imagestream.Length - 1)
imagestream.Read(data, 0, imagestream.Length)
imagestream.Close()
objCom = New SqlCommand("insert into Logos(UserID,Logo) values (#UserID,#Logo)", objConn)
Dim useridparameter As SqlParameter = New SqlParameter("#UserID", SqlDbType.Int)
useridparameter.Value = "251"
objCom.Parameters.Add(useridparameter)
Dim logoparameter As SqlParameter = New SqlParameter("#Logo", SqlDbType.Image)
logoparameter.Value = data
objCom.Parameters.Add(logoparameter)
objconn.Open()
objCom.ExecuteNonQuery()
objconn.Close()
Label2.Text = "Logo uploaded successfully!"
Catch ex As Exception
Label1.Text = ""
Label2.Text = "Failed: " + ex.ToString()
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'Form.Enctype() = "multipart/form-data"
End Sub
End Class
I'm puzzled as to why the system needs write access to the file that it is reading for upload. maybe you guys and gals can help me out?
Try this below. fileData is what you will pass to you sql.
Change asp control to:
<asp:FileUpload ID="FileUpload1" runat="server" />
Then use:
If FileUpload1.ContentLength > 0 Then
Dim size As Integer = FileUpload1.ContentLength
Dim name As String = FileUpload1.FileName
Dim position As Integer = name.LastIndexOf("\")
name = name.Substring(position + 1)
Dim contentType As String = FileUpload1.ContentType
Dim fileData As Byte() = New Byte(size - 1) {}
FileUpload1.InputStream.Read(fileData, 0, size)
End If
Many thanks to RickJames who helped me out with this conundrum. He's awesome! here is the final working code for the file upload routine that tested out ok on all my machines. I guess it was the full path that was stopping the process from working correctly and the FileUpload control handles that for you:
Web Page:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="TestImageUpload.aspx.vb" Inherits="_Default" MasterPageFile="MasterPage.master"%>
<%# Register Src="sideMenuControl.ascx" TagName="sideMenuControl" TagPrefix="uc1" %>
<asp:Content ID="contentHolder" ContentPlaceHolderID="ContentPlaceHolder" runat="Server">
<div id="mainContent">
<div id="sidecol">
<uc1:sideMenuControl ID="SideMenuControl1" runat="server" />
</div>
<div id="content">
<h1>Upload your company logo here</h1>
<asp:Label ID="Label3" runat="server" Text="Select your Logo File:"></asp:Label>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Update my Logo" />
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</asp:Content>
and here is the working VB script:
Imports System.Data
Imports System.Collections.Generic
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Text.RegularExpressions.Regex
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FileUpload1.FileContent.Length > 0 Then
End If
If FileUpload1.FileContent.Length > 0 Then
Label1.Text = ""
Label2.Text = "Starting upload of: " + FileUpload1.FileName.ToString().Trim()
SaveToDB(FileUpload1.FileName.ToString().Trim())
'Dim imageInfo As FileInfo = New FileInfo(FileUpload1.Value.ToString().Trim())
'Select Case (imageInfo.Extension.ToUpper())
' Case ".JPG" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".JPEG" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".GIF" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".BMP" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case ".PNG" : SaveToDB(Me.FileUpload1.Value.Trim())
' Case Else
'ClientScript.RegisterClientScriptBlock(Me.GetType(), "alertMsg", "<script>alert('Error: Unknown File Type.');</script>")
'End Select
Else
Label1.Text = "Please choose a file and try again"
Label2.Text = "" + FileUpload1.FileName.ToString()
End If
End Sub
Private Sub SaveToDB(ByVal name As String)
Dim objconn As SqlConnection
objconn = New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
Dim objCom As SqlCommand
Try
Dim size As Integer = FileUpload1.FileContent.Length
Dim position As Integer = name.LastIndexOf("\")
name = name.Substring(position + 1)
Dim contentType As String = FileUpload1.PostedFile.ContentType
Dim fileData As Byte() = New Byte(size - 1) {}
FileUpload1.PostedFile.InputStream.Read(fileData, 0, size)
Label2.Text = fileData.ToString()
objCom = New SqlCommand("insert into Logos(UserID,Logo) values (#UserID,#Logo)", objconn)
Dim useridparameter As SqlParameter = New SqlParameter("#UserID", SqlDbType.Int)
useridparameter.Value = "251"
objCom.Parameters.Add(useridparameter)
Dim logoparameter As SqlParameter = New SqlParameter("#Logo", SqlDbType.Image)
logoparameter.Value = fileData
objCom.Parameters.Add(logoparameter)
objconn.Open()
objCom.ExecuteNonQuery()
objconn.Close()
Label2.Text = "Logo uploaded successfully!"
Catch ex As Exception
Label1.Text = "" + name
Label2.Text = "Failed: " + ex.ToString()
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
'Form.Enctype() = "multipart/form-data"
End Sub
End Class
So I've got a XML file that looks like this:
<response>
<led0>0</led0>
<led1>1</led1>
<pot0>0.0</pot0>
<pot1>0.0</pot1>
<temp1>22.2</temp1>
<temp2>***</temp2>
<temp3>***</temp3>
</response>
All I'm trying to do is store each of these lines in the XML as a variable in VB.
For example : Line 3 in the XML would = Dim LED1 in VB.
So that they can then be more easily used in a Web Application.
I've tried looking online but there doesn't seem to be a simple solutions for this? Any help would be appreciated!
If you have zero flexibility on the model:
Using your original xml file
Private Sub testXmlReadingAndWriting()
Try
Dim filename As String = "<your file name here>"
Dim myResponse As Response = Nothing
Dim serializer As New XmlSerializer(GetType(Response))
Using sr As New StreamReader(filename)
myResponse = CType(serializer.Deserialize(sr), Response)
End Using
myResponse.led0 = 0.7
myResponse.temp3 = 23.ToString()
Using sw As New StreamWriter(filename)
serializer.Serialize(sw, myResponse)
End Using
Catch ex As Exception
MessageBox.Show("Exception handled: " & ex.Message)
End Try
End Sub
<XmlRoot("response")> _
Public Class Response
<XmlElement()> _
Public led0 As Single
<XmlElement()> _
Public led1 As Single
<XmlElement()> _
Public pot0 As Single
<XmlElement()> _
Public pot1 As Single
<XmlElement()> _
Public temp1 As String
<XmlElement()> _
Public temp2 As String
<XmlElement()> _
Public temp3 As String
Public Sub New()
End Sub
End Class
This answer for if you have flexibility on the model:
Using Xml Serialization, you can have a strongly typed representation of your xml in memory (variables, as you asked).
Consider this XML:
<response>
<measurement Type="Led" Index="0" Value="0" />
<measurement Type="Led" Index="1" Value="1" />
<measurement Type="Pot" Index="0" Value="0" />
<measurement Type="Pot" Index="1" Value="0" />
<measurement Type="Temp" Index="1" Value="22.2" />
<measurement Type="Temp" Index="2" Value="0" />
<measurement Type="Temp" Index="3" Value="0" />
</response>
Using xml model classes, you can serialize and deserialize from xml to variables. Here's the code to read from xml, modify the values, and write to xml:
Private Sub testXmlReadingAndWriting()
Try
Dim filename As String = "<your file name here>"
Dim myResponse As Response = Nothing
Dim serializer As New XmlSerializer(GetType(Response))
Using sr As New StreamReader(filename)
myResponse = CType(serializer.Deserialize(sr), Response)
End Using
myResponse.Measurements.Add(New Measurement(2, 0.7, MeasurementType.Led))
myResponse.Measurements.Add(New Measurement(2, 10700, MeasurementType.Pot))
myResponse.Measurements.Add(New Measurement(4, 23, MeasurementType.Temp))
Using sw As New StreamWriter(filename)
serializer.Serialize(sw, myResponse)
End Using
Catch ex As Exception
MessageBox.Show("Exception handled: " & ex.Message)
End Try
End Sub
<XmlRoot("response")> _
Public Class Response
<XmlElement("measurement")> _
Public Measurements As List(Of Measurement)
Public Sub New()
End Sub
End Class
Public Class Measurement
<XmlAttribute> _
Public [Type] As MeasurementType
<XmlAttribute> _
Public Index As Integer
<XmlAttribute> _
Public Value As Single
Public Sub New(index As Integer, value As Single, [type] As MeasurementType)
Me.Index = index
Me.Value = value
Me.[Type] = [type]
End Sub
Public Sub New()
End Sub
End Class
Public Enum MeasurementType
Led
Pot
Temp
End Enum
I realize I modified your xml model, but this makes for a more flexible model.