(413) Request Entity Too Large in WCF - asp.net

Trying so send Array size of 1227136 and getting error 413
This is how I am sending the data from a wreb application-
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:59624/RestServiceImpl.svc/PostFileRest");//Path for local
request.Timeout = Timeout.Infinite;
request.KeepAlive = true;
request.ContentType = "application/vnd.ms-excel";
/*---------------------------------------------------------------------------*/
string excelTojson = excelToJson();
byte[] fileData = Encoding.ASCII.GetBytes(excelTojson);
/*---------------------------------------------------------------------------*/
request.ContentLength = fileData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK);
string responseMessage = string.Empty;
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseMessage = sr.ReadToEnd();
}
Response.Write(responseMessage);
}
#region excelToJson
public string excelToJson()
{
var pathToExcel = #"E:\My_Work\MVC\Test1.xlsx";
OleDbConnection MyConnection;
DataTable dt;
OleDbDataAdapter MyCommand;
MyConnection = new OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + pathToExcel + "';Extended Properties='Excel 12.0 Xml;HDR=YES'");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
dt = new DataTable();
MyCommand.Fill(dt);
MyConnection.Close();
string jsonString = string.Empty;
return jsonString = JsonConvert.SerializeObject(dt);
}
#endregion
My WCF code where I am receiving the data when I am sending small amount of data then it is working fine. But I want to send large data.
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "PostFileRest")]
string PostFileRest(Stream fileContents);
}
public class RestServiceImpl : IRestServiceImpl
{
public string PostFileRest(Stream fileContents)
{
var httpRequest = HttpContext.Current.Request;
//var filePath = "C:\\file.xls"; //excel filePath for local
//var filePath = "D:\\Forecast\\ExcelOutput\\output.xls"; //excel filePath for 19 server
//StreamReader r = new StreamReader(HttpContext.Current.Request.InputStream);
//string jsonBody = r.ReadToEnd(); // jsonBody is empty!!
var bites = httpRequest.TotalBytes;
//Convert stream to byte array
byte[] reqBytes = readRequest(fileContents, bites);
byte[] decodedReqBytes = HttpUtility.UrlDecodeToBytes(reqBytes);
string json = System.Text.Encoding.UTF8.GetString(reqBytes);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
//MemoryStream stream = new MemoryStream(reqBytes);
//FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
//stream.WriteTo(file);
//file.Close();
//stream.Close();
string responseJson = TalkToDll.ForecastData(dt);
return responseJson;
}
#region Convert Stream to byte array
private byte[] readRequest(Stream fileContents, int bites)
{
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
int BUFFER_SIZE = bites;
int iRead = 0;
int idx = 0;
Int64 iSize = 0;
memStream.SetLength(BUFFER_SIZE);
while (true)
{
byte[] reqBuffer = new byte[BUFFER_SIZE];
try
{
iRead = fileContents.Read(reqBuffer, 0, BUFFER_SIZE);
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
if (iRead == 0)
{
break;
}
iSize += iRead;
memStream.SetLength(iSize);
memStream.Write(reqBuffer, 0, iRead);
idx += iRead;
}
byte[] content = memStream.ToArray();
memStream.Close();
return content;
}
#endregion
}
My app.config-
<?xml version="1.0"?>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<!--<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true"/>-->
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1"/>
<httpModules>
<!--<add name="WcfReadEntityBodyModeWorkaroundModule" type="ForecastREST_API.WcfReadEntityBodyModeWorkaroundModule, ForecastREST_API" />-->
</httpModules>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="myBinding" messageEncoding="Text" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" transferMode="Streamed" >
<readerQuotas maxDepth="64" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
<!--1227136-->
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="ForecastREST_API.RESTServiceImplBehavior" name="ForecastREST_API.RestServiceImpl">
<endpoint address="http://localhost:59624/RestServiceImpl.svc" binding="webHttpBinding" contract="ForecastREST_API.IRestServiceImpl" behaviorConfiguration="Web">
<!--<endpoint address="http://data-center:81/ForecastREST_API/RestServiceImpl.svc" binding="webHttpBinding" contract="ForecastREST_API.IRestServiceImpl" behaviorConfiguration="Web">-->
<identity>
<!--<dns value="localhost:59624"/>-->
<!--<dns value="data-center:81"/>-->
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="Web">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
<dispatcherSynchronization asynchronousSendEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ForecastREST_API.RESTServiceImplBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<!--<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>-->
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
<!--<modules>
<add name="WcfReadEntityBodyModeWorkaroundModule" type="ForecastREST_API.WcfReadEntityBodyModeWorkaroundModule, ForecastREST_API" />
</modules>-->
</system.webServer>

I have changed the WCf application app.config and solve the issue-
I have only add bindingConfiguration="myBinding" and change basicHttpBinding to webHttpBinding.
Here is the new code-
<bindings>
<webHttpBinding>
<binding name="myBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" transferMode="Streamed" >
<readerQuotas maxDepth="64" maxArrayLength="2147483647" maxStringContentLength="2147483647"/>
</binding>
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="ForecastREST_API.RESTServiceImplBehavior" name="ForecastREST_API.RestServiceImpl">
<endpoint address="http://localhost:59624/RestServiceImpl.svc" binding="webHttpBinding" contract="ForecastREST_API.IRestServiceImpl" behaviorConfiguration="Web" bindingConfiguration="myBinding">
</identity>
</endpoint>
<endpoint address="mex" binding="webHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="Web">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" />
<dispatcherSynchronization asynchronousSendEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ForecastREST_API.RESTServiceImplBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>

Related

Web Service - issues in 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)

Not working login with roles (web forms)

I want create a authentication module with 3 roles in asp.net web forms.
I created a simple database with one table user (id, login, password, role).
I have a 3 roles: user, user2 and admin.
I would like to users with specific roles were redirected to individual pages.
Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication6
{
public partial class Login : System.Web.UI.Page
{
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbtestConnectionStrings"].ConnectionString;
SqlConnection _connection= new SqlConnection(DatabaseConnectionString);
protected void Page_Load(object sender, EventArgs e) {
}
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
var comm = new SqlCommand("select * from user where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
var rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd["login"].ToString();
string role = rd["role"].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
}
}
}
}
Result:
web.config
<?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=169433
-->
<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>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<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>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<connectionStrings>
<add name="dbtestEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ROG-KOMPUTER\SQLEXPRESS;initial catalog=dbtest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="dbtestConnectionString" connectionString="Data Source=ROG-KOMPUTER\SQLEXPRESS;Initial Catalog=dbtest;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Can see two flaws
User is a keyword and you are using that as a table name
When assigning parameter value you are specifiying #
try below code
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
SqlCommand comm = new SqlCommand("select login,role from [user] where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd[0].ToString();
string role = rd[1].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
rd.Close();
_connection.Close();
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
}
}
Its look like that:
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
var comm = new SqlCommand("select login,role from [user] where login=#login and password=#password", _connection);
comm.Parameters.AddWithValue("#login", LoginUser.UserName);
comm.Parameters.AddWithValue("#password", LoginUser.Password);
_connection.Open();
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Session["UserName"] = rd[0].ToString();
string role = rd[1].ToString();
if (role == "user") Response.Redirect("User/User.aspx");
else if (role == "user2") Response.Redirect("User2/User.aspx");
else Response.Redirect("Admin/Admin.aspx");
}
}
else
{
LoginUser.FailureText = "ERROR";
}
rd.Close();
_connection.Close();
}
catch (Exception exception)
{
Response.Write(exception.StackTrace);
Label1.Text = exception.Message;
}
}

Uploaded website does not sent emails

I have uploaded my website to a known hosting server and i have a contact form, the weird thing is that when i run the website from visual studio (asp.net language) is sending the emails fine on my inbox.From the time that i uploaded it on the hosting server it gives the error: failure sending the email.I am using smtp.gmail.com, port:587,username and pass and ssl enabled.
protected void sendClientMail(string emailto)
{
try
{
var mail = new MailMessage
{
BodyEncoding = Encoding.UTF8,
From = new MailAddress(ConfigurationManager.AppSettings["MAILFROM"])
};
mail.To.Add(emailto);
mail.Bcc.Add(ConfigurationManager.AppSettings["MAILBCC"]); //sends to my email also
mail.Subject=ConfigurationManager.AppSettings["CLIENT-MAILSUBJECT"];
mail.IsBodyHtml = true;
#region //Load Email Control and get HTML string
string mailBody = "";
{
PrintPlaceHolder.Visible = true;
var sb = new StringBuilder();
var writer = new HtmlTextWriter(new StringWriter(sb));
var emailctl = LoadControl("~/Controls/ClientEmail.ascx") as ClientEmail;
if (emailctl != null)
{
emailctl.Name = txtName.Text;
emailctl.IntroName = txtName.Text + " " + txtSurname.Text;
emailctl.Surname = txtSurname.Text;
emailctl.Mobile = txtMobile.Text;
emailctl.Phone = txtPhone.Text;
emailctl.City = txtCity.Text;
emailctl.Street = txtStreet.Text;
emailctl.Message = txtmessage.Text;
emailctl.Email = txtEmail.Text;
emailctl.Country = ddlCountry.SelectedValue;
PrintPlaceHolder.Controls.Add(emailctl);
emailctl.RenderControl(writer);
}
mailBody = sb.ToString();
if (emailctl != null)
{
emailctl.Dispose();
}
writer.Dispose();
sb.Clear();
PrintPlaceHolder.Visible = false;
}
#endregion
mail.Body = mailBody;
//mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential (ConfigurationManager.AppSettings["MAILFROM"], ConfigurationManager.AppSettings["PASS"]);
client.Host = ConfigurationManager.AppSettings["SMTPSERVER"];
client.Port = Convert.ToInt32(ConfigurationManager.AppSettings["SMTPPORT"]);
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl= false;
//client.UseDefaultCredentials = true;
client.Send(mail);
clearFields();
Response.Write("<script>alert('"+ConfigurationManager.AppSettings["MAILSUCCESS"]+"');</script>");
}
catch (Exception e)
{
Response.Write("<script>alert('"+ ConfigurationManager.AppSettings["MAILFAIL"] +" Error: "+e+"')</script>");
}
}//end method
Web.config file code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<add key="CLIENT-MAILSUBJECT" value="Mario Website - Confirmation Email"/>
<add key="MY-MAILSUBJECT" value="Mario Website - Email Sent"/>
<add key="MAILFROM" value="mariotec#mario26tech.com"/>
<add key="MAILBCC" value="nikolaou_marios#hotmail.com"/>
<add key="SMTPSERVER" value="sns41.win.hostgator.com"/>
<add key="SMTPPORT" value="26"/>
<add key="PASS" value="pass"/>
<add key="MAILSUCCESS" value="Email was sent successfully, thank you for your interest!!!"/>
<add key="MAILFAIL" value="There was an error while sending the email."/>
</appSettings>
<system.webServer>
<defaultDocument enabled="true">
<files>
<clear/>
<add value="Index.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
I have contacted the hosting provider without any help.
Thanks in advance.

Change provider connectionstring of sessionState aspnet at runtime

in order to change the connection string of the providers in aspnet membership with
custom provider(nauckit) I use this:
var connectionStringField = Membership.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (connectionStringField != null)
connectionStringField.SetValue(Membership.Provider, connectionString);
var roleField = Roles.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (roleField != null)
roleField.SetValue(Roles.Provider, connectionString);
var profileField = ProfileManager.Provider.GetType().GetField("m_connectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (profileField != null)
profileField.SetValue(ProfileManager.Provider, connectionString);
Where connectionstring is the connectionstring I want.
But I cannot change for the sessionState.
My webconfig is like this:
<membership defaultProvider="PgMembershipProvider">
<providers>
<clear />
<add name="PgMembershipProvider" type="NauckIT.PostgreSQLProvider.PgMembershipProvider" connectionStringName="myConnection1" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" maxInvalidPasswordAttempts="100" passwordFormat="Hashed" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="PgRoleProvider" cacheRolesInCookie="true" cookieName=".AspNetRoles" cookiePath="/" cookieProtection="All" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieTimeout="30" maxCachedResults="25">
<providers>
<clear />
<add name="PgRoleProvider" type="NauckIT.PostgreSQLProvider.PgRoleProvider" connectionStringName="myConnection1" />
</providers>
</roleManager>
<profile enabled="true" defaultProvider="PgProfileProvider">
<providers>
<clear />
<add name="PgProfileProvider" type="NauckIT.PostgreSQLProvider.PgProfileProvider" connectionStringName="myConnection1" />
</providers>
<properties>
<add name="property1" type="long"/>
</properties>
</profile>
<sessionState mode="Custom" customProvider="PgSessionStateStoreProvider">
<providers>
<clear />
<add name="PgSessionStateStoreProvider" type="NauckIT.PostgreSQLProvider.PgSessionStateStoreProvider" enableExpiredSessionAutoDeletion="true" expiredSessionAutoDeletionInterval="60000" enableSessionExpireCallback="false" connectionStringName="myConnection1" />
</providers>
</sessionState>
Any help?
Thanks!
Just call global.SetStore in any IHttpModule that you have on your website.
DAMN i'm so happy this worked.
Global.asax.cs:
private FieldInfo StorePrivateMemberInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
public void SetStore()
{
var store = StorePrivateMemberInfo.GetValue(this.Modules["Session"]);
if (store == null || !(store is Microsoft.Web.SessionState.SqlInMemoryProvider))
{
var config = new NameValueCollection();
var cnn = "Your connection string";
config.Add("connectionString", cnn);
config.Add("timeout", "30");
simp = new Microsoft.Web.SessionState.SqlInMemoryProvider();
simp.Initialize("SqlInMemoryProvider", config);
StorePrivateMemberInfo.SetValue(this.Modules["Session"], simp);
}
Session["GLOBAL_ASAX_CHECK"] = true;
}

Rest WCF server "The remote server returned an error: (400) Bad Request." content larger than 64k

The problem is related to WCF configuration hell, I have developed a wcf rest server and i will be needing it to use with iPhone and android client. Problem is that my custom configuration i think is not picking up because data larger than 64kb give The remote server returned an error: (400) Bad Request. on client. Here is my code
Server Configurations:
<bindings>
<webHttpBinding>
<binding name="customHttpsBinding" openTimeout="00:10:00"
receiveTimeout="00:10:00" sendTimeout="00:30:00" maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" transferMode="Streamed" crossDomainScriptAccessEnabled="true" >
<readerQuotas maxDepth="999999999" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2097151" />
<security mode="Transport">
<transport proxyCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehaviour">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
automaticFormatSelectionEnabled="false" faultExceptionEnabled="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="customServiceBehavior" >
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" >
</serviceHostingEnvironment>
</system.serviceModel>
Server Method:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/content?contributorId={contributorId}&marketId={marketId}&fileExtension={fileExtension}",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
ActionResult PostUerContent(string contributorId,int marketId,string fileExtension, Stream streamContent);
Global.asax:
protected void Application_Start(object sender, EventArgs e)
{
ServiceRoute serviceRoute = new ServiceRoute("api", new WebServiceHostFactory(), typeof(MobileAPI));
RouteTable.Routes.Add(serviceRoute);
}
Client Side Code (.Net)
Stream fileStream = new FileStream(Server.MapPath("~/desert_.jpg"), FileMode.Open);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://shaq.***.local/mobile/api/content?contributorId=10634&marketid=2&fileExtension=.jpg");
Stream serverStream = null;
try
{
request.ContentType = "application/plain";
request.Method = "POST";
request.KeepAlive = true;
request.ContentLength = fileStream.Length;
request.SendChunked = true;
request.AllowWriteStreamBuffering = false;
serverStream = request.GetRequestStream();
byte[] buffer = new byte[16384];
while (true)
{
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
serverStream.Write(buffer, 0, bytesRead);
}
else
{
break;
}
}
request.GetResponse();
}
catch (Exception ex)
{ }
finally
{
serverStream.Close();
fileStream.Close();
}

Resources