What is going on in this ExecuteDataset method? - asp.net

OK so I one page I find this line:
objDsCourse = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings("connstr").ConnectionString, CommandType.StoredProcedure, "Course_NewReportGet_Get_Sav", objPAra)
And I copied it to another page to start modifying it to work there:
getData = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings("connstr").ConnectionString, CommandType.StoredProcedure, "Course_NewReportGet_Get_Sav", objPAra)
However on the new page it underlines .ConnectionStrings saying that Non-invocable member 'System.Configuration.ConfigurationManager.ConnectionStrings' cannot be used like a method'... then why did it work in the other page??
EDIT: OK so I found in web.config what I think it is referencing because it says
<add name="ConnStr" connectionString="data source=..." />
Why would one page have access to this and the other not?

Is there any chance one page is using VB.NET, while the other is using C#?

I would agree with Daniel. In Visual Basic, both dictionary objects and methods are referenced by using parentheses. This can cause some confusion.
So in VB, ConfigurationManager.ConnectionStrings("connstr") would point to the ConnectionString object with the key "connstr" in the dictionary.
In C#, dictionary objects are referenced by square brackets [] so ConfigurationManager.ConnectionStrings("connstr") would literally mean "invoke the method ConnectionStrings of ConfigurationManager object using "connstr" as a parameter."
Long story short, check the <%# Page %> declaration at the top to make sure both pages are the same language. ... or, on the page with the error, change the line to use the ConfigurationManager.ConnectionStrings["connstr"] syntax.

Related

How to pass value from web form to another web form?

Can anybody tell me how to pass a value from one web form to another web form without using a query string and session?
You can pass the Values over different pages via QueryString like:
Response.Redirect("yourNextpage.aspx?identifier=DesiredValue");
On your next page you can retrieve the value like this:
Request.QueryString["identifier"];
Other Preferred way would be Server.Transer() and Postbackurl.
Refer this link for various possible ways.
there are several ways you can pass parameters between pages.
Using a Query String
Getting Post Information from the Source Page
Using Session State
Getting Public Property Values from the Source Page
Getting Control Information from the Source Page in the Same Application
for more detail visit followng link.
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
You could use a Querystring in this case:
Page.Response.Redirect("show.aspx?id=1");
And then read it on the other end:
int id = Page.Request.QueryString["id"];
Using PostBackURL, ex:
PostBackUrl="~/result.aspx"
and on result.cs (Page Load)
lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
With Session:
For example you login the system and your id is 123123123.
string userid = 123123123;
Session["userid"] = userid;
When you go another page/pages your session is alive when your session timeout.
<system.web>
<sessionState timeout="1250"/>
</system.web>
It seems what you're looking for is something like the flash-, view- or conversation scope in Java EE and Ruby on Rails.
For ASP.NET you could perhaps take a look at this one: Is there an equivalent of JSF #ViewScope in ASP MVC?
depends on type and how much information you wish to transfer. for instance, if you want to transfer some variable (strings or integer values) you consider to use querystring (you can found here major information). for instance, if you want to transfer typed objects (class instance) you consider to use session (you can found here major information).

Access compilation element in web.config [duplicate]

Is there any way to access the <compilation /> tag in a web.config file?
I want to check if the "debug" attribute is set to "true" in the file, but I can't seem to figure out how to do it. I've tried using the WebConfigurationManager, but that doesn't seem to allow me to get to the <compilation /> section.
Update:
I know I could easily just load the file like an XML Document and use XPath, but I was hoping there was already something in the framework that would do this for me. It seems like there would be something since there are already ways to get App Settings and Connection Strings.
I've also tried using the WebConfigurationManager.GetSection() method in a few ways:
WebConfigurationManager.GetSection("compilation")// Name of the tag in the file
WebConfigurationManager.GetSection("CompilationSection") // Name of the class that I'd expect would be returned by this method
WebConfigurationManager.GetSection("system.web") // Parent tag of the 'compilation' tag
All of the above methods return null. I'm assuming there is a way to get to this configuration section since there is a class that already exists ('CompilationSection'), I just can't figure out how to get it.
Use:
using System.Configuration;
using System.Web.Configuration;
...
CompilationSection configSection =
(CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" );
You can then check the configSection.Debug property.
TIP: if you need to know how to get a value from a config file, check the machine.config file in your \Windows\Microsoft.net\Framework\<version>\CONFIG folder. In there you can see how all the configuration section handlers are defined. Once you know the name of the config handler (in this case, CompilationSection), you can look it up in the .Net docs.
The easy way to check if you're running in debug mode is to use the HttpContext.IsDebuggingEnabled property. It gets its answer from the compilation element's debug attribute which is the same thing you're trying to do.
After all, you can always load up the Web.config file into an XmlDocument and use an XPath query to find out!
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/Web.config"));
doc.SelectSingleNode("/configuration/system.web/compilation/#debug");
However, I suggest you use the Configuration.GetSection method for solution.
CompilationSection section =
Configuration.GetSection("system.web/compilation") as CompilationSection;
bool debug = section != null && section.Debug;
You can always check debug option on the compiler level by enclosing your code with
#if (DEBUG)
#endif
in case that was the idea...
Try using:
HttpContext.Current.IsDebuggingEnabled
Cant you just load the file up as a regular XML File and use XPath to get the nodes?
Try using the ConfigurationManager.GetSection method.

Resource file for a Custom ASP.net control (.ascx) InvalidOperationException

I have a control containing some text which I want to get from a resx file, I thought I could just create a file called ControlName.ascx.resx but that doesn't seem to be working.
I'm using
label1.InnerText = (string)GetLocalResourceObject("default");
To get the value from the resource file but it keeps throwing up an InvalidOperation Exception.
Am I right about how resx files work or does it only work for Pages?
I have the same code working on an aspx page.
When you call GetLocalResourceObject from within a user control, you are actually calling TemplateControl.GetLocalResourceObject, which will look in the wrong place for the resource file. You need to call HttpContext.GetLocalResourceObject instead.
protected string HttpContextGetLocalResourceObjectAsString(string message)
{
string path = HttpContext.Current.Request.Path;
return (HttpContext.GetLocalResourceObject(path, message) as string);
}
Now you can do
label1.InnerText = HttpContextGetLocalResourceObjectAsString("default");
Per the documentation:
Gets a page-level resource
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.getlocalresourceobject.aspx
Edit- added
It may be less work to just add the string to the web.config and grab it from there.
<configuration>
<appSettings>
<add key="LoggingSystemId" value="B2F085A9-6EC1-4CBF-AF8B-B17BFA75AD81"/>
<appSettings>
...
referenced as follows:
logger.SystemId = System.Configuration.ConfigurationManager.AppSettings["LoggingSystemId"];
Of course, you'll need a reference to the System.Configuration dll.
A year or so later, but i think this is what you're after?
var resource = HttpContext.GetLocalResourceObject(TemplateControl.AppRelativeVirtualPath, termType.ToString());
Mark answer if that's the one!

ASP.NET MVC: Using LINQ to XML to render (X)HTML

There has been a lot of discussions on View-engines for ASP.NET MVC and some criticisms against the inline "tag-soup" with for-loops and thing like it.
The alternative or complement has been to use HTML-helpers, which are just inline method-calls.
When I look inside ASP.NET MVC's HTML-helpers today they are using a class called TagBuilder.
My proposal is to use LINQ to XML to get strongly typed and correctly formatted (X)HTML:
XDocument output = new XDocument();
XElement root = new XElement("div",
new XAttribute("class", "root_item"));
XElement iconImage = new XElement("img",
new XAttribute("src", ResolveUrl("~/image.gif")),
new XAttribute("alt", "This is an image"));
XElement link = new XElement("a",
new XAttribute("class", "link"),
new XAttribute("href", "http://google.com"),
new XText("Link to Google"));
root.Add(link);
root.Add(iconImage);
output.Add(root);
I like it because it's like the strongly typed controls in WebForms, where you can new-up a Button and add it to another control's Control-collection.
Are there any apparent problems or limitations in this?
This is a great idea! The only problem I see with it is the use of C#. ;) VB.NET has much better support for producing XML via it's XML literals feature.
The code you list in your question could be written like this in VB.NET. (With the addition of the text "This is a link" as your example didn't contain any text within the a element.)
Dim root = <div class="root_item">
<img src=<%= ResolveUrl("~/image.gif") %> alt="This is an image"/>
<a class="link" href="http://google.com">This is a link</a>
</div>
There are still <%= ... %> tags, but they are checked for validity at compile time. If this code was made the return value of a function that returned type XElement, then that Xhtml snippet could be reused elsewhere in the site.
I have a project on CodePlex that uses VB.NET XML Literals as a custom ASP.NET MVC View Engine at http://vbmvc.codeplex.com. It is based on code by Dmitry Robsman, who is Product Unit Manager for ASP.NET at Microsoft. Views are VB.NET classes and Master Pages are base classes. You new-up Partial view classes instead of referencing them by a name string, so that is also an additional compile time check. Instead of the HtmlHelper class, which returns strings, there is an XhtmlHelper class which returns XElement and works similarly to what you have proposed.
I can think of two problems to the above mentioned method.
First,
XElement iconImage = new XElement("img",
new XAttribute("src", ResolveUrl("~/image.gif")),
new XAttribute("alt", "This is an image"));
Referring to what you write above, we can have something like:
<img src=<%=whatever%> alt=<%=whatever%> />
This might be personal judgement or what, but I certainly vote the later one more "human" readable. Right, using LINQ 2 XML might get rid of the weird <% } %> that wandering around in my aspx pages, but at the same time, you make those "good boys" looks clumsy.
Second might come with performance issue. I think parsing and executing LINQ 2 XML could be quite slow, although I don't have any data regarding this.
Personally I am still experimenting the MVC framework, it feels like getting back to old days like ASP or PHP 3.X, since almost all the interactive parts are explicitly handled, instead of the window/GUI-OOP oriented ASP Dot Net Framework. I think the main reason I will use MVC is that it can guarantee the best quality client-side HTML codes..

Asp.Net System.Web.Routing Find actual .aspx Page

I'm using System.Web.Routing to have some better URL's and have come across a problem. I need to know the actual page that's handling the request.
for example a request comes in as:
/basketball/home
I need to find the page that handles that request, like:
/management/default.aspx
I'm only using the System.Web.Routing and not MVC. I have a handle to the RequestContext that contains some of the route information, but i don't see what i need.
Thanks in advance.
******* UPDATE *******
I was able to use Context.CurrentHandler which give me "ASP.management_default_aspx", not exactly the page but enough to get the page name.
There is actually another simple way to get the actual page:
String vPath = ((System.Web.Routing.PageRouteHandler)Page.RouteData.RouteHandler).VirtualPath
Do not forget to check Page.RouteData.RouteHandler is not null - while you are getting the page w/o ASP.Net routing but directly.
Can you not retrieve this from the current HttpContext object?
Perhaps something like this:
public string GetCurrentPageName()
{
string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
string sRet = oInfo.Name;
return sRet;
}
UPDATE:
Have you tried this article?
How to: Construct a URL from a Route
You should be able to retrieve it back from the Routing table you have constructed.
vhinn terrible's answer worked...
Page.AppRelativeVirtualPath
You just have to remove the initial tilde ("~"), and you're ready to go.
var path = Page.AppRelativeVirtualPath.Replace("~", String.Empty);
I don't know why it was downvoted. Worked for me like a charm.
Try using this code:
Page.AppRelativeVirtualPath
I was able to use Context.CurrentHandler which give me "ASP.management_default_aspx", not exactly the page but enough to get the page name.

Resources