No ViewData localhost versus localhost in debug - c#

I'm stumped. When I run my solution in debug mode, the entire website works. It comes up with home page and everything. I can add, delete and update data to my database. The website was built with MVC, using SQLExpress (built in).
The issue is when I try to access the site either through localhost or from the outside world. The site worked last year before I had to reinstall windows. I upgraded from windows 7 to windows 8.1.
There's some kind of authentication that I'm missing. Could someone point it out to me?
Permissions set
IIS_USRS, and IUSR have modify, read & execute, list folder contents, read, and write
My physical path credentials is set to "Application User (pass-through authentication).
Application pool is using DefaultAppPool
.NET CLR Version v4.030319
Managed pipeline mode = Integrated
I had this issue before with windows 7, I thought I changed the DefaultAppPool process model identity to LocalService, or one of the other options. None of them are working now. Even tried to use a custom account.
Is there any more information I can provide?
Server Error in '/' Application.
There is no ViewData item of type 'IEnumerable' that
has the key 'YearID'.
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.InvalidOperationException: There is no
ViewData item of type 'IEnumerable' that has the key
'YearID'.
Source Error:
Line 53: Line 54: Year: Line 55: <%=
Html.DropDownList("YearID", ViewData["years"] as SelectList) %> Line
56: Line 57: League:
Source File:
e:\FantasyFootball\FantasyFootball\mvcFantasyFootball\FantasyFootball\Views\Home\Index.aspx
FFBallEntities _db = new FFBallEntities();
public ActionResult Navigation()
{
return View();
}
public ActionResult Index(int? id, int? leagueid, int? teamid)
{
try
{
bool ImMobile = DisplayModeProvider.MobileDisplayModeId.ToString() == "Mobile";
if (!ImMobile)
{
ViewData["Message"] = "Welcome To Fantasy Football Fantasy Edition!";
}
List<FanYear> years = _db.FanYearSet.OrderByDescending(m => m.FantasyYear).ToList();
List<League> leagues = _db.LeagueSet.ToList();
if (leagueid == null) leagueid = leagues[0].LeagueID;
if (id == null)
{
id = _db.TeamSet.OrderByDescending(m => m.FanYear.YearID).Select(m => m.FanYear.YearID).First();
}
ViewData["years"] = new SelectList(years, "YearID", "FantasyYear", id);
ViewData["leagues"] = new SelectList(leagues, "LeagueID", "League_Name", leagueid);
ViewData["selectedyear"] = id.ToString();
ViewData["selectedleague"] = leagueid.ToString();
ViewData["selectedteam"] = "0";
if (teamid != null)
ViewData["selectedteam"] = teamid.ToString();
int scoringid = _db.LeagueHistorySet.Include("FanYear").Include("Leagues").Include("Scoring").First(m => m.FanYear.YearID == id && m.Leagues.LeagueID == leagueid).Scoring.ScoringID;
ViewData["selectedscore"] = scoringid.ToString();
return View(_db.TeamScoreSet.Where(m => m.LeagueID == leagueid && m.YearID == id && (m.ScoringID == scoringid || m.ScoringID == 0)).OrderByDescending(m => m.PointsEarned).ToList());
}
catch
{
return View();
}
}

Me being an experienced web programmer, I should have known... (yet novice with .net and SQL server on windows platform).
The issue wasn't with the code, however, the code was preventing me from seeing the real error. My try... catch threw out a message I wasn't expecting.
I was having difficulty getting passed the fact that the code worked when I run it on my laptop in debug mode.
The solution is stored and compiled on my server, however, I use the laptop to modify the code.
When I started it in debug, I figured it was still running off the server. But at last I was not. I was using the SQL Express install on the laptop.
I have installed SQL Express 2012 on the server (which wasn't done when I reloaded the server), named the instance as I needed for the website. The website is now communicating with the database. I have other issues to resolve but I should be able to figure those out. My javascript and css isn't getting pulled in. I'll post a new question if I have trouble getting it working.
Thank you for the help.

Related

Object reference not set to an instance of an object on c# EF6

Sometime I get this error message when i run my project in Hosting.There is no problem on the local server. Sometimes this error comes up on the server, sometimes it works without any problems. I could not find the cause of the problem. Is it giving an error when creating a database instance? I'm using EF 6. Could it be a problem with the version?
https://www.linkpicture.com/q/Screen-Shot-2022-05-06-at-12.43.10.png
public ActionResult Index()
{
//var getNotes = (_noteManager.ListQueryable().Where(x => x.IsDraft == false && x.IsApproved == true).OrderByDescending(x => x.CreatedOn).Take(10).ToList());
return View(getNotes);
}
When i get this error i refresh browser and i can join website without problem.But another times i get again this error and i should refresh again.İts very weird

Why does `MemberShip.GetUser()` return null while `User.IsAuthenticated` returns true and the Username information is available in the database?

A Debian server is running a MVC4 app on Mono which uses a Membership ASPSqlProvider. The application has a method GetUserIdByName which creates a link between the Users table in the Membership database and the non-Membership Users table Users user's ID.
On my local Linux Mint system this setup does not have problem, but when the application is put on the Debian host (with the same XSP4 server and same version of Mono) and visited via the web it happens that MemberShip.GetUser() returns null. I found that out by wrapping the code in try-catch blocks and reading the exception from the website:
public int GetCurrentUserId()
{
var userName = "";
var currentUserName = "test";
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
try
{
userName = HttpContext.Current.User.Identity.Name;
currentUserName = Membership.GetUser().UserName;
}
catch (Exception ex)
{
throw new Exception(ex.Message + " User is:" + userName);
}
}
var currentUserId = _repository.GetUserIdByUserName(currentUserName);
return currentUserId;
}
The exception raised reads something like
NullReferenceException User is:theusersemailaddress#gmail.com
Interestingly enough when I query the database I see that the Username is there in the Membership Users table.
A solution is to just use the users email and change the method to GetUserIdByEmail which I will do for now. Someone who provided this solution in another answer got told that this was not a real solution but a workaround, and I agree.
So the question remains: why does on the Debian machine MemberShip.GetUser() return null while User.IsAuthenticated returns true and the Username information is available in the database?
/Edit, I see now that HttpContext.Current.User.Identity.Name returns the Email column on the Debian machine, and the Username column on the Linux mint one. Why would that be?

ASP.NET MVC 2.0 application not working on server

I have an MVC 2.0 application that is only loading the Home Index page. Whenever I try to navigate away from the page I get a HTTP Error 404 - File or directory not found.
Internet Information Services (IIS).
The site works find While testing on a localhost but whenever I try to run it on the destination site I keep not being able to navigate away from the Home page.
This is the way I am currently trying to get into the LoginOut Controller and trying to run the login method.
<% var login = Url.Action("Login", "LogInOut"); %>
<form method="post" class="pure-form" action="<% Response.Write(login); %>">
Then the LoginOutController is suppose to run this code. However no code get's run as the page both doesn't redirect and there is no Log file of what has just happened.
[HttpPost]
public ActionResult Login()
{
var username = Request.Form["username"];
var password = Request.Form["password"];
SessionFacade.UserSession = UserQueries.GetUserSession(username, password);
UserSession us = SessionFacade.UserSession;
//redirects to login if us is null
if (us == null)
{
Log.InvalidLogin(us, username);
return RedirectToAction("Index", "Home");
}
else if (us.GetUploader())
{
var uploadedFiles = new SessionFilesUploaded();
Session[SessionValue.SessionFilesUploaded()] = uploadedFiles;
}
Log.UserLogin(us);
//Checks that each user type has an appropriate folder and makes folders that are missing
var folders = UserQueries.GetFolders();
FolderExist.MakeFolder(folders);
return RedirectToAction("Index", "Browser");
}
The URL that I end up getting the 404 error is LogInOut/Login. Which as I said earlier works on my localhost server but doesn't seem to work on the webserver.
Any help would be appreciated
Found out the issue was with the fact that we are running an old server and IIS6. The MVC requests aren't getting processed as ASP.NET and that's what causing the issues. Had to port the code from MVC to webforms.

Error saving Entity dynamics crm 2011

I have an error that I can not repair.
Im developing an application that takes a guid as a parameter and "clone" that entity in another. (I know I can do this through javascript, the problem is the CRM server don't have the required rollup and I can't update it).
The projects works fine when I'm debugging in my computer, but when I deploy it to production server it just crash. My first guess was that it was an authentication problem, but I modified the authentication rules in IIS and impersonate any windows user that use the app with mine but didn't worked anyway.
The error it throws is: -2146233088 System.Collections.ListDictionaryInternal An error occured while processing this request. at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options) at Ambiente.DataAccess.Entities.CRMOrdenDeCompra.CreateOrdenDeCompra(Guid guidSolicitudDeCompra) in c:\Wip\Projects\Dev\CRMINTEGRATION\CRMINTEGRATION.DataAccess\Entities\CRMOrdenDeCompra.cs:line 42 at CRMINTEGRATION.WebApp.Controllers.RequestController.CreateOrdenDeCompra(String guid) in c:\Wip\Projects\Dev\CRMINTEGRATION\CRMINTEGRATION.WebApp\Controllers\RequestController.cs:line 22
The code that insert the entity:
var solicituddecompraContext = new CRMSolicitudDeCompra();
var solicituddecompra = new new_solicituddecompra();
solicituddecompra = context.new_solicituddecompraSet.FirstOrDefault(q => q.new_solicituddecompraId == parameterGuid);
new_ordendecompra ordendecompra = new new_ordendecompra();
ordendecompra.new_ordendecompraId = Guid.NewGuid();
ordendecompra.new_name = string.Format(solicituddecompra.new_name + " ({0})", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
ordendecompra.new_FechaRequirida = solicituddecompra.new_Fecharequerida;
ordendecompra.new_Tipodesolicitud = solicituddecompra.new_Tipodesolicitud;
ordendecompra.new_Observaciones = solicituddecompra.new_observaciones;
ordendecompra.new_Numerodesolicitud = solicituddecompra.new_SolicitudNo;
var detallerequisicion = CRMDetalleRequisicion.getDetalleRequisicion(context, guidSolicitudDeCompra);
context.AddObject(ordendecompra);
context.SaveChanges();
I generated the XRM class of CRM with the crmsvcutil.exe. So the name of the classes you see in the code are actually the name of the entities in CRM. All of the above works fine until it reaches the method entidad.SaveChanges().
Ps. As you can see in the code, english is not my native language. Feel free to correct me if I make any mistake. I will apreciate that :).

WCF Data Service Update returns 401- Unauthorized: Access is denied due to invalid credentials

I have a WCF data service and I am trying to use the UpdateObject method on the DataServiceContext client. When I call the SaveChanges method, I get the following error page:
Unauthorized: Access is denied due to invalid credentials
You do not have permission to view this directory or page using the credentials that you supplied.
Does anyone have any ideas of how I can fix this? I found this, which would theoretically fix the problem, but setting this disk access is not a realistic solution for a production service. Keep in mind, when running this WCF Data service on my local machine, it works just fine. The C# code for my call is below:
public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection)
{
var userName = ( string ) context[ "UserName" ];
var isAuthenticated = ( bool ) context[ "IsAuthenticated" ];
if (userName != null && userName.Length >= 1 && collection.Count >= 1)
{
var allNames = string.Empty;
var allValues = string.Empty;
byte[] buf = null;
PrepareDataForSaving( ref allNames, ref allValues, ref buf, true, collection, isAuthenticated );
if (allNames.Length != 0)
{
var client = GetDataContext( );
var profile = client.ProfileViews.Where(p => p.UserName == userName).FirstOrDefault();
if (profile == null)
{
profile = new ProfileView() { UserName = userName };
client.AddToProfileViews(profile);
}
profile.PropertyNames = allNames;
profile.PropertyValuesString = allValues;
profile.PropertyValuesBinary = buf;
profile.LastUpdateDate = DateTime.UtcNow;
client.UpdateObject(profile);
client.SaveChanges( );
}
}
}
I had a similiar issue with a Silverlight application that was using WCF Data Services. The users could view data in the application---SELECTS from the database were functioning---but they were receiving the same "401 - Unauthorized: Access is denied du to invalid credentials." you are describing when they attempted to save changes to the database (i.e., at the point when SaveChanges was executed in code). The underlying problem ended up being a permissions issue with the IIS application folder itself. To fix, we had to grant the Application Pool being used by the WCF service Write permissions to the folder.
Go to IIS and right click on the virtual directory containing the WCF service and choose Manage Application -> Advanced Settings.... Make note of the Application Pool name.
Within same right-click menu, choose Edit Permissions..... On Security tab, check group and user names.
If the name of the Application Pool is missing. Add it using the name format "IIS APPPOOL\MyApplicationPoolName". See this helpful link: http://www.bluevalleytech.com/techtalk/blog/assigning-ntfs-folder-permission-to-iis7-application-pools/
Make sure MyApplicationPoolName has Write permissions (we actually gave it Full control)
In my case I had Windows authentication with impersonation using kerberos (useAppPoolCredentials=true) on a WCF Data Service hosted on IIS 7.5. The weird thing was that I could successfully select and insert data, but when I tried to update I got a 401.3 access denied error. The solution was to give the AD group specified in the web config (myRole):
<authorization>
<allow roles="myRole"/>
<deny users="*" />
</authorization>
Read and write access to the application folder like Dan Sabin said . The error message was:
Error message 401.3: You do not have permission to view this directory or page using the credentials you supplied (access denied due to Access Control Lists). Ask the Web server's administrator to give you access

Categories