Changing Entity connection string error - asp.net

I am having a problem when changing the model entities connection string,
when a user first logs in the KurtDBEntities conection string is being chosen properly
but when logging in as an admin if (daRoles.IsUserInRole(User, 1)) or any other instance it is giving me this error:
System.InvalidOperationException was unhandled by user code
Message=No modifications to connection are permitted after the metadata has been registered either by opening a connection or constructing the connection with a MetadataWorkspace.
Source=System.Data.Entity
StackTrace:
at System.Data.EntityClient.EntityConnection.ValidateChangesPermitted()
at System.Data.EntityClient.EntityConnection.set_ConnectionString(String value)
at DataLayer.ConnectionClass..ctor(String User) in Documents\Visual Studio 2010\Projects\DataLayer\ConnectionClass.cs:line 32
at BusinessLayer.BLBase..ctor(String user) in Documents\Visual Studio 2010\Projects\BusinessLayer\BLBase.cs:line 54
at BusinessLayer.Roles..ctor(String userLogged) in Visual Studio 2010\Projects\BusinessLayer\Roles.cs:line 12
at PresentationLayer.UserControls.Menu.Page_Load(Object sender, EventArgs e) in C:\Users\Documents\Visual Studio 2010\Projects\PresentationLayer\UserControls\Menu.ascx.cs:line 23
at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
and:
public ConnectionClass(string User)
{
this.Entities = new KurtDBEntities();
DataLayer.DARoles daRoles = new DARoles(this.Entities);
if (User == "Login")
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["KurtDBEntities"].ConnectionString.ToString();
}
else
{
//can also use entity connection string builder
if (User != "")
{
if (daRoles.IsUserInRole(User, 1))
{
this.Entities.Connection.ConnectionString = #"Data Source=KURT-PC\SQLEXPRESS;Initial Catalog=KurtDB;User ID=Admin;Password=123456";
}
else if (daRoles.IsUserInRole(User, 2))
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["BasicUser"].ConnectionString.ToString();
}
}
else
{
this.Entities.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["KurtDBEntities"].ConnectionString.ToString();
}
}
//this.Entities.Connection.ConnectionString = conn;
}
}
Any Help Please?

Please see my answer to your other question:
You'll need to first determine the connection string that you want to use and only after that you'll be able to new up the Entities object:
string connectionString = GetConnectionStringBasedOnUserRole(); // do your magic here
this.Entities = new KurtDBEntities(connectionString);
After this you should be able to use Entities normally, pointing to the correct database/server.

Related

LINQ Specified Cast Not Valid

Not getting much info on this error, but I'm not using any casting in this specific code, so I'm pretty lost.
var dsn = Request.ServerVariables["HTTP_HOST"].Split('.').First();
using (var ctx = new SharedDataContext("switchcurrent"))
{
var dbDsn = ctx.SiteObjects.FirstOrDefault(s => s.DSN == dsn);
if (dbDsn == null)
{
Session["CurrentDsn"] = "SwitchCurrent";
}
else
{
Session["CurrentDsn"] = dbDsn.DSN;
Response.Redirect(String.Format("~/{0}", dbDsn.DefaultPage));
}
}
The LINQ statement is where I'm getting the error. If the statement returns null, the code continues fine, but if it's an actual match with an object in the database, I'm getting this error.
EDIT (additional info)
The error message is an InvalidCastException
Stack trace:
at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)at System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate) at WebApplication1.Default.SetCurrentDsn() in C:\Code\dir\Default.aspx.cs:line 163 at WebApplication1.Default.Page_Load(Object sender, EventArgs e) in C:\Code\dir\Default.aspx.cs:line 32 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
SiteObject.Dsn is a string. and so is dsn.
Basically if it is 'localhost' (which isn't in the db) the code passes, but if its a match ('pgande') this error is thrown.
If s.DSN cannot be cast to dsn, you'll get this error. You may need to supply a conversion.
I think you already tried, but may be you need to cast dsn, not s.DSN? Try something link "s => s.DSN == dsn.ToString()".
Did this help?
Try this:
var dbDsn = ctx.SiteObjects.FirstOrDefault(s => s.DSN.ToString() == dsn.ToString());
I ended up dropping the table back into my Data Context and everything is working. Obviously something was corrupt with the table that was dropped in there the first time.

ASP.NET: Random.Next: NullReferenceException?

I am trying to set the text of two labels to random numbers on page load. This code
Random random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LINE 22 Label12.Text = random.Next(99).ToString();
LINE 23 Label13.Text = random.Next(999).ToString();
}
foreach (string s in scr1.Style.Keys)
{
Response.Write(s + ",");
}
}
...
works on localhost but when run on my server throws a NullReferenceException.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
.apps..Page_Load(Object sender, EventArgs e) in C:\Users**\Documents\Visual Studio 2010\Projects****\apps**.aspx.cs:22
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
Two options:
Label12 could be null
random could have been set to null by some other piece of code
The first part of diagnosing the problem would be to work out which of those is the case. Simply split the assignment:
string randomText = random.Next(99).ToString();
Label12.Text = randomText;
Then see which line it fails on. Once you know which expression is null, you can try to work out why it's null.

Column '' does not belong to table " even though it is present in the table and the query

Error Message is :
Exception of type 'System.Web.HttpUnhandledException' was thrown.
Friendly Message : System.ArgumentException: Column 'testfile' does
not belong to table . at System.Data.DataRow.GetDataColumn(String
columnName) at System.Data.DataRow.get_Item(String columnName) at
Registration_test.FillImage() in
c:\inetpub\wwwroot\testWeb\Events\Registration.aspx.cs:line 49 at
Registration_test.Page_PreInit(Object sender, EventArgs e) in
c:\inetpub\wwwroot\testWeb\test\Registration.aspx.cs:line 39 at
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object
o, Object t, EventArgs e) at
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender,
EventArgs e) at System.Web.UI.Page.OnPreInit(EventArgs e) at
System.Web.UI.Page.PerformPreInit() at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Target Site : Boolean HandleError(System.Exception) Source :System.Web
Error Stack Trace is : at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest() at
System.Web.UI.Page.ProcessRequest(HttpContext context) at
ASP.events_registration_aspx.ProcessRequest(HttpContext context) in
c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET
Files\testWeb\761ce6e4\d915dd85\App_Web_posk8hm6.6.cs:line 0 at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
I have got the above error as email when the site is hosted in IIS, but i donot get it when i am checking the code locally or even online.The error says the testfile column doesnot belong to datable even though the query returns the column.
can anyone help what could be the cause..
//////////////////////this is my code///////////////////////////////////////////////////
public partial class Registration_Registration : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
FillImage();
}
protected void FillImage()
{
string Query = "select t.header_image_file as 'HeaderImage',t.image,c.testfile from registrars c left join trade t on c.tradeid = t.tradeid and c.mainitemid = t.mainitemid ";
DataTable result = GetDataTable(Query);
if (result != null && result .Rows.Count > 0)
{
if (result .Rows[0]["testfile"] != null)
{
this.Theme = result .Rows[0]["testfile"].ToString().Trim();
this.MasterPageFile = result .Rows[0]["testfile"].ToString().ToLower().Trim() + ".master";
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}}
Ok so at a first glance we are seeing that the error is related to a column not being in a table.
To fix this I suggest you first run the query in management studio, check the names of the columns returned against the ones you are trying to access in your ASP.Net page.
If the column names are all correct backup the data then drop and recreate the table and the stored procedure that accesses this table and hopefully this will solve the issue.
It is a fairly easy to accidentally update a column etc in your database whilst developing and not push that change through to your production database.
If this doesnt solve things you will be able to get better help if you post your table structure, the query and the code which is accessing the query so we can diagnose the problem more efficiently.
UPDATE:
These are the columns you are selecting in your query
strt.header_image_file as 'HeaderImage',
t.image,
c.themefile
Yet in your code you are trying to access a column called testfile

How to clear error in asp.net

i have been designing a web page in asp.net and my project is successful. and i published my web application.However, below error occurs.How can I clear it?
Server Error in '/sarav' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web >request. Please review the stack trace for more information about the error and where it >originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. >Information regarding the origin and location of the exception can be identified using >the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Login.btnLogin_Click(Object sender, EventArgs e) +155
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent (String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746
How to clear error
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection Cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != null)
{
constr = ConfigurationManager.ConnectionStrings["PhotostudioConnectionString"].ConnectionString;
Cnn.ConnectionString = constr;
try
{
if (Cnn.State != ConnectionState.Open)
Cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = Cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UspGetDataUsrmast";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#usrname", txtUsername.Text);
cmd.Parameters.AddWithValue("#passwrd", txtPassword.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
// cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new ApplicationException("!!! An Error Occurred While Inserting Record. " + ex.Message);
}
finally
{
da.Dispose();
cmd.Dispose();
Cnn.Close();
Cnn.Dispose();
}
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Login Successfully";
// da.Dispose();
// cmd.Dispose();
// Cnn.Close();
// Server.Transfer("Home.aspx");
Response.Redirect("PhotosettingsReport.aspx");
}
else
{
Msg.Text = "Login Failed";
}
}
}
}
Without seeing the code, it's impossible to even guess as to what object is throwing this error.
Run the website in Visual Studio in debug mode (F5), and put a breakpoint at btnLogin_Click. When you click the button, it will break and allow you to step into the code. Step through the code until you find the line that is throwing the exception - that is the object that is null.
You're either trying to access something declared in the method that has not been initialized, or an object outside the method that has not been initialized.
Stepping through the code will quickly show you what's wrong.
UPDATE
I'd check txtUserName and txtPassword to be sure they have values. Also, are you sure you're getting results into the ds.Tables[0]? Calling Rows.Count on ds.Tables[0] could also result in that error if there are no tables.
Also, check your Web.config file - make sure that "PhotostudioConnectionString" is spelled correctly, including the case of the letters.
Why are you checking for IsValid != null? I think if (!IsValid) would be more proper. IsValid will either be true or false, it will never be null, so your code will always pass that check.

convert text to json

i use Newtonsoft.Json.Net20.dll
Html
<div id="a" runat="server">
</div>
Code
string kb = "a";
string b= Newtonsoft.Json.JsonConvert.SerializeObject(kb).ToString();
a.InnerText = b;
in local host on iis6 show "a"
but on internet show
��G�[�!�{��u^Ӹ�SY�L?��qz�Z�Ŕ�?���U1k������)f�]A�(�ݣ�w N����Q�x�.�0�=�����X�y6�?��.�r�~;��[�t�~�/�K��z�|�-��W�ź��Q��&���4B��Q�4o�u��x|wrt�L�K�$���Ms�.��4��ٺ.��|�.����s����W�$��_���ӗe�54��ȯ��`�6mk�#�.*��by�ap٤Z��Oa�^�s�jӪ.��p� �n�Y>�������Ӽ͊�����n�|1~M����z�r�}�Qz�9��u��i��v���0�-ˑǃ�������/���s��t���:b�������l�~�H[�4��o'�g�/�E�=����o�� ��3G��ގ}Yߝ|�~�����H�Z�;�����i��vrg�z�m����]�Uh�Z6>[.�� )�er����I���.��.�K_yȞF(C�v�Ha>"s�4��gE����G�/a׮֓��r^5m��u�<ϊzZ������jVM�߷��d���x���/\N�ա�b� qo�֜��%� $���l����s?/��
This link
but
when use Newtonsoft.Json
Dictionary<string, string> companyProducts = new Dictionary<string, string>();
companyProducts.Add("product" + item.IdProduct, item.NameProduct.ToString());
string JsonCompany = JavaScriptConvert.SerializeObject(companyProducts);
this code work fine.
this link
when site upload to internet for add new reference.
Enough that copy dll to appcode
Edit
use gzip in gloabal.asax
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
if (!(app.Context.CurrentHandler is Page ||
app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
app.Request["HTTP_X_MICROSOFTAJAX"] != null)
return;
if (acceptEncoding == null || acceptEncoding.Length == 0)
return;
acceptEncoding = acceptEncoding.ToLower();
if (acceptEncoding.Contains("gzip") )
{
// gzip
app.Response.Filter = new GZipStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
{
// defalte
app.Response.Filter = new DeflateStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
}
}
The file that you are getting from that page is a compressed file that contains an error page with an exception in it. Why it is doing this I don't know. Your global error handler might have a bug in it that causes it to send compressed data without the correct headers...
I assume you can get the file information out now you know what it is (I just right clicked on the link above and then used 7zip to open the file).
The key points though are:
Source File: c:\inetpub\vhosts\iranfairco.com\httpdocs\test.aspx.cs Line: 20
[VerificationException: Operation could destabilize the runtime.]
Newtonsoft.Json.JsonWriter..cctor() +6
[TypeInitializationException: The type initializer for 'Newtonsoft.Json.JsonWriter' threw an exception.]
Newtonsoft.Json.JsonWriter..ctor() +0
Newtonsoft.Json.JsonTextWriter..ctor(TextWriter textWriter) +16
Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Formatting formatting, JsonSerializerSettings settings) +157
Newtonsoft.Json.JsonConvert.SerializeObject(Object value) +9
test.Page_Load(Object sender, EventArgs e) in c:\inetpub\vhosts\iranfairco.com\httpdocs\test.aspx.cs:20
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
There is most likely something that is completely unrelated to the JSON conversion that is wrong, as not even the div tag show up in the page source.
Analysing the response in a binary editor reveals a lot of the UTF-8 sequence EF BF BD which is the character FFFD which is the Unicode replacement character. This is used when Unicode decoding fails, most likely because you have tried to decode something with the wrong encoding.

Resources