I have the following code, that uses session but i have an error in the line :
if (Session["ShoppingCart"] == null)
the error is cS0103: The name 'Session' does not exist in the current context what is the problem ?
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.SessionState;
/// <summary>
/// Summary description for ShoppingCart
/// </summary>
public class ShoppingCart
{
List<CartItem> list;
public ShoppingCart()
{
if (Session["ShoppingCart"] == null)
list = new List<CartItem>();
else
list = (List<CartItem>)Session["ShoppingCart"];
}
}
Use
if (HttpContext.Current == null ||
HttpContext.Current.Session == null ||
HttpContext.Current.Session["ShoppingCart"] == null)
instead of
if (Session["ShoppingCart"] == null)
The issue is that your class does not inherit from Page. you need to Change
public class ShoppingCart
to
public class ShoppingCart : Page
and it will work
You either need to convert your class to a Page by inheriting from Page, or have the Session passed in, or use HttpContext.Current.Session.
If you want to use session directly then just simply add following namespace
using system.web.mvc
In my case only try-catch block fix problem, like this:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
/// Using from Try-Catch to handle "Session state is not available in this context." error.
try
{
//must incorporate error handling because this applies to a much wider range of pages
//let the system do the fallback to invariant
if (Session["_culture"] != null)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Session["_culture"].ToString());
//it's safer to make sure you are feeding it a specific culture and avoid exceptions
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Session["_culture"].ToString());
}
}
catch (Exception ex)
{}
}
Related
I'm attempting to implement Model Binding but I'm receiving an error: ModelBindingExecutionContext is a type but used like a variable. Here is my code:
(Should specify this is for ASP.NET Web Form Application not MVC)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.ModelBinding;
protected ActivityBO GetActivity()
{
ActivityBO activity = new ActivityBO();
//IValueProvider provider = new FormValueProvider(ModelBindingExecutionContext);
if (TryUpdateModel(activity, new FormValueProvider(ModelBindingExecutionContext)))
{
return activity;
}
else
{
//Error code will go here.
}
}
System.Stackoverflowexception
using fruittyPie.Models.DataRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace fruittyPie.Models.Other
{
public class CategoryMenu : ViewComponent
{
private readonly ICatagoryRepository _catagoryRepository;
public CategoryMenu(ICatagoryRepository catagoryRepository)
{
_catagoryRepository = catagoryRepository;
}
public IViewComponentResult Invoke()
{
var catagory = _catagoryRepository.Catagories.OrderBy(p => p.CatagoryName);
return View(catagory);
}
}
}
Check that your CategoryView does not use your _Layout.cshtml - otherwise you got an endless loop here. You are returning a View(catagory) which uses your _Layout.cshtml. Your _Layout.cshtml calls CategoryMenu, which returns a View using your _Layout.cshtml.
If that's not the cause than you should debug into your CategoryRepository.
I'm new in programming. I've followed the steps in the book "Pro asp.net 4 in c#2010" to create 2 classes.
Now I try to use this class on a webpage. In the .cs file I added using "DBComponent;" but Visual Studio says "The type or namespace name 'DBComponent' could not be found (are you missing a using directive or an assembly reference?)"
What did I forget?
If i try to add the compiled dll under 'references' i get the error:
The type 'DBComponent.EventDetails' in 'D:_Web\OSWeb\DBComponent\DBComponent\EventDetails.cs' conflicts with the imported type 'DBComponent.EventDetails' in 'D:_Web\OSWeb\DBComponent\DBComponent\bin\Debug\DBComponent.dll'. Using the type defined in 'D:_Web\OSWeb\DBComponent\DBComponent\EventDetails.cs'.
This is what I've done:
Create a new empty website 'OSWeb' in VS
On top of this solution I clicked right and choosed: Add > new Project > Visual C# > Windows > Class library: name: DBComponent and I stored in D:_Web\OSWeb\DBcomponent
List item
I created 2 cs files (EventDB.cs and EventDetails.cs)
my events.cs file
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBComponent
{
public class EventDB
{
private string connStr;
public EventDB()
{...}
public EventDB(string connectionString)
{...}
public int InsertEvent(EventDetails evd)
{...}
}
}
This is my eventdetails.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBComponent
{
public class EventDetails
{
private int eventId;
private string eventName1;
public int EventId { get { return eventId; } set { eventId = value; } }
public string EventName1 { get { return eventName1; } set { eventName1 = value; } }
public EventDetails(int eventId, string eventName1)
{
this.eventId = eventId;
this.eventName1 = eventName1;
}
public EventDetails() { }
}
}
Now I create a new webpage (this is the .cs file of this webpage) (events.aspx.cs)
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBComponent; => here is the error
public partial class events : System.Web.UI.Page
{
private EventDB db = new EventDB(); => here is the same error
protected void Page_Load(object sender, EventArgs e)
{
}
}
try the following:
right click on your web project and click in properties, then click en references. remove the reference of your class, close this windows. Verify in the Bin folder from you proyect, yours references (should not be the reference has been removed.). Next, you open again the project properties and add your class library.
(before adding the reference should be sure that the class library compiles correctly.)
sorry for my english
My project is to write a web service and a web form that consumes it. It should have two text boxes and a button. The user enters an text speak acronym in the first text box and presses the button. The web service compares the textbox1 entry against a dictionary file, and displays the resulting full word in the second text box. This is the code I have so far and I am really struggling to get it to work, any help would be appreciated. At this point I have 'Type or namespace definition, or end of file expected' error. Here are the two files i have.
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
private Dictionary<string, string> _dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
protected void Page_Load(object sender, EventArgs e)
{
using (var reader = new StreamReader(File.OpenRead(#"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(';');
_dictionary[tokens[0]] = tokens[1];
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
localhost.Service obj = new localhost.Service();
TextBox1.Text = (obj.Translate());
}
}
Service.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string Translate(string input)
{
string output;
if(_dictionary.TryGetValue(input, out output))
return output;
// Obviously you might not want to throw an exception in this basis example,
// you might just go return "ERROR". Up to you, but those requirements are
// beyond the scope of the question! :)
throw new Exception("Sinatra doesn't know this ditty");
}
}
}
Not sure if the question is still unanswered. But here are my suggestions.
In the web service file i.e. say Service1.cs you are not declaring the _dictionary object. So you will be moving the dictionary object declaration and initialization in the constructor of the service.
Some thing like this below.
public WebService1()
{
using (var reader = new StreamReader(File.OpenRead(#"C:/dictionary.csv")))
{
while (!reader.EndOfStream)
{
string[] tokens = reader.ReadLine().Split(',');
_dictionary[tokens[0]] = tokens[1];
}
}
}
Also in the split method I would assume you wanted to use the comma instead of the semicolon(that was used in your sample).
And then in the consumption of the service, you would do some thing like this below. I was not sure what you were trying to do using the localhost object in your sample.
ServiceReference1.WebService1SoapClient obj = new WebService1SoapClient();
TextBox2.Text = obj.Translate(TextBox1.Text);
Hope this helps.
-Davood.
I am working on a Web Application and i want that when the user logged In the UserID should be stored in Session. I know how to create Session.
Session["UserID"] = myvalue;
But i want that to be used on everypage. so i dont want to write code or check for session availability on every page. will Global.asax file help me ?
If i write session in Session_Start() then will that be accessible on all pages ? and if expired the return to login page.
Just require proper guidance. Thanks
I used to write as a separate class to handle session and return it as a property. I can write all the condition in the class.
I highly suggest creating a basepage that is inherited by every page but the login. this way you are only creating the session variable code on one page but that code is accessible by any page that inherits it.
edit with small example:
when your user is authenticated you need to set your session variable
currently your pages probably look something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
what you need to do is create a separate class file, basepage.cs for example that looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public class basepage : System.Web.UI.Page
{
protected int GetItem()
{
return Convert.ToInt32(Session["myvalue"]);
}
}
}
and then your original page would look more like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : basepage
{
protected void Page_Load(object sender, EventArgs e)
{
int whatINeed = GetItem();
}
}
}
as you see instead of your page inheriting the System.Web.UI.Page it is inheriting the basepage (which in turn inherits System.Web.UI.Page).