Web Service - issues in asp.net - asp.net

Issue with our web service - when trying to get the information from the web service we're getting an error: "404 not found".
Can anyone see what could be the problem?
We're expecting back a JSON string.
Service1.svc.vb
<ServiceContract(Namespace:="OurWebsiteURL-Here")>
<ServiceBehavior(Namespace:="OurWebsiteURL-Here")>
Public Class Service1
<OperationContract()>
<WebGet(UriTemplate:="/getPersonInfo/?personID={personID}&companyCode={companyCode}", BodyStyle:=WebMessageBodyStyle.Bare)>
Public Function getPersonInfo(ByVal personID As String, ByVal companyCode As String) As String
Dim dba As New DBAccess
Dim person As New PersonInfo
Dim m_SelPerson As String = String.Empty
Dim ds As DataSet = dba.GetPersonInfo(personID, companyCode)
If Not ds Is Nothing Then
Dim dr As DataRow = ds.Tables(0).Rows(0)
person = New PersonInfo
If Not String.IsNullOrEmpty(dr("UserID")) Then
person.UserID = Convert.ToInt32(dr("UserID"))
End If
person.PersonID = Convert.ToInt32(dr("PersonID"))
person.Company = dr("Company")
If Not IsDBNull(dr("Title")) Then
person.Title = dr("Title")
End If
If Not IsDBNull(dr("CellNum")) Then
person.CellNum = dr("CellNum")
End If
If Not IsDBNull(dr("EmergencyPhone")) Then
person.EmergencyPhone = dr("EmergencyPhone")
End If
If Not IsDBNull(dr("Email")) Then
person.Email = dr("Email")
End If
If Not IsDBNull(dr("PersonImageName")) Then
person.PersonImageName = dr("PersonImageName")
End If
'person.PersonImageName = dr("PersonImageName")
Dim oSerilzer As New System.Web.Script.Serialization.JavaScriptSerializer
m_SelPerson = oSerilzer.Serialize(person)
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8"
End If
'Return New MemoryStream(Encoding.UTF8.GetBytes(m_SelPerson))
Return m_SelPerson
End Function
PersonInfo.vb
<DataContract()>
Public Class PersonInfo
Private m_userID As Integer
Private m_personID As Integer
Private m_title As String
Private m_company As String
Private m_cellNum As String
Private m_emergencyPhone As String
Private m_email As String
Private m_PersonImageName As String
<DataMember()>
Public Property UserID() As Integer
Get
Return m_userID
End Get
Set(ByVal value As Integer)
m_userID = value
End Set
End Property
<DataMember()>
Public Property PersonID() As Integer
Get
Return m_personID
End Get
Set(ByVal value As Integer)
m_personID = value
End Set
End Property
<DataMember()>
Public Property Title() As String
Get
Return m_title
End Get
Set(ByVal value As String)
m_title = value
End Set
End Property
<DataMember()>
Public Property Company() As String
Get
Return m_company
End Get
Set(ByVal value As String)
m_company = value
End Set
End Property
<DataMember()>
Public Property CellNum() As String
Get
Return m_cellNum
End Get
Set(ByVal value As String)
m_cellNum = value
End Set
End Property
<DataMember()>
Public Property EmergencyPhone() As String
Get
Return m_emergencyPhone
End Get
Set(ByVal value As String)
m_emergencyPhone = value
End Set
End Property
<DataMember()>
Public Property Email() As String
Get
Return m_email
End Get
Set(ByVal value As String)
m_email = value
End Set
End Property
<DataMember()>
Public Property PersonImageName As String
Get
Return m_PersonImageName
End Get
Set(ByVal value As String)
m_PersonImageName = value
End Set
End Property
End Class
Web.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="LocalDBConnectionTest" connectionString="data source=URL;initial catalog=TEST;persist security info=True;user id=sa;password=test;Connection Timeout=60" providerName="System.Data.SqlClient" />
<customErrors mode="On"/>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime executionTimeout="4800" maxRequestLength="500000000"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="SoapEndpointBinding"
closeTimeout="00:10:00"
maxBufferPoolSize="250000000"
maxReceivedMessageSize="250000000"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00">
<readerQuotas maxDepth="4500000" maxStringContentLength="4500000" maxBytesPerRead="40960000" maxNameTableCharCount="250000000" maxArrayLength="4500000"/>
<security mode="Transport"/>
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding name="RestEndpointBinding"
closeTimeout="00:10:00"
maxBufferPoolSize="250000000"
maxReceivedMessageSize="250000000"
openTimeout="00:10:00"
receiveTimeout="00:10:00"
sendTimeout="00:10:00">
<readerQuotas maxDepth="4500000" maxStringContentLength="4500000" maxBytesPerRead="40960000" maxNameTableCharCount="250000000" maxArrayLength="4500000"/>
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="WCFDispatchWebService.Service1" behaviorConfiguration="ServiceBehavior">
<endpoint address="SOAP" binding="basicHttpBinding" contract="WCFDispatchWebService.Service1" bindingConfiguration="SoapEndpointBinding" bindingNamespace="OurURL-HERE" />
<endpoint address="REST" binding="webHttpBinding" contract="WCFDispatchWebService.Service1" bindingConfiguration="RestEndpointBinding" bindingNamespace="OurURL-HERE" behaviorConfiguration="RestEndpointBehavior"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="RestEndpointBehavior">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<security >
<requestFiltering>
<requestLimits maxAllowedContentLength="500000000"></requestLimits>
</requestFiltering>
</security>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
DBAccess
Public Function GetPersonInfo(ByVal personID As String, ByVal companyCode As String) As DataSet
Dim ds As DataSet = Nothing
Try
' Prepare the arguement list
Dim storedProc As String = "spGetPersonInfoFromPersonID"
Dim SqlParameterList As New List(Of SqlParameter)
SqlParameterList.Add(New SqlParameter("#inPersonID", Convert.ToInt32(personID)))
' Execute the SP and store the dataset
ds = SQLHelper.ExecuteNonQueryDataSet(Globals.GetConnectionStringMain(companyCode), CommandType.StoredProcedure, storedProc, SqlParameterList.ToArray())
' Check for an empty dataset
If ds.Tables(0).Rows.Count <= 0 Then
ds = Nothing
End If
Catch
End Try
Return ds
End Function
Error that we're getting after debugging and getting a Valid JSON File:
failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.
The request channel timed out while waiting for a reply after 00:00:59.9376004. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.
Server stack trace:
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Service1.getPersonInfo(String personID, String companyCode)
at Service1Client.getPersonInfo(String personID, String companyCode)
Inner Exception:
The HTTP request to 'http://localhost:56329/Service1.svc/SOAP' has exceeded the allotted timeout of 00:00:59.9680000. The time allotted to this operation may have been a portion of a longer timeout.
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
Inner Exception:
The operation has timed out
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

Related

Can't load custom httphandler over multiple projects

in my solution i have a couple of projects.
At my Allgemein.dll (General.dll) i have a custom httphandler which looks for pdf's and does something with it.
At every project in my solution i include the Allgemein.dll.
Now if i'm logged out of my application and i call a pdf, my httphandler works great.
But if i'm now login to my application and call a pdf, i got the following error: "The type "Allgemein.Handlers.FileProtectionHandler" in the assembly "Allgemein" could not be loaded."
What i'm doing wrong?
My web.config
<httpHandlers>
<add path="*.pdf" verb="*" validate="true" type="Allgemein.Handlers.FileProtectionHandler, Allgemein" />
</httpHandlers>
<handlers>
<add name="PDF" path="*.pdf" verb="*" type="Allgemein.Handlers.FileProtectionHandler, Allgemein" resourceType="Unspecified" />
</handlers>
My FileProtectionHandler.vb
Imports System
Imports System.Web
Imports System.Web.Security
Imports System.IO
Imports System.Web.SessionState
Namespace Allgemein.Handlers
Public Class FileProtectionHandler : Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "GET"
If Not context.User.Identity.IsAuthenticated Then
FormsAuthentication.RedirectToLoginPage()
Return
End If
Dim requestedFile As String = context.Server.MapPath(context.Request.FilePath)
If context.User.IsInRole("User") Then
SendContentTypeAndFile(context, requestedFile)
Else
context.Response.Redirect("~/Portal/Fehler403.aspx")
End If
Exit Select
End Select
End Sub
Private Sub IHttpHandler_ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
Throw New NotImplementedException()
End Sub
Private Function SendContentTypeAndFile(ByVal context As HttpContext, ByVal strFile As String) As HttpContext
context.Response.ContentType = GetContentType(strFile)
context.Response.TransmitFile(strFile)
context.Response.[End]()
Return context
End Function
Private Function GetContentType(ByVal filename As String) As String
Dim res As String = Nothing
Dim fileinfo As FileInfo = New FileInfo(filename)
If fileinfo.Exists Then
Select Case fileinfo.Extension.Remove(0, 1).ToLower()
Case "pdf"
res = "application/pdf"
Exit Select
End Select
Return res
End If
Return Nothing
End Function
End Class
End Namespace
After a joined effort with the OP it has been concluded that the MIR.Web.Allgemein is the root namespace.
In this case, the actual type name would be MIR.Web.Allgemein.Allgemein.Handlers.FileProtectionHandler which is the root namespace [dot] the actual namespace from code [dot] class name.

How to select a connection string dynamically from the config file from a session variable?

What am trying to create is a single login screen that connects the users to different databases depending on a certain code that each user has.
i have created some keys in my config file which corresponds to the user codes as follows
<appSettings>
<add key="ch001" value="h001"/>
<add key="ch002" value="h002"/>
</appSettings>
Then i have created connections string as follows
<connectionStrings>
<add name="Dbconn_h001" connectionString="XXX" providerName="XXX"/>
<add name="Dbconn_h002" connectionString="XXX" providerName="XXX"/>
</connectionStrings>
Then i have created a class to get the key value corresponding to the connection string as follows
Imports System.Web.Compilation
Imports System.CodeDom
Imports System.ComponentModel
Public Class ConnStringExpressionBuilder
Inherits ExpressionBuilder
Public Shared Function GetEvalData(ByVal expression As String, ByVal target As Type, ByVal entry As String) As Object
Return System.Configuration.ConfigurationManager.ConnectionStrings("Dbconn_" & System.Configuration.ConfigurationManager.AppSettings(HttpContext.Current.Session("code").ToString))
End Function
Public Overrides Function GetCodeExpression(ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, ByVal context As ExpressionBuilderContext) As CodeExpression
Dim type1 As Type = entry.DeclaringType
Dim descriptor1 As PropertyDescriptor = TypeDescriptor.GetProperties(type1)(entry.PropertyInfo.Name)
Dim expressionArray1(2) As CodeExpression
expressionArray1(0) = New CodePrimitiveExpression(entry.Expression.Trim())
expressionArray1(1) = New CodeTypeOfExpression(type1)
expressionArray1(2) = New CodePrimitiveExpression(entry.Name)
Return New CodeCastExpression(descriptor1.PropertyType, New CodeMethodInvokeExpression(New CodeTypeReferenceExpression(MyBase.GetType()), "GetEvalData", expressionArray1))
End Function
End Class
The issue is
System.Configuration.ConfigurationManager.AppSettings(HttpContext.Current.Session("code").ToString)
returns a null reference
using(SqlConnection conn = new SqlConnection())
{
var connString=ConfigurationManager.AppSetting["keyname"];
conn.ConnectionString = connString;
// using the code here...
}
and in config file save like
<add key="ch001" value="YourConnectionString" />
After a long hustle i figured it out i created this expression builder class
Public Class ConnStringExpressionBuilder
Inherits ExpressionBuilder
Public Shared Function GetEvalData(ByVal expression As String, ByVal target As Type, ByVal entry As String) As Object
Return System.Configuration.ConfigurationManager.ConnectionStrings(System.Configuration.ConfigurationManager.AppSettings(HttpContext.Current.Session("code").ToString())).ToString()
End Function
Public Overrides Function GetCodeExpression(ByVal entry As BoundPropertyEntry, ByVal parsedData As Object, ByVal context As ExpressionBuilderContext) As CodeExpression
Dim type1 As Type = entry.DeclaringType
Dim descriptor1 As PropertyDescriptor = TypeDescriptor.GetProperties(type1)(entry.PropertyInfo.Name)
Dim expressionArray1(2) As CodeExpression
expressionArray1(0) = New CodePrimitiveExpression(entry.Expression.Trim())
expressionArray1(1) = New CodeTypeOfExpression(type1)
expressionArray1(2) = New CodePrimitiveExpression(entry.Name)
Return New CodeCastExpression(descriptor1.PropertyType, New CodeMethodInvokeExpression(New CodeTypeReferenceExpression(MyBase.GetType()), "GetEvalData", expressionArray1))
End Function
End Class
Then in my markup i call the class like this
<asp:SqlDataSource ID="Ds" runat="server" ProviderName="Mysql.Data.MysqlClient"
ConnectionString="<%$ ConnStringExpression:Dbconn %>" SelectCommand="XXX"></asp:SqlDataSource>
Then from the code behind
Using conn = getConnect(System.Configuration.ConfigurationManager.AppSettings(Session("code").ToString()))
conn.Open()
Try
//logic
Catch ex As Exception
End Try
conn.Close()
End Using

'System.Web.HttpException' Additional information: Unable to connect to SQL Server database

LTL; FTP here.
I'm doing an eCommerce site following Shakeel Osmani's Tutorial here.
The issue arises when I try to register a new user in the website, it throws an "'System.Web.HttpException' Additional information: Unable to connect to SQL Server database." exception, and I can't find the problem anywhere.
I'm using VS2015 codefirst approach, and the code for the AccountsController is the following:
using System;
using System.Web.Mvc;
using System.Web.Security;
using eProject.Models;
namespace eProject.Controllers
{
public class AccountsController : Controller
{
private void MigrateShoppingCart(string userName)
{
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.MigrateCart(userName);
Session[ShoppingCart.CartSessionKey] = userName;
}
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
MigrateShoppingCart(model.UserName);
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.EmptyCart();
return RedirectToAction("Index", "Home");
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
MigrateShoppingCart(model.UserName);
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather
// than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("ChangePasswordSuccess");
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult ChangePasswordSuccess()
{
return View();
}
#region Status Codes
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
}
}
My Web.config is:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="enableSimpleMembership" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<modules>
<remove name="RoleManager" />
</modules>
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
I have to deliver this very soon (Class project) and I have followed pretty much every answer I could find about this in this and other forums, like adding a
<remove name="RoleManager" />
tag in web.config, funny thing is that when I add the connection string:
<connectionStrings>
<add name="MvcAffableBean" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MvcAffableBean;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
the webapp doesn't start at all.
Please help!
The complete exception is:
System.Web.HttpException was unhandled by user code
ErrorCode=-2147467259
HResult=-2147467259
Message=Unable to connect to SQL Server database.
Source=System.Web
WebEventCode=0
StackTrace:
at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.EnsureDBFile(String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
at System.Web.Security.SqlMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status)
at System.Web.Security.Membership.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status)
at eProject.Controllers.AccountsController.Register(RegisterModel model) in c:\users\hermes lizama\documents\visual studio 2015\Projects\eProject\eProject\Controllers\AccountsController.cs:line 75
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
InnerException:
ErrorCode=-2147467259
HResult=-2147467259
Message=Unable to connect to SQL Server database.
Source=System.Web
WebEventCode=0
StackTrace:
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
InnerException:
Class=20
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=0
Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Number=-1
Server=""
Source=.Net SqlClient Data Provider
State=0
StackTrace:
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
InnerException:
I'm working on same sample project and I had same issue you have.
I fixed it by adding config and connection string
<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="SqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlConn"
applicationName="MembershipAndRoleProviderSample"
enablePasswordRetrieval="false"
enablePasswordReset="false"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
and
<add name="SqlConn" providerName="System.Data.SqlClient" connectionString="Data Source=.\sqlexpress;Initial Catalog=aspnetdb;Integrated Security=True;" />

webService request failed with HTTP status 404

I have problem with sending a big file via webService (System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse).
Everything works fine when the file is smaller then 20 MB, if it's bigger i get a response with 404 code.
Exception Information
Exception Type: System.Net.WebException
Status: ProtocolError
Response: System.Net.HttpWebResponse
Message: The request failed with HTTP status 404: Not Found.
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object[] ReadResponse(System.Web.Services.Protocols.SoapClientMessage, System.Net.WebResponse, System.IO.Stream, Boolean)
HelpLink: NULL
Source: System.Web.Services
StackTrace Information
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ie.osds.DocumentsTransferBLL.FSDMZRepositoryService.FileStreamingWebService.UploadScanning(DateTime DateCreated, String Title, String FileName, String ReferenceNumber, String Author, String DocumentType, XmlNode IndexData, Byte[] Content, Nullable`1 IsCompressed, Nullable`1 Version, DateTime DateReceived, String CreatedBy, String OrigDocumentGUID)
at ie.osds.DocumentsTransferBLL.Actions.ActionsHelper.UploadDocumentToDMZFileStreaming(FileStreamingWebService fsDMZWebService, SPQDocument spqDocument, String documentReferenceNumber, String documentAuthor, String documentType, Byte[] documentContent, String version, DateTime dateReceived)
at ie.osds.DocumentsTransferBLL.Actions.DocumentsUploadAction.Upload()*
Sounds like your file upload is timing out:
You can trap this error in your global.asax to see if this is the case:
Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As System.EventArgs)
Dim context As HttpContext = HttpContext.Current.ApplicationInstance.Context
If Not IsNothing(context) Then
If Not context.Response.StatusCode = HttpStatusCode.OK Then
'Detect file upload exceeded max length:
If context.Response.StatusCode = 404 And
context.Response.SubStatusCode = 13 Then
'clear the previous error page content:
context.Response.Clear()
'redirect to custom error page:
context.Server.Transfer("~/error.aspx?code=404.13", False)
End If
End If
End If
End Sub
You can also increase the request length in your web.config like so:
<system.web>
<httpRuntime maxRequestLength="29296" />
</system.web>
Note: Value is in Kbytes
If there is a webservice reference in web application just delete that then Rebuild,run the webservice and then again add that webservice reference to the web application.

ConnectionStringSettings NullReference Error

I have the following settings in my web.config, as a child of the configuration element:
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
In the code behind where I wish to retrieve the connection string, I placed:
using System.Configuration
...
var connStringObject = ConfigurationManager.ConnectionStrings["GingerlimeDB"];
string connectionString = connStringObject.ConnectionString;
Console.WriteLine(connectionString);
I don't get to the console output, instead it shows:
Object reference not set to an instance of an object.
How do I get the Connection String out of the web config?
Assuming your web.config file looks like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear />
<add name="GingerlimeDB"
connectionString="Data Source=localhost;
Integrated Security=False;
Initial Catalog=dbname;
User Id=accountname;
Password=password;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You should be able to access the connection string exactly like you showed in your code. I use something nearly identical:
using System.Configuration;
....
internal bool OpenDatabaseConnection()
{
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
dbConnection = new SqlCeConnection(connectionString);
dbConnection.Open();
return true;
}
catch (SqlCeException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (InvalidOperationException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ArgumentException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
catch (ConfigurationErrorsException ex)
{
this.errorLogging = new ErrorLogging(ex.Message, ex.Source, ex.HelpLink, ex.GetType().ToString());
}
return false;
}
Which line is actually causing the NullReference exception? (object not set to an instance of an object)?

Resources