The ConnectionString property has not been initialized for DropDownList - asp.net

I have the following code:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Reports</title>
<script language="javascript" src="js/DynamicReports.js" type="text/javascript"></script>
</head>
<body onload="doSelect()">
<asp:DropDownList ID="ddlDynReports" runat="server" DataSourceID="sdsDynReports" DataTextField="DynReportName" DataValueField="DynReportID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsDynReports" runat="server" SelectCommand="select v.object_id as DynReportID, substring(v.name, 11, LEN(v.name)) as DynReportName from sys.views v where v.name like 'DynReport[_]%'">
</asp:SqlDataSource>
</body>
</html>
It throws the following error at runtime:
The ConnectionString property has not been initialized.
My web.config file seems to be okay because I am doing many other sql calls in the .vb code. This is the first time I am doing sql in .aspx code.
I presume my connection that is available in my .vb code needs to be exposed to the .aspx code.
I am open to a solution that would move the select to the .vb code.
EDIT: I figured out that I should add ConnectionString="<%$ ConnectionStrings:constr %>" to the SqlDataSource element, but the problem is that I do not have connection strings in my web.config file. My connection strings are in a file called ApplicationConfig.vb.
So, how can I get the connection string out of ApplicationConfig.vb into the .aspx code?
EDIT: I am doing it this way because it is the sample code I found for populating a dropdown from a select statement. I am a vb.net noob so I am basically surviving by cutting and pasting from the SO. Suggestions for better ways is cheerfully accepted but I get lost if the example code is not complete. Example: Some example code I find on SO looks like what I want to do, but it is a series of snip-its and I don't know where to put those snip-its.
EDIT: Add .vb code:
Partial Class XXX_CommonPages_DynamicReports
Inherits System.Web.UI.Page
Protected Sub dynreport_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles dynreports_run.ServerClick
Dim ViewObjectId As String = ddlDynReports.SelectedValue
Dim DataOut As String = "some,data,out"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=DynReport_" + ViewObjectId + ".csv")
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Length", DataOut.Length())
Response.Write(DataOut)
' Response.End ' Causes ThreadAbortException.
End Sub
End Class
EDIT: Here is the .vb code that contains the connection string:
Public Class ApplicationConfig
Public Class AppConfig
Implements IConfigurationSectionHandler
Private Const PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT As String = "serve ..."
Public Shared ReadOnly Property ConnectionString() As String
Get
If fieldConnectionString Is Nothing Then fieldConnectionString = PRODUCTION_DATAACCESS_CONNECTIONSTRING_DEFAULT
Return fieldConnectionString
End Get
End Property
End Class
End Class

Related

Load a set of variables from a SQL database - language ASP.NET VB

I am trying to translate an old "Classic ASP" page to ASP.NET page. I have limited ASP.NET knowledge.
I am reading some data from a SQL server.
I have a basic question, but so far I was not able to successfully implement any working solution.
The code attached is working well; shows the data I need.
I would like to have a similar code structure but this time I would like to assign the data from SQL to variables (I do not need to print these output values on the screen):
title (output of SQL query) ---> "titleV" variable (string)
father (output of SQL query) ---> "fatherV" variable (string)
age (output of SQL query) ---> "ageV" variable (number)
If possible, please suggest to me a piece of code I can test.
Thank you.
<%# Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=NewOleDbConnection("connection string to sql server")
dbconn.Open()
sql="SELECT * FROM photos"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:DataList id="customers" runat="server">
<ItemTemplate>
<%#Container.DataItem("title")%> in
<%#Container.DataItem("father")%> with
<%#Container.DataItem("age")%> years
</ItemTemplate>
</asp:DataList>
</form>
</body></html>
You can save one record in above 3 variables because you are not using array type or collections. You can assign the data from the table to your variables using the following code.
sub page_load()
dbconn = new oledbconnection("conn str")
dbconn.Open()
sql="SELECT * FROM photos"
dim adpt as OledbDataAdapter
dim rs as new DataTable
adpt = new OledbDataAdapter(sql,dbconn)
adpt.fill(rs)
customers.DataSource = rs
customers.DataBind()
dim titleV, fatherV As String
dim ageV as integer
titleV = rs.Rows(0).Item(0) 'Rows(0).Item(0) gives you first row's first field value.
fatherV = rs.Rows(0).Item(1)
ageV = rs.Rows(0).Item(2)
dbconn.Close()
end sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:DataList id="customers" runat="server">
<ItemTemplate>
<%#Container.DataItem("title")%> in
<%#Container.DataItem("father")%> with
<%#Container.DataItem("age")%> years
</ItemTemplate>
</asp:DataList>
</form>
</body></html>

Specified Cast is not valid when DataBind to Nullable DateTimeOffset and field is NULL

I've created a simple CompositeControl and exposed a Nullable DateTimeOffset property.
I'm binding the control to a SQL Server DateTimeOffset field using
DateTimeOffset='<%# Bind("myDateTimeOffsetField") %>'
This works great when the DateTimeOffset field has a value.
But when the field is NULL I get a "Specified Cast is not valid" error.
How do I stop this error and set my property to Nothing when the field is NULL?
I thought this would be the default behaviour!
Property definition is:
Public Property DateTimeOffset As DateTimeOffset?
Later comment:
I've found that this works if I change from using Bind to:
DateTimeOffset='<%# iif(IsDbNull(Eval("myDateTimeOffsetField")), Nothing, Eval("myDateTimeOffsetField")) %>'
But then I don't get "myDateTimeOffsetField" passed as an argument in the FormView.ItemUpdating event (yes, this is in a FormView control) since ASP.NET assumes I'm not binding back to the Database.
Actual Code (Added by Request)
This is the Property in my Composite Control that I'm trying to bind to:
Public Property DateTimeOffset As DateTimeOffset?
Get
Return CType(ViewState("DTO"), DateTimeOffset?)
End Get
Set(value As DateTimeOffset?)
ViewState("DTO") = value
End Set
End Property
Heres the markup for the Binding. The Control is in the EditItemTemplate of a FormView which is bound to a SQL DataSource returning a field called [dtoMldRejOn] with an optional DateTimeOffset value.
<APS:DateTimeOffsetControl runat="server" id="dtocMldRejOn" TextBoxCssClass="inputdatetime" ValidationGroup="vw1" FieldName="<%$ Resources: Resource, rxgFrom %>" DateTimeOffset='<%# Bind("dtoMldRejOn") %>' WindowsTimeZoneID="<%# me.WindowsTimeZoneID %>" IsRequired="false" />
As you can see, my Composite control is for handling DateTimeOffset values. It all works great unless the DateTimeOffset field [dtoMldRejOn] from the database is NULL, then I get the exception.
I have never created bindable controls before, but I would like to make suggestion. How about setting your DateTimeOffset property to be of type Object. That way, the property will accept any data types including DBNull.
And once inside the Set code, check if the value passed is DBNull.Value. If so, create a new empty DataTimeOffset? object and save it in the ViewState.
If non DBNull values, throw error if it cannot be be converted to datetime.
I didn't try this though so I don't know if this will work or not.
################ UPDATED ANSWER ################
My suggestion is, you create 2 properties as follows:
Public Property DateTimeOffset() As DateTimeOffset?
Get
Return DirectCast(ViewState("DTO"), DateTimeOffset?)
End Get
Set(ByVal Value As DateTimeOffset?)
ViewState("DTO") = Value
End Set
End Property
<Bindable(True, BindingDirection.TwoWay)>
Public Property DbDateTimeOffset As Object
Get
Return Me.DateTimeOffset
End Get
Set(value As Object)
If IsDBNull(value) OrElse value Is Nothing Then
Me.DateTimeOffset = New DateTimeOffset?
Else
Me.DateTimeOffset = DirectCast(value, DateTimeOffset?)
End If
End Set
End Property
So in your markup, the binding will be to the DbDateTimeOffset property:
DbDateTimeOffset='<%# Bind("myDateTimeOffsetField") %>'
While in code behind, you can use the other property to read the property without having to cast.
Based on this post,
I think you just need to mark your property with the Bindable attribute:
<System.ComponentModel.Bindable(True)> _
Public Property DateTimeOffset As DateTimeOffset?
The problem is that DbNull is different from Nothing and you must explicitly write that somewhere in your code. My first idea here was to use the binding events to add the value. So if you keep you code like this:
DateTimeOffset='<%# iif(IsDbNull(Eval("myDateTimeOffsetField")), Nothing, Eval("myDateTimeOffsetField")) %>'
You can manually add the DateTimeOffset parameter in the Updating events before the binding proceeds (I can update the answer later with more details on this if you want)
Anyway, after reading your code more carefully I thought that maybe the CType isn't casting correctly. Have you tried replacing your Get with something like this?
Get
Return If(IsDbNull(ViewState("DTO")), Nothing, CType(ViewState("DTO"), DateTimeOffset?))
End Get
Your code with iif ... works for me. I have created a testing control and a page version with code behind pages ( I have tested code behind version too but this one is easier to publish). I have VS2010 target framework is 4.0.
First the control(TstNullableCtrl.ascx):
<%# Control Language="vb" AutoEventWireup="false" %>
<script runat="server">
Public Property DateTimeOffset As DateTimeOffset?
</script>
<div ID="Label1" runat="server" >
<%= If(DateTimeOffset.HasValue, DateTimeOffset.ToString, "Empty")%>
</div>
and the page - a table with two rows and two columns bound to datagrid (TstNullablePage.aspx):
<%# Page Language="vb" AutoEventWireup="false" %>
<%# Import Namespace="System.Data"%>
<%# Register src="TstNullableCtrl.ascx" tagname="TstNullableCtrl" tagprefix="uc1" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim tbl As New DataTable
tbl.Columns.Add(New DataColumn("id", GetType(Integer)) With {.AutoIncrement = True})
tbl.Columns.Add(New DataColumn("myDateTimeOffsetField", GetType(DateTimeOffset)))
Dim row As DataRow
row = tbl.NewRow : row("myDateTimeOffsetField") = DateTimeOffset.Now
tbl.Rows.Add(row)
row = tbl.NewRow : row("myDateTimeOffsetField") = DBNull.Value
tbl.Rows.Add(row)
tstgrd.DataSource = tbl : tstgrd.DataBind()
End Sub
</script>
<html>
<body>
<form id="form1" runat="server">
<asp:datagrid ID="tstgrd" runat="server">
<Columns>
<asp:TemplateColumn HeaderText="Offset">
<itemtemplate>
<uc1:TstNullableCtrl ID="WithNullableDate1" runat="server"
DateTimeOffset='<%# iif(IsDbNull(Eval("myDateTimeOffsetField")), Nothing, Eval("myDateTimeOffsetField")) %>' />
</itemtemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
</form>
</body>
</html>
And expected result (a value when there is and 'Empty' when is null)
Edit
However I think that to "avoid complication" best solution is as follows:
Public _DateTimeOffset As Object
Public Property DateTimeOffset As Object
Get
If IsDBnull(_DateTimeOffset) then Return Nothing
Return Ctype(_DateTimeOffset, DateTimeOffset?)
End Get
Set(value As Object)
_DateTimeOffset = value
End Set
End Property
I know this question have been already answered I just would like to document my solution which is in between those two answers as I have came across this today:
Private _AssetId As Object
<Bindable(True, BindingDirection.TwoWay)>
Public Property AssetId() As Object
Get
If _AssetId Is Nothing Then
Return Nothing
Else
Return CType(_AssetId, Integer)
End If
End Get
Set(ByVal value As Object)
If value Is Nothing OrElse IsDBNull(value) OrElse CType(value, String) = "" Then
_AssetId = Nothing
Else
_AssetId = CType(value, Integer)
End If
End Set
End Property

ajax control toolkit fileupload

I am trying to get the fileupload control from the ajax control toolkit to work.
I need to use the uploaded files in my code behind (I use asp.net),
This includes unzipping, resizing and putting some data in a database.
The problem I have is that when I use ajaxUpload1_OnUploadComplete, i can't get the text from a textbox on the same page.
When I use a breakpoint, I noticed that the value of the textbox is just "".
I have searched a lot and I really can't find a solution for this, so I hoped that someone here might be able to help.
I have pasted my code below, thanks in advance!
.aspx code:
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"
CodeFile="Upload.aspx.vb" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="LblUploadError" runat="server" Text="Please login first" Visible="false"></asp:Label>
<asp:Panel ID="PnlUpload" runat="server" Visible="false">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<span>Album name:</span><br />
<asp:TextBox ID="txtAlbumNaam" runat="server" ViewStateMode="Disabled"></asp:TextBox><br />
<span>Private album</span> <asp:CheckBox ID="chkPrivate" runat="server" /><br />
<span>Upload files (.zip, .jpg, .jpeg or .png)</span><br />
<asp:AjaxFileUpload id="ajaxUpload1" OnUploadComplete="ajaxUpload1_OnUploadComplete" ThrobberID="MyThrobber" runat="server" AllowedFileTypes="jpg,jpeg,zip,png" /><br />
<asp:Label ID="lblError" runat="server"/><br />
</asp:Panel>
</asp:Content>
code behind:
Imports Ionic.Zip
Imports System.IO
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("LoggedIn") = True Then
PnlUpload.Visible = True
Else
LblUploadError.Visible = True
End If
End Sub
Protected Sub ajaxUpload1_OnUploadComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AjaxFileUploadEventArgs)
'indien zip:
Dim ziperror As Boolean = False
If System.IO.Path.GetExtension(e.FileName) = ".zip" Then
ajaxUpload1.SaveAs(Server.MapPath("./TempZips/" & e.FileName.ToString))
Dim ZipToUnpack As String = Server.MapPath("./TempZips/" & e.FileName.ToString)
Dim UnpackDirectory As String = Server.MapPath("./TempFotos")
Using zip1 As ZipFile = ZipFile.Read(ZipToUnpack)
Dim file As ZipEntry
For Each file In zip1
Dim strExtensie As String = System.IO.Path.GetExtension(file.ToString)
If Not (strExtensie = ".jpeg" Or strExtensie = ".jpg" Or strExtensie = ".png") Then
ziperror = True
lblError.Text = "The .zip structure is incorrect, please make sure that you only have compatible pictures inside the zip file."
End If
Next
If ziperror = False Then
For Each file In zip1
file.Extract(UnpackDirectory, ExtractExistingFileAction.OverwriteSilently)
Next
End If
End Using
'indien foto:
ElseIf System.IO.Path.GetExtension(e.FileName) = ".jpeg" Or System.IO.Path.GetExtension(e.FileName) = ".jpg" Or System.IO.Path.GetExtension(e.FileName) = ".png" Then
ajaxUpload1.SaveAs(Server.MapPath("./TempFotos/" & e.FileName.ToString))
Else
'indien geen van beide
lblError.Text = "Invalid filetype on one of the files, please use other files."
End If
'tempzips leegmaken
If ziperror = False Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(Server.MapPath("TempZips"))
File.Delete(foundFile)
Next
'verkleinen en album toevoegen aan database:
Dim strFolderDirectory As String = Server.MapPath("users/" & Session("UserNickName") & "/" & txtAlbumNaam.Text)
System.IO.Directory.CreateDirectory(strFolderDirectory)
Dim strDirectory As String = Server.MapPath("TempFotos")
Dim intAantalFotos As Integer = 0
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory)
Using Afbeelding As System.Drawing.Image = System.Drawing.Image.FromFile(foundFile)
Dim resizedimage As System.Drawing.Image
Dim resizedwidth As Integer
resizedwidth = (300 / Afbeelding.Height) * Afbeelding.Width
resizedimage = Afbeelding.GetThumbnailImage(resizedwidth, 300, Nothing, New IntPtr)
resizedimage.Save(strFolderDirectory & "/" & Path.GetFileName(foundFile))
End Using
intAantalFotos += 1
Next
Dim CmdInsert As New OleDbCommand
Dim Sqlstatement As String = "INSERT INTO tblAlbums (userID, createdDate, pictures, private, albumName) VALUES (#userID, Now(), #pictures, #private, #albumName);"
CmdInsert.Connection = dbConn.cn
CmdInsert.CommandText = Sqlstatement
CmdInsert.Parameters.AddWithValue("userID", CInt(Session("userID")))
CmdInsert.Parameters.AddWithValue("pictures", intAantalFotos)
CmdInsert.Parameters.AddWithValue("private", chkPrivate.Checked)
CmdInsert.Parameters.AddWithValue("albumName", txtAlbumNaam.Text)
dbConn.cn.Close()
dbConn.cn.Open()
CmdInsert.ExecuteNonQuery()
dbConn.cn.Close()
'TempFotos leegmaken
For Each foundFile As String In My.Computer.FileSystem.GetFiles(strDirectory)
File.Delete(foundFile)
Next
'pagina herladen
LblUploadError.Visible = True
LblUploadError.Text = "Your pictures have been successfully uploaded!"
End If
End Sub
End Class
The problem is that ajax control toolkit file upload control can upload files to server using hidden iFrame (depending on what HTML5 features browser supports). Hidden iFrame references to the same url as you page and that's why you page loaded once more but only to hidden iframe. That's why on server side during handling UploadComplete event you get that the text box has empty value (because it is really have empty value because this is the state of the page which was loaded in iframe).
One of the solution to your problem is performing additional logic (which depends on entered data) after uploading is complete. To do this you can handle client side upload complete event and perform postback (or ajax request) manually.
Other solution can be setting content of the hidden iFrame elements manually before upload will start. In this case you can get hidden iframe, found necessary HTML elements (like text input in your case) and set it value the same as it was entered by user. But this approach can required extending logic of the ajax control toolkit upload control on client side.

ASP.Net AutoCompleteExtender VB WebMethod not firing - why?

Definitely at my wits end here. This should be simple. In a page to create new user accounts, we have a database with a little of allowable users. To streamline getting the Email address of the new user correct, we want to use an AutoComplete extended textbox.
Now I know that WebMethods are working because I have a cascading-drop-down tied to web methods in another page.
As I'm just starting on this page, the code is simple.
The page itself:
<cc1:ToolkitScriptManager ID="ScriptManager2" runat="server"/>
<p></p> Please enter new user's Email:
<asp:TextBox ID="txtUser" runat="server" />
<cc1:AutoCompleteExtender runat="server" ID="autUser" TargetControlID="txtUser"
ServiceMethod="ScanGALUsers" ServicePath="~/AutoScan.asmx"
MinimumPrefixLength="3" CompletionSetCount="150" /> <p></p>
The .asmx file is simple:
<%# WebService Language="VB" CodeBehind="~/App_Code/VB_Code/AutoScan.vb" Class="AutoScan" %>
The WebMethod:
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class AutoScan
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Shared Function ScanGALUsers(ByVal strPrefix As String, ByVal intMaxCount As Integer) As String()
Dim arlResults As New ArrayList
Dim intCount As Integer
Dim dt As DataTable
Dim colParameters As New SortedList
SysDA.LogDebug("ScanGALUsers called with parameters: " & strPrefix & " and count of " & intMaxCount.ToString)
... Deleted for brevity ...
If intCount > 0 Then
Dim arrResults(intCount - 1) As String
arrResults = arlResults.ToArray(GetType(System.String))
Return arrResults
Else
Return Nothing
End If
End Function
End Class
I'm not even getting to the LogDebug statement. I've used all the same boilerplate code (Inherits, the 'WebService' tags, etc) that worked in the other WebMethod with the appropriate changes to the Class name but this really has me stumped.
What am I missing that I'm not even making it to the method?
Did you ever resolve this issue? Have you tried removing Shared from your WebService declaration? This has worked for me before (and I don't know why!).

vb.net upload file problem

When I try to post a file its coming back false ie there was no file attached. Can anyone see anything wrong with this? Or what might be causing it.
<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
<asp:FileUpload ID="fileUpload" runat="server" />
<asp:Button ID="cmdSubmitApplication" runat="server" Text="Button" />
</form>
Protected Sub cmdSubmitApplication_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmitApplication.Click
If Me.fileUpload.PostedFile Is Nothing Then
Response.Write("You must specify file to upload!")
Else
Try
Dim strExt As String = Path.GetExtension(Me.fileUpload.PostedFile.FileName)
If strExt.ToLower() = ".doc" Then
Dim savedFile As String
savedFile = Path.GetFileName(Me.fileUpload.PostedFile.FileName)
Me.fileUpload.PostedFile.SaveAs(Server.MapPath("cvs\") & savedFile)
Response.Write("File Uploaded Successfully")
Else
Response.Write("Only Image Files are Allowed")
End If
Catch exp As Exception
Response.Write(exp.Message)
End Try
End If
End Sub
Try using:
If Me.fileUpload.HasFile Then
Response.Write("You must specify file to upload!")
Else
here is a full working example from MSDN:
http://msdn.microsoft.com/en-us/kb/kb00323245.aspx
please have a look.
also try replacing "If Me.fileUpload.PostedFile Is Nothing Then" with "If fileUpload.PostedFile Is Nothing Then"
and check permissions on the destination folder
Try removing the enctype="multipart/form-data" from the form tag. I'm looking at my pages that I use the upload on and they don't have it.
I have the form tag in a master page, but it's just:
< form id="form1" runat="server" >
< form >
Public Sub UploadFile(ByVal BugID As System.Guid, ByVal Files As System.Web.UI.WebControls.FileUpload, ByVal fileDescription As String)
Dim guid As System.Guid = System.Guid.NewGuid()
Dim filesSave As New BugTrackerData.Files.Files()
Dim filename As String = Files.PostedFile.FileName
'Grab the file name from its fully qualified path at client
Dim strFileName As String = guid.ToString() & System.IO.Path.GetExtension(filename)
'Save uploaded file to server at C:\ServerFolder\
Dim savepath As String = System.Web.HttpContext.Current.Server.MapPath("~/Resources/FileUploads/" & strFileName)
Try
If Not String.IsNullOrEmpty(FileUpload1.FileName) Then
Files.PostedFile.SaveAs(savepath)
filesSave.SaveToDB(guid, BugID, strFileName, fileDescription)
End If
Catch Exp As Exception
Throw Exp
End Try
End Sub
fixed it. There was a tag in the master, so the form I added below was nested. I removed the form tag from the master. Would that cause problems elsewhere. Should I just remove the form tag above instead of the master.
ps I hate vb.net and everything about it.

Resources