NullReferenceException on web user control - asp.net

First time posting. :)
I'm a pretty new developer so I'm not well versed in common ASP.NET problems.
As a test, my boss asked me to convert a (not very critical) ASP.NET site from 1.1 to 4.0. Well, it's not extremely difficult and things are going well so far. However, I've hit a small snag. I keep getting a NullReferenceException when I run this code:
Public Property PageTitle() As String
'===========================================================================
'Exposes the PageTitle property of the child control.
'===========================================================================
Get
Return lblPageTitle.Text
End Get
Set(ByVal Value As String)
'TODO: find out why this throws a NullReference exception
lblPageTitle.Text = Value
End Set
End Property
The Value part does have a string attached to it (literally :) but the lblPageTitle just won't set right.
More background if this helps: Before, this web user control had these in the codebehind, but they started throwing errors because they were already declared. Anyways, here they are:
Public Shared lblPageTitle As New Label
Public Shared lblUser As New Label
Public Shared lblLastLogin As New Label
Public Shared lblToday As New Label
Public Shared lblSiteTitle As New Label
Obviously, the New keyword might have helped in this situation somehow, but none of those other labels have caused any trouble.
I've tried doing this but it didn't work:
Dim PageTitle As New Label
PageTitle = TryCast(ucPageHeader.FindControl("lblTitle"), Label)
If Not IsNothing(PageTitle) Then
PageTitle.Text = sb.ToString()
End If
Any ideas?

Those declarations you deleted are required SOMEWHERE. I've got a feeling you're using a web application project and your .designer.vb file has somehow got out of date. As a quick fix, toggle "Show all files" in your solution explorer (it's a little toolbar button just up on the top leftish of your sidebar) and expand the arrow beside the .ascx file you're working on. You should see a .ascx.vb file and a .ascx.designer.vb file. Without going into too much more detail, try deleting the designer.vb file, then right clicking on the .ascx and selecting "Convert to web application". Visual Studio will recreate your .designer.vb, hopefully with all control references intact.
Recommended reading: Code-Behind with VS 2005 Web Application Projects. It's for ASP.NET 2.0 but the same basic principles apply.

Related

How do I run code at client start (Not at page open) in Blazor

I need to run some code to get a user's username and department when they first connect to my Blazor Server Side application. I could just do this using OnInitialized() but that appears to only work on the one page in which it was placed. Users will likely be sent separate links to different pages though and I don't want to have to place this code on every page. I discovered that I can place code in my main layout and it will run no matter what page I start on but it runs on every page change and it doesn't allow me to run things asynchronously so that's not ideal. I'm looking for something like a Global.asax but in Blazor if that makes sense.
Edit: Turns out I can run things asynchronously in my layout! I just needed to create a code block like any other razor page. Makes sense. Though It's still weird that we have to put this type of code in the layout. It just doesn't feel right.
This is what I do:
Create a state object (class) that can be injected where needed. This is somewhat like session, but can also have global events. See here.
Add it to IoC in Startup.cs. Background info here
services.AddScoped<MyState>();
Initialize it in MainLayout.razor or elsewhere:
if (MyState.User == null)
{
MyState.User = authService.User;
}
Instantiate in pages/components as needed:
[Inject]
public MyState myState { get; set; }
...
myObj.CreatedBy = myState.User.UserName;

Code Behind No Longer finds ID tags

I've been working on a website for several months now and am nearing my deadline. I know my methods are a little dated. Especially considering I still use tables. I've actually moved in a direction away from that, but this project is being produced from an excel spreadsheet and with more than 200 fields, it seems reasonable and the person I'm creating this for was happy to see the recreation.
Nevertheless, I am having an issue where I have declared an id for an asp TableCell and am trying to assign text to it. In the past this has worked. Literally every other page I have built has been able to accept this code.
Initially I had a textbox named "depthSingleUnit." With new data coming in, I realized I could combine the depth, height, and width information into one cell. And because I don't want the user to edit this data any longer, just view the information that's already available, I dropped the idea of using a textbox and just used the tablecell to display the information.
The tablecell now has an id "dimensionsSingleUnit"
<asp:TableCell columnspan="1" id="dimensionsSingleUnit"></asp:TableCell>
The code behind reads
dimensionsSingleUnit.Text = PONDS.Tables(0).Rows(0).Item("ProductDimensions")
Yet I get the error
Error 3 'dimensionsSingleUnit' is not declared. It may be inaccessible due to its protection level. C:\Users\aking\My. Documents\Visual Studio 2012\Projects\lampSpecs\lampSpecs\Factories\view.aspx.vb 289 4 lampSpecs
Am I missing something here? I have tried changing the id. I've tried creating a new tableCell with the same name. Tried creating a new tableCell with a different name. I tried creating a new file, but still have the same issue. I've tried re-building the project. I literally copy and paste the id into my code behind and that does not work.
The old ids from when I was using multiple cells for the data are still available, but all of the new ones that I've added will not display in intellisense and displays an error.
you need to add runat="server" to your html element to get access it from code page. because only runat="server" are available on the code behind page
Sorry meant to add as an answer....
Try
dimensionsSingleUnit.InnerHtml = PONDS.Tables(0).Rows(0).Item("ProductDimentiond")
I've not worked with tables cells in this way normally use gridviews or repeaters. It may be that a runat="server" for the table element is enough... but usually you need it for any html elements to be accessible from code

Unable to render the HTML output on a Page

I am trying to build SPGridView on aspx.cs
Below is the code
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<SharePoint:SPGridView runat=\"server\" ID=\"spgridview\" AutoGenerateColumns=\"false\" AllowPaging=\"true\" AllowSorting=\"true\" Visible=\"true\">\n");
sb.AppendFormat("<Columns>\n");
sb.AppendFormat("<asp:TemplateField>\n");
sb.AppendFormat("<ItemTemplate>\n");
sb.AppendFormat("<asp:Label ID=\"lblNo\" runat=\"server\" Text=\"First\"/>\n");
sb.AppendFormat("</ItemTemplate>\n");
sb.AppendFormat("</asp:TemplateField>\n");
sb.AppendFormat("<asp:TemplateField>\n");
sb.AppendFormat("<ItemTemplate>\n");
sb.AppendFormat("<asp:Label ID=\"lblName\" runat=\"server\" Text=\"Janaki\"/>\n");
sb.AppendFormat("</ItemTemplate>\n");
sb.AppendFormat("</asp:TemplateField>\n");
sb.AppendFormat("</Columns>\n");
sb.AppendFormat("</SharePoint:SPGridView>\n");
I tried Response.Write(sb.ToString());, There is nothing on the page. How can I get this working. Maybe I am missing something..Please let me know.
You cannot dynamically render controls this way; this is not supported, and will render as plain HTML. You have to have them statically defined on the page, or load them by adding them to the controls collection or a parent control.
Everything in your string builder is a Server Side control. This means that if you try to write it out when rendering the page, you will get nothing at best or get an error at worst since the browser has no idea what a .NET control is.
If you want to add controls from the code behind you will need to use Page.Form.Controls.Add() or something similar to do it.
Based on your code it seems like you could just include the contents of your string builder in the aspx page and set Visible to false or true depending on your needs.

Generation of designer file failed: Could not load file or assembly

I have an ASP.NET web application project which references another project called ModusCore (or Modus.Core). We've had a variety of controls that use ModusCore up until now with no problem, but there's one I created lately that's been causing trouble. Here's the code:
public class PortalLinkNew : WebControl
{
public string Text { get; set; }
public bool AllowPush { get; set; }
public PortalLinkNew()
{
AllowPush = true;
}
public IChannelRequest ChannelRequest { get; set; }
protected override HtmlTextWriterTag TagKey
{
get { return HtmlTextWriterTag.A; }
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
try
{
base.AddAttributesToRender(writer);
if (DesignMode || Page == null || !(Page is IPortalPage))
{
return;
}
string href = "/";
if (ChannelRequest != null)
{
var portalPage = (IPortalPage)Page;
href = portalPage.Module.PortalRouter.GetLinkUrl(portalPage, ChannelRequest, AllowPush);
}
writer.AddAttribute(HtmlTextWriterAttribute.Href, href);
}
catch (Exception)
{
}
}
public override void RenderEndTag(HtmlTextWriter writer)
{
writer.Write(Text);
base.RenderEndTag(writer);
}
}
In the above code, IPortalPage and IChannelRequest are interfaces defined in Modus.Core.
My intent is to use this control in my code as follows:
<tnl:PortalLinkNew ID="CancelButton" runat="server" Text="Cancel" OnInit="CancelButton_Init" />
This actually compiles and runs without a problem, but when I'm editing the page (source view) in Visual Studio 2008, I get the following warning:
Generation of designer file failed: Could not load file or assembly 'Modus.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
As it says, it doesn't regenerate the designer file, meaning any attempt to refer to the CancelButton control in code-behind results in a compiler error. Following advice I've found online, I've tried deleting the corresponding .ascx.designer.cs file and using "Convert to Web Application" on that page, but it tells me that it cannot rebuild the designer file for the same reason mentioned above.
I've tried everything I can think of: cleaning the solution, restarting Visual Studio, rebooting my computer, deleting the code directory and pulling it fresh from the repository, removing and re-adding the project and dll references, etc. The same problem occurs on multiple computers I use.
How can I get the VS designer to stop failing?
I have a very similar problem (which I could not solve yet). The Application I have the problem with was converted from a "Web Site Project" though and I can't get rid of the feeling that this has something to do with it. And I am on VS 2005.
Now what I can add is that
a) "sometimes" (I could not figure out when exactly yet) the "Convert to Web Application"-trick works for me (but not always)
b) "sometimes" (same as above) it helps to switch to the designer view, change something and save -> *.designer.cs gets regenerated
I usually try several things in no fix order after I added a control to my page until "something" works.
There is a lot of noise about this on the internet but I could not find a "real fix" for it (yet). One thing I read besides the already mentioned is that it could have something to do with (not matching/not existing) namespaces.
When I checked my application there really were no namespace declarartions in the *.cs-files. So I added them (in *.cs and *.aspx) and for some time thought it did the trick. But sadly by now I know that this was not the case...
My solution:
Close and reopen Visual Studio.
Is your problem fixed? If not, go to 1.
Adding a third option for when #scherand's (a) and (b) fail:
c) "Sometimes", this works as well:
Remove the <%# Register... %> entries
Save the .AS?X file. Let the designer complain.
Add the <%# Register... %> again
Save again
[Added Oct-13-2010]:
d) "Sometimes", as well:
Clear the AS?X file off all but the most basic content.
Start adding pieces back, one bit a time.
Save.
Check that you didn't get the error message.
Add back a few more pieces. Rinse. Repeat.
I use a text comparison tool against a back up copy of the AS?X file for this.
I try to avoid adding the controls that cause the error until the very end. I also try to add from the bottom of the page. However, I don't know of a hard rule. It's a gut-feeling exercise.
(Will someone ever figure this one out?)
I've been struggling with this problem all day, and you wouldn't believe what the culprit was. I disabled ReSharper 5.0 and all of a sudden the errors went away. Unbelievable.
Another solution I have found to be effective in Visual Studio 2015 is to close VS and then clear out the following directories:
%UserProfile%\AppData\Local\Temp\Temporary ASP.NET Files\
%UserProfile%\AppData\Local\Microsoft\VisualStudio\14.0\ProjectAssemblies\
Open your solution again and select Build->Clean Solution.
Now go to your ASPX page, and then select Project->Convert To Web Application
Copying the missing assemblies into the Visual Studio\Common7\IDE\Public Assemblies directory gave me more specific error messages than 'could not load file or assembly'. From here I commented out some problematic parts of the page, deleted the .designer.cs file and chose "Convert to Web Application" from the right-click context menu of the .ascx file.
Well, I've had this very problem for two days. As far as no proposed solution completely solved the problem (it looks very... erratic), I reached the Assembly Information button (or something similar... my VS is in Spanish) in the Application Tab of the project properties. I've only changed the Neutral Language... and now it deploys correctly.
I have no idea of the correlation, but I reached here after seeing how some errors, related to the assembly information were displayed on the console after "converting to Web Application".
To ensure that your web application is OK to deploy, you can see the first lines of the aspx files and check if all CodeFiles are CodeBehind instead. If you see "Codefile=...", it will fail on the deployment machine.
Sorry for not being more explicit, but this is a weird issue to me :S
I had a similar issue but with assemblies that we had created. In our case the version number was very specific, so this may not work if all your files say 1.0.0.0.
First of all, delete the designer file for the problematic aspx file. Right-click the aspx file and select "Convert to Web Application", similar to what others suggested. Doing it on the file is faster and you get a popup with the error instead of a warning you have to look for. In our case the error was Generation of the designer file for OurPage.aspx failed: Could not load file or assembly 'OurCustomAssembly, Version=1.0.234.567...
What I then did is use a tool that searches file contents (e.g. Agent Ransack) and pointed it to our source folder (which also has the build/cache files) and searched for files "containing text" with the specific version. For each of the projects that came up, I removed the reference to the assembly that was failing, re-added it, then rebuilt the individual project. Searching again showed that the version was gone.
I ran Convert to Web Application again and now got the same error but with a different file. This time none of the above worked. I was able to determine that only some of the Register tags were problematic. I removed those register tags, created protected variables on the page's code-behind (since they weren't in the designer file) and recompiled the solution. Afterwards I removed the variables I had created, saved, readded all the Register tags, saved. At that point the designer file generated successfully.
There may be a more straightforward way to do all this, but that's what ended up working for me. Time will tell, but hopefully this is a permanent fix.
I'm using ReSharper Platform 6. I was able to resolve this issue by doing the following:
ReSharper (Menu Bar) > Options...
Environment > General > Clear Caches
Restart Visual Studio

MVVM Light + Blend designer view error: Cannot find resource named 'Locator'.

The application runs fine but i could not see my design in the designer view.
It says Cannot find resource named 'Locator'. Obviously, i did not change anything in the code, i just did the data binding using the data binding dialog...
anyone facing the same problem?
There are two known occurrences where this can happen.
If you change to Blend before you built the application, the DLLs are not available yet and this error can be seen. Building the application solves the issue.
There is a bug in Expression Blend where, if you are placing a user control in another user control (or Window in WPF), and the inner user control uses a global resource, the global resource cannot be found. In that case you will get the error too.
Unfortunately I do not have a workaround for the second point, as it is a Blend bug. I hope we will see a resolution for that soon, but it seems to be still there in Blend 4.
What you can do is
Ignore the error when working on the outer user control. When you work on the inner user control, you should see the design time data fine (not very satisfying I know).
Use the d:DataContext to set the design time data context in Blend temporarily.
Hopefully this helps,
Laurent
I've come up with a reasonably acceptable workaround to this problem since it doesn't appear to have been fixed in Blend 4:
In the constructor for your XAML UserControl just add the resources it needs, provided you're in design mode within Blend. This may be just the Locator, or also Styles and Converters as appropriate.
public partial class OrdersControl : UserControl
{
public OrdersControl()
{
// MUST do this BEFORE InitializeComponent()
if (DesignerProperties.GetIsInDesignMode(this))
{
if (AppDomain.CurrentDomain.BaseDirectory.Contains("Blend 4"))
{
// load styles resources
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(System.IO.Path.Combine(Environment.CurrentDirectory, "Resources/Styles.xaml"), UriKind.Absolute);
Resources.MergedDictionaries.Add(rd);
// load any other resources this control needs such as Converters
Resources.Add("booleanNOTConverter", new BooleanNOTConverter());
}
}
// initialize component
this.InitializeComponent();
}
There may be some edge cases, but its working OK for me in the simple cases where before I'd get a big red error symbol. I'd LOVE to see suggestions on how to better solve this problem, but this at least allows me to animate user controls that otherwise are appearing as errors.
You could also extract out the creation of resources to App.xaml.cs:
internal static void CreateStaticResourcesForDesigner(Control element)
{
if (AppDomain.CurrentDomain.BaseDirectory.Contains("Blend 4"))
{
// load styles resources
ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(System.IO.Path.Combine(Environment.CurrentDirectory, "Resources/Styles.xaml"), UriKind.Absolute);
element.Resources.MergedDictionaries.Add(rd);
// load any other resources this control needs
element.Resources.Add("booleanNOTConverter", new BooleanNOTConverter());
}
}
and then in the control do this BEFORE InitializeComponent():
// create local resources
if (DesignerProperties.GetIsInDesignMode(this))
{
App.CreateStaticResourcesForDesigner(this);
}
Note: At some point in time this stopped working for me and I ended up hardcoding the path to the Styles.xaml because I got frustrated trying to figure out which directory I was in.
rd.Source = new Uri(#"R:\TFS-PROJECTS\ProjectWPF\Resources\Styles.xaml", UriKind.Absolute);
I'm sure I could find the right path with 5 minutes work, but try this if you're at your wits end like I was!
In MyUserControl.xaml, instead of:
DataContext="{Binding Main, Source={StaticResource Locator}
use:
d:DataContext="{Binding Main, Source={StaticResource Locator}
where "d" has been previously defined as:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
The reason and workaround explained here
http://blogs.msdn.com/b/unnir/archive/2009/03/31/blend-wpf-and-resource-references.aspx
Look at (b) part of the post.
I had a similar problem with a user control resource.
I added this in my usercontrol xaml code:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/GinaControls;component/Resources/GinaControlsColors.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
Where GinaControls is the namespace where the control class is declared and /Resources/GinaControlsColors.xaml is the project folder and xaml resource file name.
Hope this helps.
Just add this in your App.xaml.cs at the very beginning
here's my piece of code
[STATThread()]
static void main(){
App.Current.Resources.Add("Locator", new yournamespace.ViewModel.ViewModelLocator());
}
public App(){
main();
}
Make sure the Blend has opened the entire solution and NOT just the single project containing the views. I was right-clicking in Visual Studio and selecting Open In Expression Blend. To my surprize, Blend could not find the solution file, so it only opened the single project.
When I realized this, I launched Blend directly, pointed it to the solution file, and then Blend was able to find the ViewModelLocator in my view.

Resources