C# Roles.GetAllRoles() error - does not contain a definition - c#

I am trying to get all Roles in my C# application.
When I copy the C# code from: https://learn.microsoft.com/en-us/dotnet/api/system.web.security.roles.getallroles?view=netframework-4.8
into a single aspx page exactly as they have the example then the page works and I can see the Roles and add one properly.
When I have the following code-behind code:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
namespace ToolingPMv2.Admin.Access
{
public partial class Roles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] rolesArray;
rolesArray = Roles.GetAllRoles();
RolesGrid.DataSource = rolesArray;
RolesGrid.DataBind();
}
}
}
}
My aspx page:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.Master" CodeBehind="UserRoles.aspx.cs" Inherits="ToolingPMv2.Admin.Access.Roles" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2>Roles</h2>
<br />
<asp:GridView runat="server" CellPadding="2" id="RolesGrid" Gridlines="Both" CellSpacing="2" AutoGenerateColumns="false" >
<HeaderStyle BackColor="navy" ForeColor="white" />
<Columns>
<asp:TemplateField HeaderText="Roles" >
<ItemTemplate>
<%# Container.DataItem.ToString() %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>
I get the following error: 'ToolingPMv2.Admin.Access.Roles' does not contain a definition for 'GetAllRoles'
I thought that if I have 'Using System.Web.Security' I could access this method.
What am I doing wrong? This seems like a basic fundamental lesson that I should know by now.

The class for your page is named Roles so that is hiding the one in the other namespace. You need to be explicit, for example:
rolesArray = System.Web.Security.Roles.GetAllRoles();

Related

GridView RowDataBoundEvent not running

I'm working with a GridView and I am using a TableAdapter to communicate with my SQL Server 2017 Express. I have managed to display the table into a GridView but I would like to make the name of each entry in my database have a hyperlink that will direct the user to another page that contains a DetailsView that would allow the user to edit the corresponding entry. However, I am currently have troubles with the RowDataBoundEvent as it seemingly is not triggering.
When I set a breakpoint right at the if statement, the program does not stop at the breakpoint.
protected void ProductViewRowBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string hyperLink = e.Row.Cells[1].Text;
e.Row.Cells[1].Text = "Test";
//HyperLink link = new HyperLink;
}
}
I checked my RowDataBound method name and it matches the one I specified in the aspx file:
<asp:GridView ID="ProductView" runat="server" Height="299px" Width="578px" AllowPaging="True" HorizontalAlign="Center"
OnRowDataBoundEvent="ProductViewRowBound" style="table-layout:auto">
<HeaderStyle Width="300px" />
</asp:GridView>
CS File:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Maintenance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
ProductSetTableAdapters.Product_Table_AlphaTableAdapter productAdapter = new ProductSetTableAdapters.Product_Table_AlphaTableAdapter();
ProductView.DataSource = productAdapter.GetData();
ProductView.DataBind();
}
ProductView.RowDataBound += new GridViewRowEventHandler(ProductViewRowBound);
}
protected void ProductViewRowBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
string hyperLink = e.Row.Cells[1].Text;
e.Row.Cells[1].Text = "Test";
//HyperLink link = new HyperLink;
}
}
}
ASPX File:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Maintenance.aspx.cs" Inherits="Maintenance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div style="overflow-x:scroll;overflow-y:scroll; margin-left:auto; margin-right:auto;">
<asp:GridView ID="ProductView" runat="server" Height="299px" Width="578px" AllowPaging="True" HorizontalAlign="Center"
OnRowDataBoundEvent="ProductViewRowBound" style="table-layout:auto">
<HeaderStyle Width="300px" />
</asp:GridView>
</div>
</asp:Content>
Why is my RowDataBoundEvent not running and what can I do to fix it?
First, OnRowDataBoundEvent does not exist. It should be OnRowDataBound in the GridView.
<asp:GridView ID="ProductView" runat="server" OnRowDataBound="ProductViewRowBound">
Next you are binding the correct method to the GridView from code behind, but AFTER you bind data to the GridView. So it will not work when you bind productAdapter.GetData().
So either set the correct event name in the GridView aspx or move the method binding above ProductView.DataBind();

Print ArrayList data to ASP.NET page using GridView

Trying to print the stored data of arraylist to the gridview.
.aspx File, Working perfectly fine.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Stock Management System</title>
<style>
body{
background-color:#63AA9C;
text-align:center
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="0" style="background-color:lightcoral">
<tr><td>Item Name:</td><td><asp:TextBox ID="Name" placeholder="Item Name" runat="server"></asp:TextBox></td></tr>
<tr><td>Quantity:</td><td><asp:TextBox ID="Quan" placeholder="Quantity" runat="server"></asp:TextBox></td></tr>
<tr><td>Price:</td><td><asp:TextBox ID="Pri" placeholder="Price" runat="server"></asp:TextBox></td></tr>
<tr><td>Description:</td><td><asp:TextBox ID="Desc" placeholder="Descrition" runat="server"></asp:TextBox></td></tr>
<tr><td><asp:Button ID="Save" runat="server" Text="Store Data" OnClientClick="Store()" width="200px"/></td></tr>
<tr><td><asp:Button ID="Show" runat="server" Text="Show Data" OnClientClick="Print()" width="200px" /></td></tr>
<tr><td><asp:Button ID="Delete" runat="server" Text="Remove Last Added Data" OnClientClick="Remove()" width="200px" /></td></tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral" ></asp:GridView>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral" ></asp:GridView>
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral"></asp:GridView>
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="true" AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="LightCoral"></asp:GridView>
</div>
</form>
</body>
</html>
.aspx.cs File
No error, but not working while pressing the show data button.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList items = new ArrayList();
ArrayList price = new ArrayList();
ArrayList quantity = new ArrayList();
ArrayList description = new ArrayList();
static int a = 0;
protected GridView GridView1;
protected GridView GridView2;
protected GridView GridView3;
protected GridView GridView4;
protected void Page_Load(object sender, EventArgs e)
{
}
public void Store()
{
items.Add(Name.Text);
price.Add(Pri.Text);
quantity.Add(Quan.Text);
description.Add(Desc.Text);
a++;
}
public void Print()
{
GridView1.DataSource = items;
GridView1.DataBind();
GridView2.DataSource = quantity;
GridView2.DataBind();
GridView3.DataSource = price;
GridView3.DataBind();
GridView4.DataSource = description;
GridView4.DataBind();
}
public void Remove()
{
if (a > 0)
{
items.RemoveAt(a);
a--;
}
}
}
}
My page, Trying to show stored data
About the attribute OnClientClick you are using, The documentation says
Gets or sets the client-side script that executes when a Button control's Click event is raised.
which means you are trying to execute a JavaScript function called "Print" in your code (same goes with other buttons).
You should check Button.Click event instead.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click(v=vs.110).aspx

pass a sql parameter into a dynamically created user control C#

I created a gridview user control with a sqldatasource calling a stored procedure. The user control is dynamically created on the aspx page and I have everything working without passing any parameters in. I cannot figure out how to pass the parameters in the user control. Here is a minimized version of the code.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Survey.ascx.cs" Inherits="AppSurvey" %>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Count" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">
<ItemTemplate>
<asp:TextBox ID="txtAnswerCount" runat="server" Columns="5" MaxLength="5" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^\d+$"
Display="None" SetFocusOnError="true" ControlToValidate="txtAnswerCount" ErrorMessage = "Count values must be entered as integer values." />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:1316 %>" SelectCommand="dbo.usp_Survey" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="Category" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Configuration;
namespace EUCNET01316
{
public partial class Survey : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["Category"].DefaultValue = ?????;
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
}
**** ASPX Page
protected void Page_Load(object sender, EventArgs e)
{
UserControl ctl = Page.LoadControl("Survey.ascx") as UserControl;
Panel PB = new Panel();
PB.Controls.Add(ctl);
}
There are a lot of ways to do this, but this is one... In your user control's codebehind you can create a public property to accept your parameter or the value that you will assign to your sql parameter:
namespace EUCNET01316
{
public partial class Survey : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource1.SelectParameters["Category"].DefaultValue = MyParameterValue;
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
public string MyParameterValue {get;set;}
}
}
Then in your ASPX page markup, add a directive to reference to the user control:
<%# Reference Control="~/Usercontrols/Survey.ascx" %>
Then in the codebehind, cast your user control as its type instead of just "UserControl"
Survey ctl = Page.LoadControl("Survey.ascx") as Survey;
// set the property
ctl.MyParameterValue = "foo";
Now in your codebehind you can set the property you created on your user control. Just make sure you set the property BEFORE attempting to load the control into the page's control collection (at which point the lifecycle will try to "catch up," and your control's page_load will fire prior to the property being set).

Simple ASP.NET File Upload

I have a very simple ASP.NET page that uploads an Excel workbook, then processes it. It uses AJAXFILEUPLOAD from the AJAX toolkit on ASP.NET... Here's the markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="ImportWorkbook.aspx.cs" Inherits="Timesheet.ImportWorkbook" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="HeaderContentPlaceHolder">
<h1 class="topContent">
Upload CPAS Timesheet Workbooks
</h1>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightContentPlaceHolder" runat="server">
<br />
<br />
<asp:HiddenField ID="tbTSID" runat="server" />
<asp:HiddenField ID="tbWorkbookPath" runat="server" />
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" AllowedFileTypes="xls,xlsx,xlsm"
CssClass="dropdown" MaximumNumberOfFiles="1" OnUploadComplete="AjaxFileUpload1_UploadComplete" />
<br />
<br />
<asp:Panel ID="ProcessChoices" runat="server" >
<br />
<br />
<p>
Select how you want this workbook processed:</p>
<br />
<asp:RadioButtonList ID="rbChoices" runat="server" BorderStyle="Groove" BorderWidth="2px"
BorderColor="Black" BackColor="Teal" Font-Names="Tahoma" Font-Size="10pt" ForeColor="White"
Width="40%">
<asp:ListItem Value="True" Selected="True">&nbsp Replace ALL Items in the Timesheet</asp:ListItem>
<asp:ListItem Value="False">&nbsp Add Items from this Workbook to the Existing Timesheet Items</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate and Process"
BackColor="#B92217" ForeColor="White" BorderColor="#7C1810"
BorderStyle="Groove" Font-Names="Tahoma" onclick="btnValidate_Click" />
</asp:Panel>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="BottomSpanContentPlaceHolder" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</asp:Content>
The master page and css pages are trivial, formatting only.
Here's the codebehind:
using System;
using System.IO;
using TimesheetUtilites;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
namespace Timesheet
{
public partial class ImportWorkbook : System.Web.UI.Page
{
private const string HDriveLocation= "H:\\mtv\\secure\\Construction\\Access\\CPAS WorkArea\\TimesheetUploads\\";
private string strWorkbookPath;
private int currTSID;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["ID"] != null)
{
tbTSID.Value = Request.QueryString["ID"]; // Storing the Timesheet ID in a hidden Textbox
}
}
else
{
if (!string.IsNullOrEmpty(tbWorkbookPath.Value))
{
ProcessChoices.Enabled = true;
}
}
int.TryParse(tbTSID.Value, out currTSID);
strWorkbookPath = tbWorkbookPath.Value;
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
strWorkbookPath = HDriveLocation + Path.GetFileName(e.FileName);
tbWorkbookPath.Value = strWorkbookPath;
AjaxFileUpload1.SaveAs(strWorkbookPath);
ProcessChoices.Enabled = true;
}
protected void btnValidate_Click(object sender, EventArgs e)
{
bool processOption;
bool.TryParse(rbChoices.SelectedValue, out processOption);
strWorkbookPath = tbWorkbookPath.Value;
TimesheetUtilites.ImportTimesheet imp = new ImportTimesheet(currTSID, strWorkbookPath, processOption);
}
}
}
My issue is simple. Although the event handler "AjaxFileUpload1_UploadComplete" works fine, and uploads the file in an instant, when I fire the "btnValidate_Click" event, the "tbWorkbookPath.Value" has become an empty string, and the "ProcessChoices.Enabled" propety doesn't change. Needless to say, the "Upload Complete" event handler is the only opportunity I have to capture this file path, so I'm at a loss what I'm doing wrong.
I posted on ASP.NET and go NO answers. Can anyone give me an idea where to start?
This is information you should be storing in your page's ViewState so that it persists between postbacks and resets on page initialization. Change your private string member to something like the following:
private string strWorkbookPath {
get {
return this.ViewState["strWorkbookPath"];
}
set {
this.ViewState["strWorkbookPath"] = value;
}
}
If you need a primer on what the ViewState is, check out this article on MSDN: Saving Web Forms Page Values Using View State. It's a bit dated but still communicates the basics of how ViewState operates currently.
Put a hidden field with runat="server" attribute on your page and use the below script:
<script type="text/javascript">
function uploadComplete(sender, args) {
var filename = args.get_fileName();
$("#hiddden_field_id").val(filename);
}
</script>
Now you should be getting the image name in your events.
I think you should try storing that value in session rather than a hidden field as the page is not reloaded and it was an ajax call. So when the button is clicked for validation, it is actually another request made but the value of the hidden field in this page object and the hidden field is still empty. Once your job is done for that value in session, remove it from there or set it to some different value.

Strange Behaviour System.NullReferenceException on crosspage postback with Master Page

I am using C# ASP.NET , i did a crosspage postback and it is working fine, without master page.
But while using Master page , same logic fails and get the error described above. I am new to ASP.NET, please tell me in little detail.
My code is
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="View_Information.aspx.cs" Inherits="View_Information" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<p>
Module 3: Assignment 1</p>
<div>
Total Data You Have Entered
<br />
<br />
Name:
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<br />
Address:
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
<br />
Thanks for submitting your data.<br />
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Placehodler2" Runat="Server">
</asp:Content>
And code behind is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class View_Information : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage.IsPostBack)
{
TextBox nametextpb = (TextBox)PreviousPage.FindControl("TextBox1");
//Name of controls should be good to identify in case application is big
TextBox addresspb = (TextBox)PreviousPage.FindControl("TextBox2");
Label1.Text = nametextpb.Text; //exception were thrown here
Label2.Text = addresspb.Text;
}
else
{
Response.Redirect("Personal_Information.aspx");
}
}
}
The problem is that, with the master page, your controls are now required to be placed in the ContentPlaceHolder controls.
The FindControl method can be used to access a control whose ID is not
available at design time. The method searches only the page's
immediate, or top-level, container; it does not recursively search for
controls in naming containers contained on the page. To access
controls in a subordinate naming container, call the FindControl
method of that container.
You now need to recursively search through the controls to find your TextBox controls from the PreviousPage. You can see an example of that here. Also noted on that site, you can get the control by its full UniqueID, which in your case will work via:
TextBox nametextpb = (TextBox)PreviousPage.FindControl("ctl00$ContentPlaceHolder1$TextBox1")
EDIT: Figured it couldn't hurt to include the code I used to locate the UniqueID of the target control.
In Page_Load:
var ids = new List<string>();
BuildControlIDListRecursive(PreviousPage.Controls, ids);
And the method definition:
private void BuildControlIDListRecursive(ControlCollection controls, List<string> ids)
{
foreach (Control c in controls)
{
ids.Add(string.Format("{0} : {2}", c.ID, c.UniqueID));
BuildControlIDListRecursive(c.Controls, ids);
}
}
Then just locate your control from the ids list.
(TextBox)PreviousPage.FindControl("TextBox1"); must have returned null, which means that the control was not found.
Try using Page.Master.FindControl() instead.

Categories