Share variable across site ASP.NET - asp.net

I have a class isSearching with a single boolean property in a 'functions' file in my webapp. On my search page, I have a variable oSearchHandler declared as a Public Shared variable. How can I access the contents of oSearchHandler on other pages in my webapp?
Code with Session....
'search.aspx
Public Function oSearchString(ByVal oTextBoxName As String) As String
For Each oKey As String In Request.Form.AllKeys
If oKey.Contains(oTextBoxName) Then
Session.Add("searching", True)
Session.Add("search-term", Request.Form(oKey))
Return Request.Form(oKey)
End If
Next
Return ""
End Function
'theMaster.master
<%
If Session("searching") Then
%><ul style="float: right;">
<li>
<div class="gsSearch">
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</div>
</li>
<li>
<div class="gsSearch">
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="true" PostBackUrl="search.aspx" CssClass="searchBtn" />
</div>
</li>
</ul>
<%
End If
%>
I think that the session will work just fine.

If you're talking about accessing these variables between page interactions, you need to bear in mind that the state is discarded between pages.
Instead, you need to store this data in Session State.
If it's not across page interactions, but simply accessing the data from other parts of the code, the key is that the ASP.NET page becomes a class and your public shared variable, a static property of that class.
So, you'd access it from elsewhere using PageName.oSearchHandler
[EDIT] Can you give us some more information about what oSearchHandler is and how you're intending using it? We can probably offer a more considered recommendation, then.

If you want it accessible from multiple pages you should pull it off that individual page class and put it in a more globally accessable place such as the Application collection. Given the naming of the variable, is 0SearchHandler a delegate? I'm not as familiar with VB.NET as much or the terminology.
Update: Steve Morgan mentioned using the Session collection, when "static" or "shared" was mentioned, i was thinking more globally. Depending on how your using the variable you can use the "Application" if it will be shared between users and sessions, or the "session" if it will be used by one user in one session. In VB.NET they are both easy to use:
Session("yourKey") = YourObjectYouWantToSave
Application("yourKey") = YourObjectYouWantToSave
Very simple stuff.
'search.aspx
Public Function oSearchString(ByVal oTextBoxName As String) As String
For Each oKey As String In Request.Form.AllKeys
If oKey.Contains(oTextBoxName) Then
Session("searching") = True
Session("search-term") = Request.Form(oKey)
Return Request.Form(oKey)
End If
Next
Return ""
End Function
' theMaster.master.vb
In PageLoad Method:
...
Dim bSearching as Boolean
bSearching = IIf(Session("searching") is Nothing, False, Session("searching") )
ulSearch.visible = bSearching
...
'theMaster.master
<ul style="float: right;" runat="server" id="ulSearch">
<li>
<div class="gsSearch">
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</div>
</li>
<li>
<div class="gsSearch">
<asp:Button ID="searchbutton" runat="server" Text="search" UseSubmitBehavior="true" PostBackUrl="search.aspx" CssClass="searchBtn" />
</div>
</li>
</ul>
Ok, that is some extra code but I think you would have less problems with it. Plus my VB is a bit rusty. Actually, If the master page is the page you will be using it on, I would put the variable as a public property on that masterpage. You can access the pages master page with this.Master (at least in C#, I think it's Me.Master in VB.NET).

Related

Display First Name instead of UserName in welcome greeting of VB Web Form App

The stock visual basic web forms app template in Visual Studio 2017 displays a welcome message with the UserName field displayed (i.e. "Hello, abc#123.com"). I need to display it with the FirstName field displayed instead (i.e. "Hello, John).
There are numerous other posts about this but none of them have solved my problem. I have added the FirstName property to the identitymodels.vb file as follows:
Private FName As String
Public Property FirstName() As String
Get
Return FName
End Get
Set(ByVal value As String)
FName = value
End Set
End Property
However, the FirstName property does not seem to be exposed in the sitemaster.aspx file. I have also tried FName with the same results.
Currently in the sitemaster.aspx file the UserName is displayed by:
<li>
<a runat="server" href="~/Account/Manage" title="Manage your account">Hello, <%: Context.User.Identity.GetUserName() %>!</a>
</li>
I need something like,
<li>
<a runat="server" href="~/Account/Manage" title="Manage your account">Hello, <%: Context.User.Identity.GetFirstName() %>!</a>
</li>
but the "GetFirstName part does not work. I assume that GetUserName is a predefined method and I need to be able to predefine a new method that returns the FirstName field instead of the the UserName field.
When the user logs in you can display the profile information by doing the following:
Add a function in the code behind of Site.Master to get the User object:
Protected Function Get_Current_User() As ApplicationUser
Dim manager = New UserManager(Of ApplicationUser)(New UserStore(Of ApplicationUser)(New ApplicationDbContext()))
Dim currentUser = manager.FindById(Context.User.Identity.GetUserId())
Return currentUser
End Function
Invoke it in your markup:
<li>
<a runat="server" href="~/Account/Manage" title="Manage your account">
Hello, <%: Get_Current_User().FirstName %>!
</a>
</li>
You need the following imports for the above code to work:
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
As a reference, here's an article that describes it nicely (in C#):
Customizing profile information in ASP.NET Identity in VS templates

How to build an infinite tree hierarchy?

I've been working on this since yesterday and I'm completely stumped. I'm working in VB.NET but I can understand C# if you'd prefer to answer it that way.
Basically I have items from a SQL database with IDs and parent IDs and I need to put them in a tree like so:
<ul>
<li>Some item
<ul>
<li>Another item
<ul>
<li>This could go forever
<ul>
<li>Still going</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
Currently I have a nested repeater which works but it only gets me to the second level. It looks something like this:
<asp:Repeater ID="parent" runat="server">
<ItemTemplate>
<ul>
<li><span><%#Container.DataItem("Name")%></span>
<asp:Repeater ID="child" DataSource='<%#CType(Container.DataItem, DataRowView).Row.GetChildRows("relation")%>' runat="server">
<ItemTemplate>
<ul>
<li><span><%#Container.DataItem("Name")%></span></li>
</ul>
</ItemTemplate>
</asp:Repeater>
</li>
</ul>
</ItemTemplate>
</asp:Repeater>
The relation is like this:
ds.Relations.Add("relation",
ds.Tables("Items").Columns("ID"),
ds.Tables("Items").Columns("ParentID"),
False)
I understand why it won't work because it doesn't have a template to continue the tree. So I'm trying to figure out a way around that.
I've considered writing a function to just build the string in the code behind and stick it in the html with an asp tag. I wasn't sure how to go about this while pulling the data out of the database.
I found a temporary solution though it's extremely inefficient. In case anyone stumbles across my question this will at least get you by. For large amounts of data it could take up to a full minute to load.
If anyone could comment on how to make this more efficient that would be nice.
Code behind:
Private Dim dt As New DataTable
Public Function BuildTree(ByVal ID As String) As String
Dim sb As New StringBuilder
dt = YourDatabase.GetChildren(ID) '<-- You'll have to write this function
sb.AppendLine("")
If dt.Rows.Count > 0 Then
sb.AppendLine("<ul>")
If dt.Rows.Count > 1 Then
For Each row As DataRow In dt.Rows
sb.AppendLine("<li>" & row("ItemName"))
' Recursive call
sb.AppendLine(BuildTree(row("ID").ToString))
sb.AppendLine("</li>")
Next
Else
sb.AppendLine("<li>" & dt.Rows(0)("ItemName").ToString & "</li>")
End If
sb.AppendLine("</ul>")
End If
Return sb.ToString
End Function
Then in your aspx page do something like this:
<%#BuildTree(Container.DataItem("ID").ToString)%>
EDIT: Declaring the DataTable outside of the function helps the efficiency a bit.

ASP.NET MVC: on button click, call display multiple ActionResults in different windows

I have a form that has a drop-down list of values and a submit button.
Currently, when you click on the submit button, a stored procedure is called and then the application generates a url and then the ActionResult is a Redirect to a new window. The url is based on the currently selected value in the dropdown list.
Our client wants another button that when clicked, will basically do the same thing, but FOR ALL VALUES in the drop down list.
Basically, on click, multiple windows will be opened, whose urls each based on a value in the drop down list.
I just started working with MVC and research confused me even more. I'm hoping someone can point me in the right direction.
Should I handle this via some sort of loop in javascript? How? Can you give some examples, please?
ASPX Portion:
<div id="MyContainer" class="select-report">
<%
using (Html.BeginForm(MyManager.Query.Actions.GenerateReport(null), FormMethod.Post, new{target="_blank"}))
{%>
<select name="SearchText" class="my-values-select">
<% foreach (var cc in Model.MyCentresList)
{%>
<option value="<%=Html.Encode(cc.Name) %>">
<%=Html.Encode(cc.Name) %></option>
<% } %>
</select>
<input type="hidden" name="SearchType" value="MyCentre" />
<input type="submit" value="Generate" name="EntityName" />
<% } %>
</div>
Code-Behind:
public virtual ActionResult GenerateReport(GenerateReportOperation operation)
{
string entityName = operation.SearchText;
int entityType = (int)operation.SearchType;
string requestID1 = <code here that calls a stored procedure, a value is returned>;
string requestID2 = <code here that calls a stored procedure, a value is returned>;
string urlString = <code here that contructs the URL based on the values of entityName, entityType, requestID1, requestID2>;
return Redirect(urlString);
}
You would have to use JavaScript to open new windows for each individual HTTP request.

Formatting Controls in ASP.NET

I feel as though this this is a simple question, but can't find an answer anywhere. We've got an interface we're trying to move to an ASP.NET control. It currently looks like:
<link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLayout.css"" />
<script type=""text/javascript"" src=""../../Scripts/vcaptcha_control.js""></script>
<div id="captcha_background">
<div id="captcha_loading_area">
<img id="captcha" src="#" alt="" />
</div>
<div id="vcaptcha_entry_container">
<input id="captcha_answer" type="text"/>
<input id="captcha_challenge" type="hidden"/>
<input id="captcha_publickey" type="hidden"/>
<input id="captcha_host" type="hidden"/>
</div>
<div id="captcha_logo_container"></div>
</div>
However all the examples I see of ASP.NET controls that allow for basical functionality - i.e.
public class MyControl : Panel
{
public MyControl()
{
}
protected override void OnInit(EventArgs e)
{
ScriptManager.RegisterScript( ... Google script, CSS, etc. ... );
TextBox txt = new TextBox();
txt.ID = "text1";
this.Controls.Add(txt);
CustomValidator vld = new CustomValidator();
vld.ControlToValidate = "text1";
vld.ID = "validator1";
this.Controls.Add(vld);
}
}
Don't allow for the detailed layout that we need. Any suggestions on how I can combine layout and functionality and still have a single ASP control we can drop in to pages? The ultimate goal is for users of the control to just drop in:
<captcha:CaptchaControl ID="CaptchaControl1"
runat="server"
Server="http://localhost:51947/"
/>
and see the working control.
Sorry for the basic nature of this one, any help is greatly appreciated.
Although you may want to look into user controls, the following page has an example of doing this using a web control. http://msdn.microsoft.com/en-us/library/3257x3ea.aspx The Render() method does the output of the actual HTML for the control.
There are a couple of ways to do it. You can make a custom control, or a user control. I think you will find it easier to do a user control. It lets you lay out parts of your control as you would a regular page. Here is some example documentation: http://msdn.microsoft.com/en-us/library/26db8ysc(VS.85).aspx
By contrast a custom control typically does all of the rendering in code (as your example you show). It is harder to make your first control in this way.

custom controls and query string(asp.net)

How to call a custom control when query string is changed?
My example not work?Why?
<% if(Convert.ToInt32(Request.QueryString["id"])==6){ %>
<answer:answer_n id="give_me_top_five_news" runat="server" />
<%} %>
<% if(Request.QueryString["do"]=="registracija"){
Page.Header.Title = "HHHHH";
%>
<reg:f_reg id="custom_controls_for_registration" runat="server" />
<%} %>
Changed in what fashion? Anytime you load the page with a new URL and query string, the page will be loaded for the first time. You would have to save the info you wanted to store in the Session (for example) and then in the Page_Load event check the query string vs the Session variable to see if they are the same or different.
There may be different ways to do it, but that's what comes to mind off the cuff.

Resources