Dynamic page creation from db at run time in asp.net - asp.net

I'm making E-Commerce website. Under that I want to show particular product details. From query string I can do that but that is not seo friendly so I need to make product name in url(from db) instead of using querystring. I tried following code but it is not working for me.
Error - The resource could not be Found
Global.asax
<%# Application Language="VB" %>
<%# Import Namespace="System.Web.Optimization" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
Sub Application_Start(sender As Object, e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
End Sub
Private Shared Sub RegisterRoutes(routes As RouteCollection)
routes.MapPageRoute("product-detail", "{product_name}.aspx", "product-detail.aspx")
End Sub
</script>
product-detail.aspx (Dynamic Page)
Private Sub product_detail_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim pageName As String = Me.Page.RouteData.Values("product_name").ToString()
End If
End Sub
shop.aspx (used listview control to display list of products)
<asp:ListView ID="products" runat="server" DataKeyNames="ID">
<ItemTemplate>
<asp:HyperLink ID="productID" runat="server" NavigateUrl='<%# Eval("product_name", "~/{0}") %>' CssClass="product-link">
<!--blocks-starts--><div class="blocks blocks-shop">
<asp:Image ID="readyStock" runat="server" ImageUrl="images/common/ready_stock_tag.png" Visible="false" CssClass="tag" />
<asp:Label ID="checkReadyStock" runat="server" Visible="false"></asp:Label>
<div class="block-img">
<img src='<%# Eval("image") %>' runat="server" id="proImg" />
</div>
<div class="block-content">
<span class="sku" style="font-size:0.6em !important">Item No. <asp:Label ID="skuID" runat="server" Text='<%# Eval("sku") %>'></asp:Label></span>
<h3>
<asp:Label ID="prodName" runat="server" Text='<%# Eval("product_name") %>'></asp:Label></h3>
<p><strong>
<asp:Label ID="priceRange" runat="server" Text='<%# Eval("price_range") %>'></asp:Label></strong></p>
</div>
</div><!--blocks-ends-->
</asp:HyperLink>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
</asp:ListView>
shop.aspx.vb
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "select * from products where status = 'active'"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
products.DataSource = dt
products.DataBind()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub

Related

Dynamic file download buttons in VB .NET

I have a page in a VB NET 2005 web project. On page load, it takes data from the logged in user, looks up a set of documents owned by that user, and creates a "download" button for each. Currently, this button opens a new window that streams the document, but we'd like the button itself to trigger a download.
I've got some options for this, but they all seem kind of hacky, and while I haven't found any good solutions, this seems like it should be a solved problem.
The buttons are in a form (so postback with hidden fields is one of the "hacky" options).
Let's say I have a GridView with 3 columns: Filename, Size and a Download button. Then set the CommandName and CommandArgument of the button. For security reason, it might be a better idea to use the user's document id instead of the full path name like I did. You can get the real file using combination of current user and the document id.
<asp:TemplateField HeaderText="Filename">
<ItemTemplate>
<asp:Label ID="lblFilename" runat="server" Text='<%# Bind("Filename") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<ItemTemplate>
<asp:Label ID="lblSize" runat="server" Text='<%# Bind("Size") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download">
<ItemTemplate>
<asp:Button ID="btnDownload" runat="server" Text="Download"
CommandName="Download" CommandArgument='<%# Eval("FullName") %>' />
</ItemTemplate>
</asp:TemplateField>
This is the class which I use to hold the list of files for download. A list of this class binds to the GridView.
Public Class MyFileInfo
Public Property Filename As String
Public Property Fullname As String
Public Property Size As Long
End Class
Last is handling the Download button click. I use the CommandName and CommandArgument to pass what button is click and what file it needs to give to the browser. I use stream and write to the browser with proper MIME type in the header.
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Download" Then
DownloadFile(e.CommandArgument)
End If
End Sub
Sub DownloadFile(filename As String)
Using fs = New FileStream(filename, FileMode.Open)
Response.BufferOutput = False
Response.AddHeader("Content-Length", fs.Length.ToString())
Response.AppendHeader("Content-Disposition", "attachment;filename=" & Path.GetFileName(filename))
Response.ContentType = "application/msword"
fs.Position = 0
fs.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
End Using
End Sub
Full code (aspx):
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Filename">
<ItemTemplate>
<asp:Label ID="lblFilename" runat="server" Text='<%# Bind("Filename") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Size">
<ItemTemplate>
<asp:Label ID="lblSize" runat="server" Text='<%# Bind("Size") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Download">
<ItemTemplate>
<asp:Button ID="btnDownload" runat="server" Text="Download"
CommandName="Download" CommandArgument='<%# Eval("FullName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Full code (code behind):
Imports System.IO
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then BindGridList()
End Sub
Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Download" Then
DownloadFile(e.CommandArgument)
End If
End Sub
Sub BindGridList()
GridView1.DataSource = GetFiles()
GridView1.DataBind()
End Sub
Function GetFiles() As List(Of MyFileInfo)
Dim listFileInfos = New List(Of MyFileInfo)
Dim dirInfo = New DirectoryInfo(Server.MapPath("~/Data"))
Dim fileInfos = dirInfo.GetFiles("*.doc")
For Each fileInfo In fileInfos
listFileInfos.Add(New MyFileInfo With {.Filename = fileInfo.Name, .Size = fileInfo.Length, .Fullname = fileInfo.FullName})
Next
Return listFileInfos
End Function
Sub DownloadFile(filename As String)
Using fs = New FileStream(filename, FileMode.Open)
Response.BufferOutput = False
Response.AddHeader("Content-Length", fs.Length.ToString())
Response.AppendHeader("Content-Disposition", "attachment;filename=" & Path.GetFileName(filename))
Response.ContentType = "application/msword"
fs.Position = 0
fs.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
End Using
End Sub
End Class
Public Class MyFileInfo
Public Property Filename As String
Public Property Fullname As String
Public Property Size As Long
End Class

ListView Datapager not working When Session used instead of VeiwState

I want to display list of clinics details in listview. From MasterPage Users selects the city & If he goes to clinincs page then list of hospitals display from selected city. Now If I use ViewState in my clinics page then It does not gets clinics data from selected city So what I have done I store City session & on clinics page I have used Session instead of ViewState Which is now working right but my datagaer stopped working. If I have to see another page from datapager then it doesn't switch over. Here is my code
MasterPage
Protected Sub locationSelector_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles locationSelector.TextChanged
Session("masterLocation") = locationSelector.text
Session("Data") = Nothing
End Sub
Clinics Page
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Try
If Not Session("Data") Is Nothing Then
hospitals.DataSource = Session("Data")
hospitals.DataBind()
Else
Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator")
query = "select hospitalid, name, address, thumbnail, serviceID, mondayFrom, mondayTo, consultancyFees, city from hospitals Where city Like '" + citySelector.Text + "%' and status = 'active'"
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 120
Dim da As New MySqlDataAdapter(cmd)
Dim table As New DataTable
da.Fill(table)
Session("Data") = table
hospitals.DataSource = table
hospitals.DataBind()
End If
'mainCount.Text = table.Rows(0)("countRows").ToString
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Protected Sub DataPager1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Try
Dim table As DataTable = Session("Data")
hospitals.DataSource = table
hospitals.DataBind()
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Listview on ASPX
<asp:ListView ID="hospitals" runat="server" DataKeyNames="hospitalID" DataKey="hospitalID">
<ItemTemplate>
My Content
</ItemTemplate>
<EmptyDataTemplate>
<div class="not-found">
<p>
Sorry! Selected Query Not Found</p>
<center>
<img src="images/not-found.jpg" /></center>
</div>
</EmptyDataTemplate>
<LayoutTemplate>
<ul id="itemPlaceholderContainer" runat="server" style="">
<li runat="server" id="itemPlaceholder" />
</ul>
<div class="datapager" style="padding-bottom: 10px;">
<asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID="hospitals" ViewStateMode="Enabled">
<Fields>
<asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</div>
</LayoutTemplate>
</asp:ListView>
This is working sample of your page:
hospital.master
<%# Master Language="VB" CodeFile="hospital.master.vb" Inherits="hospital_master" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" />
<div>
<asp:Label ID="lblLockSel" runat="server" AssociatedControlID="locationSelector">Locator Selector</asp:Label>
<asp:UpdatePanel ID="upLocSel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="locationSelector" runat="server" AutoPostBack="true"></asp:TextBox>
<asp:Label ID="locationPopupActivator" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
hospital.master.vb
Partial Class hospital_master
Inherits System.Web.UI.MasterPage
Protected Sub locationSelector_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles locationSelector.TextChanged
Session("masterLocation") = locationSelector.Text
Session("Data") = Nothing
locationPopupActivator.Text = locationSelector.Text
End Sub
End Class
clinics.aspx
<%# Page Title="" Language="VB" MasterPageFile="~/hospital.master" AutoEventWireup="false" CodeFile="clinics.aspx.vb" Inherits="Clinics" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:UpdatePanel ID="upHospitals" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:ListView ID="hospitals" runat="server" DataKeyNames="hospitalID" DataKey="hospitalID">
<ItemTemplate>
<%--My Content--%>
<li>
<asp:HyperLink ID="lnkHospital" runat="server" NavigateUrl='<%#Eval("hospitalID", "~/hospital.aspx?id={0}") %>' Text='<%#Eval("Name") %>'></asp:HyperLink>
</li>
</ItemTemplate>
<EmptyDataTemplate>
<div class="not-found">
<p>
Sorry! Selected Query Not Found</p>
<center><%--<center>Is Deprecated Use div with CSS</center>--%>
<img src="images/not-found.jpg" /></center>
</div>
</EmptyDataTemplate>
<LayoutTemplate>
<ul>
<li runat="server" id="itemPlaceholder" />
</ul>
</LayoutTemplate>
</asp:ListView>
<%--Inside Update Panel dataPager should be outside paged control--%>
<div class="datapager" style="padding-bottom: 10px;">
<asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID="hospitals"><%-- ViewStateMode="Enabled"> this is default--%>
<Fields>
<asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
clinics.aspx.vb
Partial Class Clinics
Inherits System.Web.UI.Page
Private Sub Clinics_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Session.Remove("Data") 'init
End If
End Sub
Private Sub hospitals_PagePropertiesChanging(sender As Object, e As PagePropertiesChangingEventArgs) Handles hospitals.PagePropertiesChanging
DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
hospitals.DataSource = GetData() 'Session("Data")
hospitals.DataBind()
End Sub
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
hospitals.DataSource = GetData()
hospitals.DataBind()
End Sub
Private Function GetData() As Data.DataTable
Try
If Session("Data") IsNot Nothing Then
Return Session("Data")
Else
'This is MS SQL server. If you use MySQL then change types accordingly
DataPager1.SetPageProperties(0, DataPager1.PageSize, False) 'reinit
Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator")
Using con As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ClinicsCNN").ConnectionString)
Dim cmd As New Data.SqlClient.SqlCommand("select hospitalid, name, address, thumbnail, serviceID, mondayFrom, mondayTo, consultancyFees, city from hospitals Where city Like #city and status = 'active'", con)
cmd.CommandType = Data.CommandType.Text
cmd.Parameters.Add("#city", Data.SqlDbType.VarChar, 50).Value = citySelector.Text & "%" 'same as Session("masterLocation")
Dim table As New Data.DataTable()
Dim da As New Data.SqlClient.SqlDataAdapter(cmd)
da.Fill(table)
da.Dispose()
cmd.Dispose()
Session("Data") = table
Return table
End Using
End If
Catch ex As Exception
Response.Write(ex) 'for debug purpose
Return Nothing
End Try
End Function
End Class
Do you accept this solution?
Ok, after your comments here is my code that works for me:
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Try
If Session("Data") Is Nothing Then
Dim citySelector As Label = Page.Master.FindControl("locationPopupActivator")
query = "select hospitalid, name, address, thumbnail, serviceID, mondayFrom, mondayTo, consultancyFees, city from hospitals Where city Like '" + citySelector.Text + "%' and status = 'active'"
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 120
Dim da As New MySqlDataAdapter(cmd)
Dim table As New DataTable
da.Fill(table)
Session("Data") = table
hospitals.DataSource = table
hospitals.DataBind()
End If
'mainCount.Text = table.Rows(0)("countRows").ToString
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
protected void hospitals_PagePropertiesChanging(object sender, System.Web.UI.WebControls.PagePropertiesChangingEventArgs e)
{
var datapager = ((DataPager)hospitals.FindControl("DataPager1"));
datapager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
hospitals.DataSource = Session["Data"];
hospitals.DataBind();
datapager.DataBind();
}
I don't think you need DataPager1_PreRender method at all so probably you should remove it all together. You will need to attach new event to your list view: OnPagePropertiesChanging="hospitals_PagePropertiesChanging". Sorry for code in c#, but I don't know VB very well ;)

ASp.Net Identity Role manager

I am using Visual Studio 2013. I have a ASP.net (vb) Webforms site with asp.net identity. I trying to create a page that manages User role and create roles. I cant find any help online for this when it comes to web forms. This code works for asp.net membership but not for Identity. Here is my code.
Please help Thanks.
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Imports Owin
Partial Class AssignRoles
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Roles.AddUserToRole(DropDownList5.SelectedValue, DropDownList6.SelectedValue)
Label1.Text = DropDownList5.SelectedValue + " Was added to the " + DropDownList6.SelectedValue + " Role."
End Sub
Protected Sub btnremoverole_Click(sender As Object, e As EventArgs) Handles btnremoverole.Click
Roles.RemoveUserFromRole(DropDownList3.SelectedValue, DropDownList4.SelectedValue)
Label1.Text = DropDownList3.SelectedValue + " Was removed from the " + DropDownList4.SelectedValue + " Role."
End Sub
Protected Sub CreateRole_Click(sender As Object, e As EventArgs) Handles CreateRole.Click
Dim createRole As String = RoleTextBox.Text
Try
If Roles.RoleExists(createRole) Then
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' already exists. Please specify a different role name."
Return
End If
Roles.CreateRole(createRole)
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' created."
' Re-bind roles to GridView.
Catch
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' <u>not</u> created."
End Try
End Sub
End Class
Here is the Markup code
<%# Page Title="Admin Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true"CodeBehind="AssignRoles.aspx.vb" Inherits="Conflict_Minerals.AssignRoles" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="row">
<div class="col-md-12">
<h2>Admin Panel</h2>
<br />
</div>
<div class="col-md-8">
<asp:Label ID="Label3" runat="server" Text="Add user to role: "></asp:Label>
<asp:DropDownList ID="DropDownList5" runat="server" DataSourceID="SqlDataSource1" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
<asp:DropDownList ID="DropDownList6" runat="server" DataSourceID="SqlDataSource2" DataTextField="Name" DataValueField="Name">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Add user to role" />
</div>
<div class="col-md-8">
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Remove user from role: "></asp:Label>
<asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource1" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
&nbsp<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource2" DataTextField="RoleName" DataValueField="RoleName">
</asp:DropDownList> &nbsp
<asp:Button ID="btnremoverole" runat="server" Text="Remove user from role" Height="26px" />
<br />
<br />
<div>
<h2>Manage Roles</h2>
</div>
<br />
<asp:TextBox ID="RoleTextBox" runat="server"></asp:TextBox>
<asp:Button ID="CreateRole" runat="server" Text="Create Role" />
<br />
<br />
<asp:Label ID="Msg" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [Name] FROM [vw_AspNetRoles]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT [UserName] FROM [AspNetUsers]"></asp:SqlDataSource>
<br />
<br />
</div>
</div>
</asp:Content>
I found a solution here is my code
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Microsoft.Owin.Security
Imports Owin
Partial Class AssignRoles
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim UserManager = New UserManager(Of IdentityUser)(New UserStore(Of IdentityUser)(New IdentityDbContext()))
UserManager.AddToRole(DropDownList5.SelectedValue, DropDownList6.SelectedValue)
Label1.Text = DropDownList5.SelectedItem.Text + " Was added to the " + DropDownList6.SelectedValue + " Role."
End Sub
Protected Sub btnremoverole_Click(sender As Object, e As EventArgs) Handles btnremoverole.Click
Dim UserManager = New UserManager(Of IdentityUser)(New UserStore(Of IdentityUser)(New IdentityDbContext()))
UserManager.RemoveFromRoles(DropDownList3.SelectedValue, DropDownList4.SelectedValue)
Label1.Text = DropDownList3.SelectedItem.Text + " Was removed from the " + DropDownList4.SelectedValue + " Role."
End Sub
Protected Sub CreateRole_Click(sender As Object, e As EventArgs) Handles CreateRole.Click
Dim createRole As String = RoleTextBox.Text
Dim RoleManager = New RoleManager(Of IdentityRole)(New RoleStore(Of IdentityRole)(New ApplicationDbContext()))
Try
If RoleManager.RoleExists(createRole) Then
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' already exists. Please specify a different role name."
Return
End If
RoleManager.Create(New IdentityRole(createRole))
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' created."
' Re-bind roles to GridView.
Catch
Msg.Text = "Role '" & Server.HtmlEncode(createRole) & "' <u>not</u> created."
End Try
End Sub
End Class
You're going to need to instantiate a RoleManager to work with the roles. From there you can replace your AddRole and RemoveRole code. You will need a UserManager to assign roles to users. Here is a walkthrough for WebForms.http://www.asp.net/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/membership-and-administration

ASP.net Syntax error in INSERT INTO statement - cmd.ExecuteNonQuery()

Currently doing a project and I am having a serious problem with some code. I keep getting the cmd.ExecuteNonQuery() and i have searched all over the internet to find the solution. I have inserted [] in certain catagories and still produces the same error.
All I am doing is creating a page where people can input data for certain catagories, in which once added, it will be updated to the access database. I had this working on an earlier version but ever since i added more characters, it has come with this error.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="addcar.aspx.vb" Inherits="WebApplication1.addcar" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
<p>
<br />
CarName<asp:TextBox ID="tb_CarName" runat="server"></asp:TextBox>
</p>
<p>
<br />
Year<asp:TextBox ID="tb_Year" runat="server"></asp:TextBox>
</p>
<p>
<br />
EngineSize<asp:TextBox ID="tb_EngineSize" runat="server"></asp:TextBox>
</p>
<p>
<br />
BHP<asp:TextBox ID="tb_BHP" runat="server"></asp:TextBox>
</p>
<p>
<br />
Origin<asp:TextBox ID="tb_Origin" runat="server"></asp:TextBox>
</p>
<p>
<br />
Description<asp:TextBox ID="tb_Description" runat="server"></asp:TextBox>
</p>
<p>
<br />
Pictures<asp:TextBox ID="tb_Pictures" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button" runat="server" Text="Add Car Details" />
</p>
</asp:Content>
Followed by the button code which is:
Imports System.Data.OleDb
Public Class addcar
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("CarsConnectionString").ConnectionString)
Dim SqlString As String = "Insert into Table1(CarName,Year,EngineSize,BHP,Origin,Description,Pictures) Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_CarName.Text)
cmd.Parameters.AddWithValue("#f2", tb_Year.Text)
cmd.Parameters.AddWithValue("#f3", tb_EngineSize.Text)
cmd.Parameters.AddWithValue("#f4", tb_BHP.Text)
cmd.Parameters.AddWithValue("#f5", tb_Origin.Text)
cmd.Parameters.AddWithValue("#f6", tb_Description.Text)
cmd.Parameters.AddWithValue("#f7", tb_Pictures.Text)
oleDbConn.Open()
cmd.ExecuteNonQuery()
Response.Redirect("confirmation.aspx")
End Sub
End Class
Help? What am I doing wrong?
Error is as follows:
Syntax error in INSERT INTO statement.
Year is a reserved keyword in access / Jet.
You need to encapsulate it with square brackets.
Dim SqlString As String = "Insert into Table1(CarName, [Year],EngineSize,BHP,Origin,Description,Pictures) Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7)"
You can check every reserved keyword in the jet engine here:
http://support.microsoft.com/kb/248738

Making changes to a pre-populated textbox

I have the following webform with textboxes that are pre-populated on page load:
<%# Page Title="" Language="VB" MasterPageFile="~/default.master" AutoEventWireup="true" CodeFile="admin.aspx.vb" Inherits="admin" Theme="G2M" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="form1" Runat="Server">
<label>Username: </label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<label>Password: </label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<label>Product Type: </label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<label>SMTP Default Only: </label>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<br />
<label>Logo: </label>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<br />
<asp:Button ID="submit" Text="Submit changes" runat="server" OnClick="SubmitChanges" />
</form>
</asp:Content>
And the codebehind is as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmlDoc As New XmlDocument
xmlDoc.Load(Server.MapPath("~/XML_Config/Config.xml"))
Dim configValues As XMLParser = New XMLParser(xmlDoc) ''Instantiate the XMLParser
''Populate textboxes with XML data
TextBox1.Text = configValues.UserName
TextBox2.Text = configValues.Password
TextBox3.Text = configValues.ProductType
TextBox4.Text = configValues.SMTPDefaultOnly
TextBox5.Text = configValues.Logo
End Sub
Public Sub SubmitChanges(ByVal sender As Object, ByVal e As System.EventArgs)
Dim xmlDoc As New XmlDocument
xmlDoc.Load(Server.MapPath("~/XML_Config/Config.xml"))
Dim configValues As XMLParser = New XMLParser(xmlDoc) ''Instantiate the XMLParser
configValues.SMTPDefaultOnly = TextBox4.Text
End Sub
All I'm trying to do is make the values editable so when the form is presented to the user, they can change the values and submit them back to the file. My problem is that when the SubmitChanges function is called, even though I change the value of the textbox, it is still the same. How do I pass a new value, typed into thetextbox, to the function?
Enclose your setter in If Not ispostback in that page load. It's overwriting the boxes.

Resources