Upload Large File In MVC Encountered an Error - c#

I have a .txt file that the size up to 2GB, i want to upload that file from client to a folder in a server, while uploading that file, there is an error, this is what the page says:
An operation was attempted on a nonexistent network connection. (Exception from HRESULT: 0x800704CD)
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.Runtime.InteropServices.COMException: An operation was attempted on a nonexistent network connection. (Exception from HRESULT: 0x800704CD)
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:
[COMException (0x800704cd): An operation was attempted on a nonexistent network connection. (Exception from HRESULT: 0x800704CD)]
[HttpException (0x80004005): An error occurred while communicating with the remote host. The error code is 0x800704CD.]
System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect) +3399867
System.Web.Hosting.IIS7WorkerRequest.ReadEntityCoreSync(Byte[] buffer, Int32 offset, Int32 size) +9621484
System.Web.Hosting.IIS7WorkerRequest.ReadEntityBody(Byte[] buffer, Int32 size) +24
System.Web.HttpRequest.GetEntireRawContent() +315
System.Web.HttpRequest.GetMultipartContent() +63
System.Web.HttpRequest.FillInFormCollection() +160
System.Web.HttpRequest.EnsureForm() +69
System.Web.HttpRequest.get_Form() +13
System.Web.HttpRequestWrapper.get_Form() +14
System.Web.Mvc.HttpRequestExtensions.GetHttpMethodOverride(HttpRequestBase request) +121
System.Web.Mvc.AcceptVerbsAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) +37
System.Web.Mvc.HttpGetAttribute.IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) +39
System.Web.Mvc.ActionMethodSelectorBase.IsValidMethodSelector(ReadOnlyCollection`1 attributes, ControllerContext controllerContext, MethodInfo method) +54
System.Web.Mvc.ActionMethodSelectorBase.RunSelectionFilters(ControllerContext controllerContext, List`1 methodInfos) +132
System.Web.Mvc.ActionMethodSelectorBase.FindActionMethods(ControllerContext controllerContext, String actionName) +142
System.Web.Mvc.ActionMethodSelectorBase.FindActionMethod(ControllerContext controllerContext, String actionName) +104
System.Web.Mvc.Async.ReflectedAsyncControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +54
System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +16
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +114
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +468
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__3(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
And this is some of the code:
public ActionResult UploadFile_Post(FormCollection dt, string btn, HttpPostedFileBase uploadFile, FileUpload dataFile)
{
string nameFile, getExtension = "";
nameFile = System.IO.Path.GetFileNameWithoutExtension(uploadFile.FileName.ToString().Trim()) + "_" + usernm.Trim() + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss").Trim();
getExtension = System.IO.Path.GetExtension(uploadFile.FileName.ToString().Trim());
string FilePath = Server.MapPath("~\\Upload\\" + nameFile + ".txt");
string pathFile = Server.MapPath("~\\Upload\\");
if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}
uploadFile.SaveAs(FilePath);//i think failed at this process
}
In the Web.config file, i already set the configuration for maxRequestLength , executionTimeout, and maxAllowedContentLength.
Maybe my code is wrong, can you guys give me the better way to upload such file?
Thank You,
Sorry for my bad english.

<system.web>
<httpRuntime executionTimeout="3600" maxRequestLength="102400"
appRequestQueueLimit="100" requestLengthDiskThreshold="10024000"/>
</system.web>
executionTimeout : Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
maxRequestLength : Specifies the limit for the input stream buffering threshold, in KB
appRequestQueueLimit : Specifies the maximum number of requests that ASP.NET queues for the application.
requestLengthDiskThreshold: Specifies the limit for the input stream buffering threshold, in bytes. This value should not exceed the maxRequestLength attribute.
Change these setting and see what happens. It also would be nice to know the version of IIS you are using.
https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.100%29.aspx

You should never allow an upload of a file that large to a web server because it will take up all the memory and crash your web server. Remember that when you upload file to a web server, all that data gets stored in memory while its trying to write to your database or your file system. For files that large, you need to upload the file via file streaming or via FTP. If you google Jon Galloway, he might have some answers for you on other ways to upload large files.

Related

Problem with: Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied

Server Error in '/' Application.
Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied.
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.UnauthorizedAccessException: Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.
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:
[UnauthorizedAccessException: Access to the path '$(sourceFolder)\Foundation\Articles\serialization' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +435
System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost) +1436
System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost) +98
Rainbow.Storage.SerializationFileSystemDataStore.InitializeRootPath(String rootPath) +346
Rainbow.Storage.SerializationFileSystemDataStore..ctor(String physicalRootPath, Boolean useDataCache, ITreeRootFactory rootFactory, ISerializationFormatter formatter) +236
lambda_method(Closure , Object[] ) +246
Configy.Containers.MicroContainer.Activate(Type type, KeyValuePair`2[] unmappedConstructorParameters) +841
Unicorn.Configuration.<>c__DisplayClass8_0.<RegisterConfigTypeInterface>b__3() +41
System.Lazy`1.CreateValue() +734
System.Lazy`1.LazyInitValue() +189
Unicorn.Data.ConfigurationDataStore.RegisterForChanges(Action`2 actionOnChange) +19
Unicorn.Data.DataProvider.UnicornDataProvider..ctor(ITargetDataStore targetDataStore, ISourceDataStore sourceDataStore, IPredicate predicate, IFieldFilter fieldFilter, IUnicornDataProviderLogger logger, IUnicornDataProviderConfiguration dataProviderConfiguration, ISyncConfiguration syncConfiguration, PredicateRootPathResolver rootPathResolver) +549
lambda_method(Closure , Object[] ) +402
Configy.Containers.MicroContainer.Activate(Type type, KeyValuePair`2[] unmappedConstructorParameters) +841
Configy.Containers.MicroContainer.Resolve() +110
System.Linq.WhereSelectArrayIterator`2.MoveNext() +145
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +284
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +90
Unicorn.Data.DataProvider.UnicornSqlServerDataProvider..ctor(String connectionString) +222
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +223
Sitecore.Reflection.ReflectionUtil.CreateObject(Type type, Object[] parameters) +119
Sitecore.Configuration.DefaultFactory.CreateFromTypeName(XmlNode configNode, String[] parameters, Boolean assert) +108
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +163
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.CreateObject(String configPath, String[] parameters, Boolean assert) +703
Sitecore.Configuration.DefaultFactory.CreateFromReference(XmlNode configNode, String[] parameters, Boolean assert) +170
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +116
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.GetInnerObject(XmlNode paramNode, String[] parameters, Boolean assert) +947
Sitecore.Configuration.DefaultFactory.AssignProperties(XmlNode configNode, String[] parameters, Object obj, Boolean assert, Boolean deferred, IFactoryHelper helper) +545
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert, IFactoryHelper helper) +326
Sitecore.Configuration.DefaultFactory.CreateObject(XmlNode configNode, String[] parameters, Boolean assert) +72
Sitecore.Configuration.DefaultFactory.CreateObject(String configPath, String[] parameters, Boolean assert) +703
Sitecore.Configuration.DefaultFactory.GetDatabase(String name, Boolean assert) +157
Sitecore.XA.Foundation.Multisite.Providers.SxaSiteProvider.GetSiteList() +51
Sitecore.XA.Foundation.Multisite.Providers.SxaSiteProvider.InitializeSites() +105
Sitecore.XA.Foundation.Multisite.Providers.SxaSiteProvider.GetSites() +18
System.Linq.<SelectManyIterator>d__17`2.MoveNext() +265
Sitecore.Sites.SiteCollection.AddRange(IEnumerable`1 sites) +221
Sitecore.Sites.SitecoreSiteProvider.GetSites() +258
Sitecore.Sites.DefaultSiteContextFactory.GetSites() +253
Sitecore.XA.Foundation.Multisite.SiteInfoResolver.get_Sites() +60
Sitecore.XA.Foundation.Multisite.Pipelines.Initialize.InitSiteManager.Process(PipelineArgs args) +85
(Object , Object ) +9
Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args) +490
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists) +236
Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain) +22
Sitecore.Nexus.Web.HttpModule.Application_Start() +220
Sitecore.Nexus.Web.HttpModule.Init(HttpApplication app) +1165
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +584
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +168
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +277
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +369
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +724
Iv tried suggestions taken from the following:
Problems with error: "Access to the path is denied."
1) Open Internet Information Systems (IIS) Manager
2) Expand the site you want to modify (hit the plus next to the name)
3) Right-click the directory where you would like to be able to write files and select Edit Permissions
4) Click on the Security tab
5) Click on Edit... under the group and users list
6) Select IIS_IUSRS from the "Groups or user names" list and add make sure the Allow checkbox is marked for Write.
ASP.NET is not authorized to access the requested resource when accessing temp folder
a really simple fix to solve my issue, in IIS I had to right click on Application Pools and set .NET Framework V4 to Integrated rather than classic/.
Another solution was to set the specific folder that was being accessed to read/write to the users that required it, this can be done by unique users or within an organization, a group of users
(https://stackoverflow.com/a/47503132/19587900)
(1) I have gone to wwwroot folder. Right-click and security tab. Provided IISUSER to set read and write permission to the wwwroot folder.
(2) Changed the application pool to the separate pool and set identity to Application pool Identity.
Iv tried other things but so far no success
Looks like you're trying to create a folder that starts with "$(sourceFolder)", that's not going to work well. Are you missing a variable definition like:
<sc.variable name="sourceFolder" set:value="c:\whatever" />

An unhandled exception was generated during the execution of the current web request.[HttpAntiForgeryException]

I have a C# .NET MVC app and I am getting "anti-forgery token could not be decrypted". I don't know where the error is and I need help resolving this issue. And I am running this application on my localhost. Below is the error I am getting.
Server Error in '/' Application.
The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.
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.Web.Mvc.HttpAntiForgeryException: The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.
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:
[HttpAntiForgeryException (0x80004005): The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.]
System.Web.Helpers.AntiXsrf.AntiForgeryTokenSerializer.Deserialize(String serializedToken) +337
System.Web.Helpers.AntiXsrf.AntiForgeryTokenStore.GetFormToken(HttpContextBase httpContext) +91
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext) +44
System.Web.Helpers.AntiForgery.Validate() +92
System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext) +18
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +97
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
When ASP.NET generates the token, it uses some machine key for that. If you later try to decrypt that token with another key, you will get this type of exception.
It is very strange that you can get this by just running localhost, since this usually happens on a load balanced scenario e.g. when you have not set up the machine key to be the same.
Another possible reason is that you manipulate the token on the frontend somehow or get the web page from another machine, though both scenarios seem to be unlikely.
Anyway, if you have troubles with the load balancing or something like this, you need to set up the same machine key in all web.config files.

ASP.NET MVC 5 Invalid object name 'dbo.UsersInRoles'

I'm working on my ASP.NET MVC 5 project
Here is my Admin code
[Authorize(Roles = "Admin")]
public ActionResult Admin()
{
return View(UserManager.Users);
}
All I want to do is to be able to delete users from database and its related records in AspNetUserRoles.
I added this into my web.config inside system.web section
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider"
connectionstringname="DefaultConnection" enablepasswordretrieval="false" enablePasswordReset="true"
requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider"
connectionStringName="DefaultConnection" applicationName="/" />
When trying to open the /Admin page it throws exception:
Invalid object name 'dbo.UsersInRoles'.
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.Data.SqlClient.SqlException: Invalid object
name 'dbo.UsersInRoles'.
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:
[SqlException (0x80131904): Invalid object name 'dbo.UsersInRoles'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction) +1789294 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
+5340642 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +61
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +377
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds) +1421
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +137 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41 System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10 System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +66
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 executed) +138
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext) +475
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior) +239
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
+10 System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +97
[EntityCommandExecutionException: An error occurred while executing
the command definition. See the inner exception for details.]
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +181
System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext
context, ObjectParameterCollection parameterValues) +1282
System.Data.Entity.Core.Objects.<>c__DisplayClass7.b__6()
+184 System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +448 System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +270 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1
operation) +251
System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption) +645
System.Data.Entity.Core.Objects.ObjectQuery1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +68 System.Data.Entity.Internal.LazyEnumerator1.MoveNext() +68 System.Linq.Buffer1..ctor(IEnumerable1 source) +216
System.Linq.Enumerable.ToArray(IEnumerable1 source) +77 System.Web.Providers.QueryHelper.GetRolesNamesForUser(MembershipContext ctx, String applicationName, String username) +8129 System.Web.Providers.DefaultRoleProvider.GetRolesForUser(String username) +219 System.Web.Security.RolePrincipal.IsInRole(String role) +9612755 System.Linq.Enumerable.Any(IEnumerable1 source,
Func2 predicate) +146 System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +333 System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +379 System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor)
+143 System.Web.Mvc.Async.<>c__DisplayClass21.b__19(AsyncCallback
asyncCallback, Object asyncState) +1680
System.Web.Mvc.Async.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback
callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback,
Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate1 endDelegate, Object tag, Int32 timeout) +94 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559 System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate1 beginDelegate,
EndInvokeVoidDelegate1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588 System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate1 beginDelegate,
EndInvokeVoidDelegate1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback
callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151 System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate1 beginDelegate,
EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag,
Int32 timeout, SynchronizationContext callbackSyncContext) +106
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) +446
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+301 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.34009
Where might I have gone wrong?
I think that your problem is due to the new Memebership infrastructure in MVC5.
On This link: http://www.asp.net/mvc/tutorials/mvc-5/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2
I found the following tip which may help you:
If your app uses the User.IsInRole() method, add the following to the Web.config file.
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>
It appears you are very confused about authorization and authentication. As a quick and brief overview:
MVC 1-2 Used the default FormsAuthentication Framework. This required using the aspnet_regsql as Shai Aharoni mentioned in the comments.
MVC 3 was introduced with the SimpleMembership Provider Framework. This extended the default FormsAuthentication Model. Did not require aspnet_regsql but could be designed to be compatible with it.
MVC 4 was introduced with ASP.Net Identity 1.0. This completely removed the need for FormsAuthenication. Is not compatible with aspnet_regsql. This includes adding the following to the webconfig:
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
...
MVC 5 was released, and slightly later, ASP.Net Identity 2.0 was released. I'm pretty sure that Visual Studio 2013 with Update 1 or 2, now automatically uses ASP.Net Identity 2.0 (as they are forwards compatible 100%).
I added this into my web.config inside system.web section
What you've tried to do is add the now antiquated SimpleMembershipProvider and RoleProvider (Universal Providers) to ASP.Net Identity 1 or 2. This simply won't work out of the box, they are not compatible, they use different tables, different assemblies, etc.
If I load up the default MVC 5 template, which uses Identity 2.0 (with the TKey for User as string, just like 1.0), and a data source the looks like the following:
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication3-20140601125344.mdf;Initial Catalog=aspnet-WebApplication3-20140601125344;Integrated Security=True" />
The AuthrizeAttribute works, out-of-the-box with no changes made. They only way I can get the AuthorizeAttribute to not work, is if I add the AllowAnonymousAttribute at the controller level:
[AllowAnonymous]
public class HomeController
{
[Authorize]
public ActionResult Index()
{
return View();
}
}
The other possible but not probable problem is that you have Lazy Loading disabled on the ApplicationDbContext/IdentityDbContext AND are using an Identity version prior to 2.0-alpha1 as mentioned in a work item on codeplex.

ASP.NET MVC3 The requested name is valid, but no data of the requested type was found

NET MVC3 with Entity Framework 5 (DB First) application and all of the access to the db raises the same error
The requested name is valid, but no data of the requested type was found
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.Net.Sockets.SocketException: The requested name is valid, but no data of the requested type was found
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:
[SocketException (0x2afc): The requested name is valid, but no data of the requested type was found]
System.Net.Dns.GetAddrInfo(String name) +6603626
System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6) +106
System.Net.Dns.GetHostEntry(String hostNameOrAddress) +109
MySql.Data.Common.StreamCreator.GetDnsHostEntry(String hostname) +75
[Exception: Call to GetHostEntry failed after 00:00:00 while querying for hostname 'xxxxxxxx.db.1and1.com': SocketErrorCode=NoData, ErrorCode=11004, NativeErrorCode=11004.]
MySql.Data.Common.StreamCreator.GetDnsHostEntry(String hostname) +349
MySql.Data.Common.StreamCreator.GetHostEntry(String hostname) +36
MySql.Data.Common.StreamCreator.GetStreamFromHost(String pipeName, String hostName, UInt32 timeout) +70
MySql.Data.Common.StreamCreator.GetStream(UInt32 timeout) +204
MySql.Data.MySqlClient.NativeDriver.Open() +370
[MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]
MySql.Data.MySqlClient.NativeDriver.Open() +428
MySql.Data.MySqlClient.Driver.Open() +22
MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) +218
MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() +287
MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() +93
MySql.Data.MySqlClient.MySqlPool.GetConnection() +65
MySql.Data.MySqlClient.MySqlConnection.Open() +543
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +44
[EntityException: The underlying provider failed on Open.]
System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +203
System.Data.EntityClient.EntityConnection.Open() +104
System.Data.Objects.ObjectContext.EnsureConnection() +75
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +41
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +36
System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +72
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +23
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
domvaproject.Controllers.PropiedadesController.Index() +21
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) +182
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +256
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +22
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +190
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +311
System.Web.Mvc.Controller.ExecuteCore() +105
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +88
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +31
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.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628700
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
My hosting provider (1and1) tells me that the problem is mine, but i think that this problem is caused by some error in DNS. They told me that the error is in the code but it crashes on every connection
I got the same error due to my connection string. It included a port number, but the correct connection string has to be like this:
<add name="myConnectionString" connectionString="Server=localhost;Database=mydatabase;Uid=root;Pwd=password;Allow Zero Datetime=true" providerName="MySql.Data.MySqlClient"/>

How to publish web service in ASP.Net?

Below url is web service which I hosted: http://monocept.net/vlt/html/AutoComplete.asmx
when I am invoking this service it calls web method GetCompleteList(). This method implementation is defined in AutoComplete.asmx.cs file. When I invoking this service it throws exception as HTTP 404, where as in my local machine service is working fine and able to hit GetCompleteList() Web method.
The error page is actually dumping out the exception/stack trace in a HTML comment:
[HttpException]: The controller for path '/vlt/html/AutoComplete.asmx/GetCompleteList' was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I'm not familiar with MVC, so I really can't give you a solid answer, but researching that exception turns up a few results.
You haven't defined a controller for this path. It is MVC error. Your service doesn't has a business logic.
Have you ensured that you are excluding the route in your global.asax file?
routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");

Categories

Resources