ConnectionString property has not been initialized IIS - asp.net-mvc

Having some issues when I deploy my application to IIS. This is only happening on two pages and the rest of my site works just fine when hitting the database.
public static List<Parent> GetParentsWithAssignedStudentsByISDId()
{
SqlConnection sqlConn = null;
SqlDataReader sqlDataReader = null;
string sConnString = ConfigurationManager.AppSettings["SMARTDBConn"];
var parents = new List<Parent>();
try
{
sqlConn = new SqlConnection(sConnString);
sqlConn.Open();
string commandText = String.Format("SELECT * FROM dbo.ParentFullInfo WHERE ISDId = {0}", Utilities.getISDId());
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConn);
sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
var parent = new Parent() { Students = new List<Student>() };
parent.Id = Convert.ToInt32(sqlDataReader["ParentId"]);
parent.ParentName = sqlDataReader["ParentName"].ToString();
parent.EmailAddress = sqlDataReader["EmailAddress"].ToString();
parent.Address = sqlDataReader["Address"].ToString();
parent.City = sqlDataReader["City"].ToString();
parent.State = sqlDataReader["State"].ToString();
parent.ZipCode = sqlDataReader["ZipCode"].ToString();
parent.WorkNumber = sqlDataReader["WorkNumber"] == DBNull.Value ? string.Empty : sqlDataReader["WorkNumber"].ToString();
parent.PrimaryCellNumber = sqlDataReader["PrimaryCellNumber"] == DBNull.Value ? string.Empty : sqlDataReader["PrimaryCellNumber"].ToString();
parent.HomeNumber = sqlDataReader["HomeNumber"] == DBNull.Value ? string.Empty : sqlDataReader["HomeNumber"].ToString();
parent.Password = sqlDataReader["Password"].ToString();
var student = StudentFactory.GetStudentByStudentId(Convert.ToInt32(sqlDataReader["StudentId"]));
if (!parents.Exists(p => p.Id == parent.Id))
{
parent.Students.Add(student);
parents.Add(parent);
}
else
{
var par = parents.FirstOrDefault(p => p.Id == parent.Id);
if (par != null)
par.Students.Add(student);
}
}
}
finally
{
if (sqlDataReader != null) sqlDataReader.Close();
if (sqlConn != null) sqlConn.Close();
}
return parents;
}
my Web.config does have the proper key
<add key="SMARTDBConn" value="server=ConnStringHere" />
The error
[InvalidOperationException: The ConnectionString property has not been initialized.]
System.Data.SqlClient.SqlConnection.PermissionDemand() +6616256
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6610951
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
System.Data.SqlClient.SqlConnection.Open() +239
SMART_Library.Factories.StudentFactory.GetStudentByStudentId(Int32 studentId) +138
SMART_Library.Factories.ParentFactory.GetParentsWithAssignedStudentsByISDId() +1378
SMARTSupport.Controllers.ParentController.Search(String SearchKey) +48
lambda_method(Closure , ControllerBase , Object[] ) +127
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +270
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +120
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +240
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +74
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Related

MySQL and SQL Server / Keyword not supported: 'data source HOST.com;initial catalog'

Note as of 9/16/2019 at 3:30 EDT
I have disabled the parts of my app that use the SQL Server DB so my site would not crash. Just as info, in case anyone access my site and can't reproduce the error.
I have read most if not all of the similar threads to no avail. My site uses BOTH MySQL and SQLserver. Everything works fine on my PC [localhost]. I issued the code for the first time this weekend, and have run into this problem with the published code on my hosting site. I am able to access the MySQL DB just fine, but when I try and access the SQLServer, I get the error -- Keyword not supported: 'data source HOST.com;initial catalog'.
Web.config
<connectionStrings>
<add name='DefaultConnection' providerName='System.Data.SqlClient' connectionString='Data Source=[HOST Server];Initial Catalog=aspnet-Lat34North-20190423140228;Integrated Security=SSPI' />
<add name='Lat34NorthContext' providerName='System.Data.SqlClient' connectionString='Data Source=[HOST Server];Initial Catalog=Lat34North;Integrated Security=False;User Id=[user id 1]; Password=[password 1]' />
<!-- Production -->
<add name="CitiesContext" connectionString="Data Source=[HOST Server]; Database=Lat34CitiesSQL; uid=[user id 2]; pwd=[password 2];" providerName="MySql.Data.MySqlClient" />
DAL
using Lat34North.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace Lat34North.DAL
{
public class Lat34NorthContext : DbContext
{
public DbSet<Photo> Photo { get; set; }
public DbSet<MarkersPrevNext> MarkersPrevNext { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Photo>().Property(p => p.PhotoFile).HasColumnType("image");
modelBuilder.Entity<MarkersPrevNext>().HasKey(t => new { t.StateCounty, t.Sequence });
}
}
}
Controller
using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Data.Entity.Spatial;
using Lat34North.DAL;
using Lat34North.Models;
namespace Lat34North.Controllers
{
public class HistoricMarkersALController : BaseController
{
private ALMarkersContext db = new ALMarkersContext();
private Lat34NorthContext db2 = new Lat34NorthContext();
---- skip ahead --
int CurrentCount = CountPrevNext(PrevNextLocation, "M"); // Count number if records created today
if (CurrentCount == 0)
{
var temps = db.ALHistoricMarkers.Where(t => t.County == county_name).OrderBy(t => t.Title).ToList();
string dateCreated = DateTime.Now.ToString("yyyy-MM-dd");
int i = 0;
foreach (var temp in temps)
{
db2.MarkersPrevNext.Add(new MarkersPrevNext() ***<--Error here***
{
StateCounty = PrevNextLocation,
Sequence = i,
Type = "M", // Type M - marker
MarkerKey = temp.MarkerKey,
CraetedDate = dateCreated
});
i++;
}
db2.SaveChanges();
}
return View(vModel);
}
Error
Server Error in '/' Application.
________________________________________
Keyword not supported: 'data source HOST.com;initial catalog'.
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.ArgumentException: Keyword not supported: 'data source HOST.com;initial catalog'.
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:
[ArgumentException: Keyword not supported: 'data source {Server name.com];initial catalog'.]
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +418
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +99
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +25
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +166
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +57
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +148
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +360
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +270
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +129
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() +11
System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) +92
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +515
System.Data.Entity.Internal.InternalContext.Initialize() +20
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +83
Lat34North.Controllers.BaseController.DeletePrevNext(String PrevNextLocation, String type) in c:\Lat34North\Lat34North\Controllers\CommonController.cs:71
Lat34North.Controllers.HistoricMarkersALController.SearchChurches(String option, String search) in c:\Lat34North\Lat34North\Controllers\HistoricMarkersALController.cs:459
lambda_method(Closure , ControllerBase , Object[] ) +147
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
change your config to the following. you missed a closing ' for connectionString=''
<add name='Lat34NorthContext' connectionString='Data Source=[HOST Server];Initial Catalog=Lat34North;Integrated Security=False;User Id=[user id 1]; Password=[password 1];Min Pool Size=20; Max Pool Size=200;' providerName="System.Data.SqlClient" />
If your SQL Server is on one domain controller and you are trying to connect to it from another domain controller then you will get this error when IntegratedSecurity = true;
Integrated security means simply - use your windows credentials for login verification to SQL Server. So, if you are logged in to a different domain controller then it will fail. In the case where you are on two different domain controllers then you have no choice but to use IntegratedSecurity = false;

Cannot close stream until all bytes are written (VirusTotal API, Mvc)

This Question is different from
Sending file to VirusTotal with MVC
I am a student trying out another mini project where the user can upload a CSV file to the web server. But before I can create another program to execute the file, I would like to send the file to virustotal to have it check for the virus.
I tried but I got an error: "Cannot close stream until all bytes are written"
Here are my codes:
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VirusTotalNET;
namespace Testing_1.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult Upload(HttpPostedFileBase file)
{
string filename = Server.MapPath("~/CSV/" + file.FileName);
file.SaveAs(filename);
FileInfo fi = new FileInfo(filename);
VirusTotal vtObj = new VirusTotal("%API KEY");
var resID = vtObj.ScanFile(fi).ToString();
ViewBag.resID = resID;
ViewBag.Path = filename;
return View();
}
}
}
I got the error at this line: string resID = vtObj.ScanFile(file.FileName);
Index
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="File" id="file"/>
<input type="submit" value="Upload" />
}
Upload
#{
ViewBag.Title = "Upload";
}
<h2>Uploaded: #ViewBag.Path : #ViewBag.resID</h2>
Stack Trace
[IOException: Cannot close stream until all bytes are written.]
System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting) +609
[WebException: The request was aborted: The request was canceled.]
VirusTotalNET.VirusTotal.GetResults(RestRequest request, Boolean applyHack) in d:\Source control\Github\VirusTotal.NET\VirusTotal.NET\VirusTotal.cs:687
VirusTotalNET.VirusTotal.ScanFile(Stream fileStream, String filename) in d:\Source control\Github\VirusTotal.NET\VirusTotal.NET\VirusTotal.cs:191
VirusTotalNET.VirusTotal.ScanFile(FileInfo file) in d:\Source control\Github\VirusTotal.NET\VirusTotal.NET\VirusTotal.cs:150
C200_1.Controllers.HomeController.Upload(HttpPostedFileBase file) in C:\Users\FrezzeY\Desktop\C200\C200_1\Controllers\HomeController.cs:28
lambda_method(Closure , ControllerBase , Object[] ) +103
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +30
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +197
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +46
System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +37
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +24
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +43
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +68
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +69
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +230
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +68
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +42
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +124
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +32
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +26
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +24
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +29
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +23
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9744261
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Please help me Thank you
Saving the file to disk before scanning could be a security issue.
You should scan it before trying to save it.
Update your method.
public ActionResult Upload(HttpPostedFileBase file) {
string fileName = file.FileName
var fileStream = new MemoryStream();
file.InputStream.CopyTo(fileStream);
var vtObj = new VirusTotal("%API KEY");
var fileResults = vtObj.ScanFile(fileStream, fileName);
var resId = fileResults.ScanId;
//should do something based on message and then decide if you want to save the file
var savePath = Server.MapPath("~/CSV/" + fileName);
file.SaveAs(savePath);
ViewBag.resID = resId;
ViewBag.Path = savePath;
return View();
}

MVC application SESSION for some users null

My problem is with a system i developed for school. We are experiencing some issues for some users. this is the error:
[NullReferenceException: Object reference not set to an instance of an object.]
_360Feedback.Controllers.SurveyController.Answers() +170
lambda_method(Closure , ControllerBase , Object[] ) +78
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +273
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +38
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +119
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +452
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +240
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
For some reason the student id is not retained by the session object. I cannot regenerate the error so it is very hard for me to find the reason what is causing this.
Setting the session to cookieless seemed to cause less errors for users, but still generated the error for some users.
I can see that for about 90% of the users everything is working fine. I will post the controller code where this session id is used. I hope you guys can help me.
public ActionResult Start(string x)
{
string decryptedstudentIDString = EncryptionHelper.Decrypt(x);
int studentID = Convert.ToInt32(decryptedstudentIDString);
Student student = repo.FindStudentWithID(studentID);
Session["StudentName"] = student.Name;
Session["StudentID"] = student.StudentID;
if (student.CompletedAnswers == true)
{
return RedirectToAction("Completed");
}
return View(student);
}
public ActionResult Answers()
{
Student student = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"]));
if (student.CompletedAnswers == true)
{
return RedirectToAction("Completed");
}
List<Student> remainingStudentInGroup = repo.GetRemainingStudentIDsInGroup(student.StudentID);
student.Answers.Add(new AnswerSet() { AssociatedStudentID = student.StudentID, AssociatedStudentName = student.Name });
foreach (var studentInGroup in remainingStudentInGroup)
{
student.Answers.Add(new AnswerSet() { AssociatedStudentID = studentInGroup.StudentID, AssociatedStudentName = repo.FindStudentWithID(studentInGroup.StudentID).Name });
}
Group group = repo.GetGroupAssociatedWithStudent(student.StudentID);
Session["StudentID"] = student.StudentID;
Session["GroupSize"] = group.Students.Count;
return View(student);
}
[HttpPost]
public ActionResult Answers(Student student)
{
int s = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"])).StudentID;
foreach (var answerSet in student.Answers)
{
repo.AddAnswerSetToStudent(answerSet, s);
}
return RedirectToAction("Completed");
}
public ActionResult Completed()
{
Student student = repo.FindStudentWithID(Convert.ToInt32(Session["StudentID"]));
if (student.CompletedAnswers == false)
{
repo.SetBooleanForCompletedAnswerToTrue(student.StudentID);
Group group = repo.GetGroupAssociatedWithStudent(student.StudentID);
ExcelHelper.FillExcelWithAnswersForStudent(group.ExcelFilePath, student);
ExcelHelper.CheckIfAllStudentAnswered(group);
}
return View();
}
Error occurs when users submit form, StudentID is null when they post there answers.

No Handler Registered CQRS-ES

I am creating a cqrs-es test application. I scan command handler against command by following code
public class StructureMapCommandHandlerFactory : ICommandHandlerFactory
{
public ICommandHandler<T> GetHandler<T>() where T : Command
{
var handlers = GetHandlerTypes<T>().ToList();
var cmdHandler = handlers.Select(handler =>
(ICommandHandler<T>)ObjectFactory.GetInstance(handler)).FirstOrDefault();
return cmdHandler;
}
private IEnumerable<Type> GetHandlerTypes<T>() where T : Command
{
var handlers = typeof(ICommandHandler<>).Assembly.GetExportedTypes()
.Where(x => x.GetInterfaces()
.Any(a => a.IsGenericType && a.GetGenericTypeDefinition() == typeof(ICommandHandler<>)))
.Where(h => h.GetInterfaces()
.Any(ii => ii.GetGenericArguments()
.Any(aa => aa == typeof(T)))).ToList();
return handlers;
}
}
I dispatches command as follows:
public class CommandBus:ICommandBus
{
private readonly ICommandHandlerFactory _commandHandlerFactory;
public CommandBus(ICommandHandlerFactory commandHandlerFactory)
{
_commandHandlerFactory = commandHandlerFactory;
}
public void Send<T>(T command) where T : Command
{
var handler = _commandHandlerFactory.GetHandler<T>();
if (handler != null)
{
handler.Execute(command);
}
else
{
throw new UnregisteredDomainCommandException("no handler registered");
}
}
}
When I run the project it throw an exception
"No Handler Registered"
My project location is https://drive.google.com/file/d/0B1rU7HOTfLwea0tVOXdIb2Nib2M/edit?usp=sharing
The Stack-Trace of this exception as follow:
[UnregisteredDomainCommandException: no handler registered]
CQRS.Infrastructure.Messaging.CommandBus.Send(T command) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\HRMSystem\CQRS.Infrastructure\Messaging\CommandBus.cs:31
HRMSWeb.Facade.DiaryItemFacade.Delete(Guid id) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\HRMSystem\HRMSWeb\Facade\DiaryItemFacade.cs:59
HRMSWeb.Controllers.HomeController.Delete(Guid id) in f:\Video\Latest Readable\CQRS Tutorial\CQRS By Authors\HRMSystem\HRMSWeb\Controllers\HomeController.cs:29
lambda_method(Closure , ControllerBase , Object[] ) +184
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c_DisplayClass42.b_41() +28
System.Web.Mvc.Async.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c_DisplayClass39.b_33() +57
System.Web.Mvc.Async.<>c_DisplayClass4f.b_49() +223
System.Web.Mvc.Async.<>c_DisplayClass37.b_36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c_DisplayClass1d.b_18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c_DisplayClass4.b_3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c_DisplayClass8.b_3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
The problem is on your ObjectFactory.
I don't know if you use some DI container (I can't see your code), but it can't retrieve your handlers.
You should use some kind of Typed Factory, so you could retrieve more than one commandHandler (as you do in your code).
I send you the link of my training journey into CQRS/ES: it's very similar to what you're doing and there are some articles about the journey.
I Hope it helps.

ASP.NET MVC 4 + EF5 beta2 + DbGeography types + MiniProfiler throws error

I have an MVC 4 project using EF 5 Code First. I am trying to install MiniProfile at no avail.
I pulled MiniProfiler 2.0.1 and MiniProfiler.EF 2.0.2 from NuGet, added the following on the Global.asax.cs:
protected void Application_Start()
{
MiniProfilerEF.Initialize();
}
Immediately upon run, I get this error:
The provider did not return a DbSpatialServices instance.
Line 58: if (user != null)
Line 59: {
Line 60:>>> if (user.Places != null)
Line 61: {
Line 62: var place= user.Places .OrderByDescending(x => x.CreationTime).FirstOrDefault();
[ProviderIncompatibleException: The provider did not return a DbSpatialServices instance.]
System.Data.Common.DbProviderServices.GetDbSpatialDataReader(DbDataReader fromReader, String manifestToken) +62
System.Data.Common.DbProviderServices.GetSpatialDataReader(DbDataReader fromReader, String manifestToken) +101
System.Data.Spatial.SpatialHelpers.CreateSpatialDataReader(MetadataWorkspace workspace, DbDataReader reader) +70
System.Data.Common.Internal.Materialization.Shaper.CreateSpatialDataReader() +12
System.Data.Common.Utils.Singleton`1.get_Value() +25
System.Data.Common.Internal.Materialization.Shaper.<GetSpatialPropertyValueWithErrorHandling>b__d(DbDataReader reader, Int32 column) +12
System.Data.Common.Internal.Materialization.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) +149
System.Data.Common.Internal.Materialization.Shaper.GetSpatialPropertyValueWithErrorHandling(Int32 ordinal, String propertyName, String typeName, PrimitiveTypeKind spatialTypeKind) +269
lambda_method(Closure , Shaper ) +942
System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly(Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) +239
lambda_method(Closure , Shaper ) +221
System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) +163
System.Data.Common.Internal.Materialization.SimpleEnumerator.MoveNext() +88
System.Data.Objects.DataClasses.RelatedEnd.Merge(IEnumerable`1 collection, MergeOption mergeOption, Boolean setIsLoaded) +222
System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption) +218
System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption) +25
System.Data.Objects.DataClasses.RelatedEnd.Load() +37
System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad() +300
System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +85
System.Data.Objects.Internal.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item) +105
System.Data.Entity.DynamicProxies.User_C006B0EF9498157C70250EEE038C6BEADB719A2D5BDC4AA1FB567FB579AECEB5.get_Places() +55
Project.Web.Controllers.PlaceController.Ribbon() in c:\Project\Project.Web\Controllers\PlaceController.cs:60
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +204
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +30
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +42
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +54
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +9
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +47
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +22
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +10
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +64
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +71
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1121
I have a couple of DbGeography types in my Places POCO.
public class Places
{
public Guid PlacesId { get; set; }
...
public DbGeography Location { get; set; }
public DbGeography Area { get; set; }
...
}
I have tried searching for that error but it does not show up in google anywhere.
This looks like a bug in MiniProfiler, it should be reported at: http://community.miniprofiler.com
In particular profiling EF is very tricky, a lot of the work is done by wrapping every "provider" it uses. It seems that EFProfiledDbProviderFactory needs some special logic to locate, intercept and wrap the spatial services.

Resources