I can't connect to a web service http request failed err400 - asp.net

I did use SQL Server Management Studio Express (free edition) to create my DB, Visual Studio Community (free edition) to create a web service SOAP through ASP.net (the WS just have 1 web method when you click it then show 5 empty fields), then i ran my WS in VS through option Debug in the Solution Configuration menu, after that the page open and i did check that my method insert the data in my DB and until here everything was correct, the data was inserted in the proper columns.
My problem start when i build the android app, the app have 5 empty fields that the user will fill and then send the info to the WS and put the data in the DB, but show me the next error:
org.ksoap2.transport.HttpResponseException: HTTP request failed, HTTP status: 400
at org.ksoap2.transport.HttpTransportSE.call
I read every thread about this problem, but none of that info solve my problem, i tried to make another project with 3 different variations but none of them work, i changed the localhost for my local ip, use 10.0.2.2:port, i add at the end "?wsdl", etc, etc.
I used SOAPUI to connect to test my WS, but when i try to connect from whatever location says me to did not found the page. Then i realized that maybe my App doesn't work because the WS only works for me and for nobody else, and need to put my WS in a real domain or something like that.
I'm very noob in this world, but the real objective that i have is that my app can get/add data in a database on the internet, for the purpose that the users can see/add data, i dont know if this way is the correct for that goal.
Any advice is welcome, please i'm searching info since 3 days ago and i cannot solve this.
Thanks in advance!
My android code is below:
package com.example.ejembd2;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView txtResultado;
private Button btnins;
private EditText txtTit;
private EditText txtDes;
private EditText txtAco;
private EditText txtPal;
private EditText txtFec;
private TextView txtResultado2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtCodigo = (EditText) findViewById(R.id.txtReg);
txtNombre = (EditText) findViewById(R.id.txtVal);
txtResultado = (TextView) findViewById(R.id.txtResultado);
btnInsertar = (Button) findViewById(R.id.btnInsertar);
btnActualizar = (Button) findViewById(R.id.btnActualizar);
btnEliminar = (Button) findViewById(R.id.btnEliminar);
btnConsultar = (Button) findViewById(R.id.btnConsultar);
btnins = (Button) findViewById(R.id.InsEnBD);
txtTit = (EditText) findViewById(R.id.T);
txtDes = (EditText) findViewById(R.id.D);
txtAco = (EditText) findViewById(R.id.A);
txtPal = (EditText) findViewById(R.id.P);
txtFec = (EditText) findViewById(R.id.F);
txtResultado2 = (TextView) findViewById(R.id.txtResultado2);
btnins.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String a = txtTit.getText().toString();
String b = txtDes.getText().toString();
String c = txtAco.getText().toString();
String d = txtPal.getText().toString();
String f = txtFec.getText().toString();
new insercion1().execute(a, b, c, d, f);
}
});
}
private class insercion1 extends AsyncTask<String,Integer,Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String a = params[0];
String b = params[1];
String c = params[2];
String d = params[3];
String f = params[4];
boolean resul = true;
final String NAMESPACE = "http://proof.net/";
/*final String URL = "http://10.0.2.2:50490/ServicioWebSoap/ServicioClientes.asmx"; //cambio*/
final String URL = "http://10.0.2.2:50490/ServicioClientes.asmx";
final String METHOD_NAME = "NuevoEvento";
final String SOAP_ACTION = "http://proof.net/NuevoEvento";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Titulo",a);
request.addProperty("Descripcion",b);
request.addProperty("Compania",c);
request.addProperty("Palabras",d);
request.addProperty("Fecha",f);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try
{
transporte.call(SOAP_ACTION, envelope);
Log.v("prueba1", ">>>>>>>>>");
SoapPrimitive resultado_xml = (SoapPrimitive) envelope.getResponse();
String res = resultado_xml.toString();
//My code in the .asmx return 1 if a row was added to the Table.
if (!res.equals("1"))
resul = false;
}
catch(
Exception e
)
{
e.printStackTrace();
resul = false;
}
return resul;
}
protected void onPostExecute(Boolean result) {
if (result)
txtResultado.setText("Insertado OK");
else
txtResultado.setText("Error!");
}
}
}
EDIT1: WSDL (im only using the WebMethod "NuevoEvento")
<wsdl:definitions xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://proof.net/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://proof.net/">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://proof.net/">
<s:element name="NuevoEvento">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="Titulo" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Descripcion" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Compania" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Palabras" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Fecha" type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="NuevoEventoResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="NuevoEventoResult" type="s:int"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="ListadoEventos">
<s:complexType/>
</s:element>
<s:element name="ListadoEventosResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="ListadoEventosResult" type="tns:ArrayOfEventos"/>
</s:sequence>
</s:complexType>
</s:element>
<s:complexType name="ArrayOfEventos">
<s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="Eventos" nillable="true" type="tns:Eventos"/>
</s:sequence>
</s:complexType>
<s:complexType name="Eventos">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="Id" type="s:int"/>
<s:element minOccurs="0" maxOccurs="1" name="Titulo" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Descripcion" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Compania" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Palabras" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Fecha" type="s:string"/>
</s:sequence>
</s:complexType>
<s:element name="NuevoEventoObjeto">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="evento" type="tns:Eventos"/>
</s:sequence>
</s:complexType>
</s:element>
<s:element name="NuevoEventoObjetoResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="NuevoEventoObjetoResult" type="s:int"/>
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
<wsdl:message name="NuevoEventoSoapIn">
<wsdl:part name="parameters" element="tns:NuevoEvento"/>
</wsdl:message>
<wsdl:message name="NuevoEventoSoapOut">
<wsdl:part name="parameters" element="tns:NuevoEventoResponse"/>
</wsdl:message>
<wsdl:message name="ListadoEventosSoapIn">
<wsdl:part name="parameters" element="tns:ListadoEventos"/>
</wsdl:message>
<wsdl:message name="ListadoEventosSoapOut">
<wsdl:part name="parameters" element="tns:ListadoEventosResponse"/>
</wsdl:message>
<wsdl:message name="NuevoEventoObjetoSoapIn">
<wsdl:part name="parameters" element="tns:NuevoEventoObjeto"/>
</wsdl:message>
<wsdl:message name="NuevoEventoObjetoSoapOut">
<wsdl:part name="parameters" element="tns:NuevoEventoObjetoResponse"/>
</wsdl:message>
<wsdl:portType name="ServicioClientesSoap">
<wsdl:operation name="NuevoEvento">
<wsdl:input message="tns:NuevoEventoSoapIn"/>
<wsdl:output message="tns:NuevoEventoSoapOut"/>
</wsdl:operation>
<wsdl:operation name="ListadoEventos">
<wsdl:input message="tns:ListadoEventosSoapIn"/>
<wsdl:output message="tns:ListadoEventosSoapOut"/>
</wsdl:operation>
<wsdl:operation name="NuevoEventoObjeto">
<wsdl:input message="tns:NuevoEventoObjetoSoapIn"/>
<wsdl:output message="tns:NuevoEventoObjetoSoapOut"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="ServicioClientesSoap" type="tns:ServicioClientesSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="NuevoEvento">
<soap:operation soapAction="http://proof.net/NuevoEvento" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="ListadoEventos">
<soap:operation soapAction="http://proof.net/ListadoEventos" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="NuevoEventoObjeto">
<soap:operation soapAction="http://proof.net/NuevoEventoObjeto" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="ServicioClientesSoap12" type="tns:ServicioClientesSoap">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="NuevoEvento">
<soap12:operation soapAction="http://proof.net/NuevoEvento" style="document"/>
<wsdl:input>
<soap12:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="ListadoEventos">
<soap12:operation soapAction="http://proof.net/ListadoEventos" style="document"/>
<wsdl:input>
<soap12:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="NuevoEventoObjeto">
<soap12:operation soapAction="http://proof.net/NuevoEventoObjeto" style="document"/>
<wsdl:input>
<soap12:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ServicioClientes">
<wsdl:port name="ServicioClientesSoap" binding="tns:ServicioClientesSoap">
<soap:address location="http://localhost:50490/ServicioClientes.asmx"/>
</wsdl:port>
<wsdl:port name="ServicioClientesSoap12" binding="tns:ServicioClientesSoap12">
<soap12:address location="http://localhost:50490/ServicioClientes.asmx"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
EDIT1: The data i posted to the service (only using the first webmethod)
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
namespace ServicioWebSoap
{
/// <summary>
/// Descripción breve de ServicioClientes
/// </summary>
[WebService(Namespace = "http://proof.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la línea siguiente.
// [System.Web.Script.Services.ScriptService]
public class ServicioClientes : System.Web.Services.WebService
{
[WebMethod]
public int NuevoEvento(string Titulo, string Descripcion, string Compania, string Palabras, string Fecha)
{
SqlConnection con = new SqlConnection(#"Data Source=SRCOMPUTADOR\SQLEXPRESS01;Initial Catalog=DBEventos;Integrated Security=True");
con.Open();
string sql = "INSERT INTO Eventos (Titulo, Descripcion, Compania, Palabras, Fecha) VALUES (#Titulo, #Descripcion, #Compania, #Palabras, #Fecha)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#Titulo", System.Data.SqlDbType.NVarChar).Value = Titulo;
cmd.Parameters.Add("#Descripcion", System.Data.SqlDbType.NVarChar).Value = Descripcion;
cmd.Parameters.Add("#Compania", System.Data.SqlDbType.NVarChar).Value = Compania;
cmd.Parameters.Add("#Palabras", System.Data.SqlDbType.NVarChar).Value = Palabras;
cmd.Parameters.Add("#Fecha", System.Data.SqlDbType.NVarChar).Value = Fecha;
int res = cmd.ExecuteNonQuery();
con.Close();
return res;
}
[WebMethod]
public Eventos[] ListadoEventos()
{
SqlConnection con = new SqlConnection(#"Data Source=SRCOMPUTADOR\SQLEXPRESS01;Initial Catalog=DBEventos;Integrated Security=True");
con.Open();
string sql = "SELECT id, Titulo, Descripcion, Compania, Palabras, Fecha FROM Eventos";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
List<Eventos> lista = new List<Eventos>();
while (reader.Read())
{
lista.Add(
new Eventos(reader.GetInt32(0),
reader.GetString(1),
reader.GetString(2),
reader.GetString(3),
reader.GetString(4),
reader.GetString(5)));
}
con.Close();
return lista.ToArray();
}
[WebMethod]
public int NuevoEventoObjeto(Eventos evento)
{
SqlConnection con = new SqlConnection(#"Data Source=SRCOMPUTADOR\SQLEXPRESS01;Initial Catalog=DBEventos;Integrated Security=True");
con.Open();
string sql = "INSERT INTO Eventos (Titulo, Descripcion, Compania, Palabras, Fecha) VALUES (#Titulo, #Descripcion, #Compania, #Palabras, #Fecha)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#Titulo", System.Data.SqlDbType.NVarChar).Value = evento.Titulo;
cmd.Parameters.Add("#Descripcion", System.Data.SqlDbType.NVarChar).Value = evento.Descripcion;
cmd.Parameters.Add("#Compania", System.Data.SqlDbType.NVarChar).Value = evento.Compania;
cmd.Parameters.Add("#Palabras", System.Data.SqlDbType.NVarChar).Value = evento.Palabras;
cmd.Parameters.Add("#Fecha", System.Data.SqlDbType.NVarChar).Value = evento.Fecha;
int res = cmd.ExecuteNonQuery();
con.Close();
return res;
}
}
}

The answer was my suposition; the WS only was a emulation (doesnt exist in the web), the solution was solved following the next steps:
Publish it with VS and making use of IIS Manager.
If problems arise with the WS, follow the instructions that support.microsoft.com deliver really works (i searched for days and the key was there).
Then in the URL for the HttpTransportSE call use your local ip substituting "localhost".

Related

fx:id="grid" stays null in controller

grid stays null when user clicks the button that calls 'pressLookUp' User is suppose to go from an old stage to the new one in the fxml file. And before the new window is shown, I want to add in values to the grids children from the database using grid.add(node, colIndex, rowIndex)
Controller:
package login;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import userGroups.User;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class studentOptionsController{
#FXML
private GridPane grid;//gridpane from ClassesToAdd
public void pressLookUp(ActionEvent event) throws IOException{
Parent userOption = FXMLLoader.load(getClass().getResource("ClassesToAdd.fxml"));
Scene classesToAddScene = new Scene(userOption);
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(classesToAddScene);
app_stage.show();
Connection c = null;
Statement stmt = null;
try{
c = DriverManager.getConnection("jdbc:sqlite:users.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Classes WHERE IDCLASSES= " + "5;");
int currentIndex = 0;
int currentRow = 0;
//assusming all columns are NOT NULL
while(rs.next()){
Label currentLabel = new Label();
currentLabel.setText(rs.getString("CLASSNAME"));
System.out.println(currentLabel.getText());
grid.add(currentLabel, 5, 0 );
/*if (rs.getString("SUSERNAME") != null && rs.getString("STUDENTPASS") != null){
String username = rs.getString("SUSERNAME");
System.out.println( "SUSERNAME = " + username );
String password = rs.getString("STUDENTPASS");
System.out.println("STUDENTPASS = " + password);
}*/
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
//System.exit(0);
}
System.out.println("Operation done successfully");
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<GridPane fx:id="grid" prefHeight="400.0" prefWidth="850"
xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="login.studentOptionsController">
<columnConstraints>
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="11" />
<ColumnConstraints percentWidth="12" /> <!-- This column for 'Add
Class' buttons ?-->
</columnConstraints>
<rowConstraints>
<RowConstraints />
</rowConstraints>
<children>
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Class Name" GridPane.columnIndex="0" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Size of Class" GridPane.columnIndex="1" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Spots Taken" GridPane.columnIndex="2" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Instructor" GridPane.columnIndex="3" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="CRN" GridPane.columnIndex="4" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Days" GridPane.columnIndex="5" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Time" GridPane.columnIndex="6" GridPane.rowIndex="0" />
<Label maxHeight="Infinity" maxWidth="Infinity" style=" -fx-border-color:gray; " text="Subject" GridPane.columnIndex="7" GridPane.rowIndex="0" />
<Button maxHeight="Infinity" maxWidth="Infinity" mnemonicParsing="false" onAction="#pressBack" style=" -fx-background-color:red; -fx-border-color:black" text="Back..." GridPane.columnIndex="8" GridPane.rowIndex="0" />
</children>
</GridPane>
Output on system:
Opened database successfully
java.lang.NullPointerException: null
Operation done successfully
No clue why this works but it does.
public void pressLookUp(ActionEvent event) throws IOException{
FXMLLoader loader = new FXMLLoader(getClass().getResource("ClassesToAdd.fxml"));
Parent userOption = loader.load();
grid = loader.getRoot();
Scene classesToAddScene = new Scene(userOption);
Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
app_stage.setScene(classesToAddScene);
app_stage.show();
Connection c = null;
Statement stmt = null;
try{
c = DriverManager.getConnection("jdbc:sqlite:users.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Classes WHERE IDCLASSES= " + "5;");
int currentIndex = 0;
int currentRow = 0;
//assusming all columns are NOT NULL
while(rs.next()){
Label currentLabel = new Label();
currentLabel.setText(rs.getString("CLASSNAME"));
System.out.println(currentLabel.getText());
grid.add(currentLabel, 0, 1 );
}
loader.setRoot(grid);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}

'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;" />

(413) Request Entity Too Large in WCF

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>

isAuthenticated() not working with my custom authentication provider .?

I'm new with spring security ,
I have made a custom authentication provider to check if the user haw access to the secured page or not via database.
every thing was ok, but when I added <intercept-url pattern="/home" access="isAuthenticated()" /> to security configuration an error occurs !
this is my userService :
public Authentication authenticate(Authentication auth) throws AuthenticationException {
Logger logger = null;
logger = Logger.getLogger(Logger.class.getName());
PropertyConfigurator.configure("src/main/resources/log4j.properties");
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
name= auth.getName();
pwd=auth.getCredentials().toString();
UsernamePasswordAuthenticationToken ret=null;
String select_auth= "select username,password from users where username=? and password=?";
try {
connection = dataSource1.getConnection();
preparedStatement = connection.prepareStatement(select_auth);
preparedStatement.setString(1,name);
preparedStatement.setString(2,pwd);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
logger.info("user <"+name+"> is connected");
ret= new UsernamePasswordAuthenticationToken(name, null);}
else
{
ret= null;
}
} catch (SQLException e) {
logger.error("SQLException: " + e.getMessage());
e.printStackTrace();
}
and this is my seurity-config
<http use-expressions="true" auto-config="true">
<form-login login-page="/login.jsp" default-target-url="/home"
authentication-failure-url="/403" />
<logout logout-success-url="/login" />
<intercept-url pattern="/home" access="isAuthenticated()" />
</http>
could someone help me ,or explain me what's the cause of the problem ?
Thanks in advance.

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