Getting an Error while Accessing Web Service - c#

I am working on one Console Application and in that I am using a web service but I am getting an error While accessing that service:
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
<head>
<title>Runtime Error</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>
This is my code:
namespace ConsoleWebService
{
class MainDataService
{
static void Main(string[] args)
{
Console.WriteLine("New Account GUID="+CreateAccount("GTLDEV","New Account1"));
Console.ReadKey();
}
private static string CreateAccount(string organizationName, string accountName)
{
try
{
CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
myCrm.Url = GetCrmServiceForOrganization(organizationName);
CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
myToken.AuthenticationType = 0;
myToken.OrganizationName = organizationName;
myCrm.CrmAuthenticationTokenValue = myToken;
myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;
CrmSdk.account newAccount = new CrmSdk.account();
newAccount.name = accountName;
newAccount.address1_country = "India";
newAccount.address1_city = "Mumbai";
CrmSdk.Lookup objLookup=new CrmSdk.Lookup();
objLookup.type= "account";
objLookup.Value= new Guid("A8A58DB6-5364-E111-9493-00E04C39161E");
newAccount.parentaccountid = objLookup;
CrmSdk.Lookup objLookup1 = new CrmSdk.Lookup();
objLookup1.type = "contact";
objLookup1.Value = new Guid("1EDE79DD-FC5D-E111-9493-00E04C39161E");
newAccount.primarycontactid = objLookup1;
CrmSdk.Picklist pl = new CrmSdk.Picklist();
pl.name = "address1_addresstypecode";
pl.Value = 1;
newAccount.address1_addresstypecode = pl;
Guid newAccountId = myCrm.Create(newAccount);
return newAccountId.ToString();
}
catch (System.Web.Services.Protocols.SoapException soapEx)
{
Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText + " " + soapEx.ToString());
return soapEx.Detail.InnerText + " " + soapEx.ToString();
}
catch (Exception ex)
{
Console.WriteLine("General exception: " + ex.ToString());
return "General exception: " + ex.ToString();
}
}
private static string GetCrmServiceForOrganization(string organizationName)
{
string urlResult = "";
CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();
//myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
System.Net.CredentialCache.DefaultNetworkCredentials.Password = "gtl12#";
myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();
CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
{
Console.WriteLine("Organization = " + tDetail.OrganizationName);
if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
{
return tDetail.CrmServiceUrl;
}
}
return urlResult;
}
}
}

Related

How to check if certain data is already in the database?

Im doing a Project for my internship right now and I want to know how to get data from html and from the database and compare if the html data already exists in the database.
I have tried to run it but now I always get the localhost not found error.
HTML
Edit: The Context and the Database are working fine.
#{
ViewData["Title"] = "Home Page";
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Starter</title>
<style>
p {
margin-top: 30%;
margin-left: 20%;
margin-right: 20%;
font-family: Arial;
font-size: 25px;
text-align: center;
}
#Code {
border: 2px solid black;
}
</style>
</head>
<body>
<h1>249765876358312345655</h1>
<p>
Eingabe des Maschinen Codes:
<br />
<!-- Here is the important stuff for this aka HTML data-->
<input id="Code"
name="code"
pattern=""
size="30"
spellcheck="false"
title="Maschine Code"
value="">
</p>
<script>
var x = document.getElementById("Code");
x.addEventListener('input', function (event) {
x = document.getElementById("Code").value;
let vars = x;
let digits = vars.match(/^\d{13}(\d{6})\d{2}$/)[1];
let stringDigits = digits.toString();
if (stringDigits.length == 6 && vars.length == 21) {
window.location.href = '/home/Kontrolle';
document.getElementById("Code").innerHTML = "";
localStorage.setItem("Code_Kurz", stringDigits);
}
}
);
</script>
</body>
</html>
Controller
namespace Qualitätskontrolle.Controllers
{
public class HomeController : Controller
{
Boolean newID;
[HttpPost]
public IActionResult StartPage(string Code)
{
try
{
ViewData["Code"] = Code;
ApplicationDbContext dbContext = new ApplicationDbContext();
var Ergebnisse = dbContext.Result.ToArray();
for (int i = 0; i < Ergebnisse.Length; i++)
{
if (!Ergebnisse[i].Equals(ViewData["Code"]))
{
//Create New Page
newID = true;
}
else
{
newID = false;
}
return View();
}
}
catch
{
return View();
}
return View();
}
}
The result should be that a new site opens depending on wheter its a new Code or an old one.
Can you please check with this approach?
Considered that Code is the name of the column of the Result table in with the value of Code is getting saved.
var Ergebnisse = dbContext.Result.FirstOrDefault(x => x["Code"] == ViewData["Code"].ToString());
if(Ergebnisse != null)
{
// Means the item with same code exist
}
else
{
// Means the item with same code is not exist
}
So, the above code will check for the row having a value is code column which is equal to the value that we are giving[ViewData["Code"]], if no such value is found, then null will be assigned to Ergebnisse. A simple if..else can be used to check the value

How can I get rid of an error that says "ByteArray Objects Cannot be Converted to Strings" in my ASP.NET MVC 5 application?

I am using the following code to POST XML data to a remote server.
public async Task<ActionResult> Index(Transmission t)
{
ViewBag.ErrorMessage = "";
ViewBag.OtherMessage = "";
ViewBag.ResponseHtml = "";
try
{
var xmlSerializer = new XmlSerializer(typeof(Transmission));
XmlWriterSettings xws = new XmlWriterSettings();
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", "");
xws.OmitXmlDeclaration = true; //omit the xml declaration line
using (StringWriter sw = new StringWriter())
{
XmlWriter writer = XmlWriter.Create(sw, xws);
xmlSerializer.Serialize(writer, t, ns);
var contentData = sw.ToString();
var httpContent = new StringContent(contentData, Encoding.UTF8, "application/xml");
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 1, 0);
var response = await httpClient.PostAsync("theUrl", httpContent);
ViewBag.ResponseHtml = await response.Content.ReadAsStringAsync();
return View("Error"); //TODO: change this to success when I get the 500 error fixed
}
}
catch (Exception ex)
{
string message = ex.Message;
ViewBag.ErrorMessage = ex.Message;
return View("Error");
}
}
The response that I am getting is saying "ByteArray objects cannot be converted to strings." I haven't been given many details about the system to which I am posting this data, only that it using Adobe ColdFusion (which I know next to nothing about). Is there something that I can do on my side to fix this problem?
Edit
The response HTML I am getting is this:
<head>
<title>Error Occurred While Processing Request</title>
<script language="JavaScript">
function showHide(targetName) {
if( document.getElementById ) {
// NS6+
target = document.getElementById(targetName);
} else if( document.all ) {
// IE4+
target = document.all[targetName];
}
if( target ) {
if( target.style.display == "none" ) {
target.style.display = "inline";
} else {
target.style.display = "none";
}
}
}
</script>
</head>
<body>
<font style="COLOR: black; FONT: 16pt/18pt verdana">
The web site you are accessing has experienced an unexpected error.
<br>
Please contact the website administrator.
</font>
<br><br>
<table border="1" cellpadding="3" bordercolor="#000808" bgcolor="#e7e7e7">
<tr>
<td bgcolor="#000066">
<font style="COLOR: white; FONT: 11pt/13pt verdana" color="white">
The following information is meant for the website developer
for debugging purposes.
</font>
</td>
<tr>
<tr>
<td bgcolor="#4646EE">
<font style="COLOR: white; FONT: 11pt/13pt verdana" color="white">
Error Occurred While Processing Request
</font>
</td>
</tr>
<tr>
<td>
<font style="COLOR: black; FONT: 8pt/11pt verdana">
<table width="500" cellpadding="0" cellspacing="0" border="0">
<tr>
<td id="tableProps2" align="left" valign="middle" width="500">
<h1 id="textSection1" style="COLOR: black; FONT: 13pt/15pt verdana">
ByteArray objects cannot be converted to strings.
</h1>
</td>
</tr>
.... A BUNCH OF OTHER CF DEBUG TEXT ....

Wcf Rest Service Return Number Conversion Error

I am consuming Wcf Rest Service into Angular JS Application . I am trying to display single record based on account number in input filed. But when i click the submit button to display the record then i got following errors in Google Chrome Network Tap.
The server encountered an error processing the request. The exception message is 'Conversion failed when converting the nvarchar value '{Account_Number}15' to data type int.'. See server logs for more details. The exception stack trace is:
And its returns 400 Bad Request on Post Method Operation .
Here is the interface .
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAccountDetails/{Account_Number}")]
string GetAccountDetails(string Account_Number);
Here is the Implementation.
public string GetAccountDetails(string Account_Number)
{
List<object> customers = new List<object>();
string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Number = #Account_Number";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Parameters.AddWithValue("#Account_Number", Account_Number);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new
{
Tittle = sdr["Tittle"],
Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
Account_Holder_DOB = sdr["Account_Holder_DOB"],
Account_Holder_House_No = sdr["Account_Holder_House_No"],
Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],
Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
Account_Number = sdr["Account_Number"]
});
}
}
conn.Close();
}
return (new JavaScriptSerializer().Serialize(customers));
}
}
Here is the Script code.
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
var Account_Number = $scope.Account_Number;
$scope.search = function (Account_Number) {
var promisePostSingle = myService.postbyId(Account_Number);
promisePostSingle.then(function (pl) {
var res = pl.data;
$scope.Account_Number = res.Account_Number;
$scope.Account_Creation_Date = res.Account_Creation_Date;
$scope.Account_Type = res.Account_Type;
$scope.Branch_Sort_Code = res.Branch_Sort_Code;
$scope.Account_Fees = res.Account_Fees;
$scope.Account_Balance = res.Account_Balance;
$scope.Over_Draft_Limit = res.Over_Draft_Limit;
// $scope.IsNewRecord = 0;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
}
}]);
app.service("myService", function ($http) {
this.postbyId = function (Id) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
};
})
Here is the HTML .
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>AccountBalance</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/RegistrationScript/AccountBalance.js"></script>
</head>
<body>
<div data-ng-controller="Web_Client_Controller">
Enter Account_Number: <input type="text" ng-model="Account_Number" />
<input type="button" value="search" ng-click="search(Account_Number)" />
<table id="tblContainer">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>Account Number</th>
<th>Account Creation Date</th>
<th>Account Type</th>
<th>Branch Sort Code</th>
<th>Account Fees</th>
<th>Account Balance</th>
<th>Over Draft Limit</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="user in Users">
<tr>
<td></td>
<td><span>{{user.Account_Number}}</span></td>
<td><span>{{user.Account_Creation_Date}}</span></td>
<td><span>{{user.Account_Type}}</span></td>
<td><span>{{user.Branch_Sort_Code}}</span></td>
<td><span>{{user.Account_Fees}}</span></td>
<td><span>{{user.Account_Balance}}</span></td>
<td><span>{{user.Over_Draft_Limit}}</span></td>
<td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
</td>
</tr>
</table>
</div>
</body>
</html>
Here is the Screen Shot on Debugging mode on Wcf Service .
Here is the result on Google Chrome Console Windows .
You should change it;
$http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
to
$http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails?Account_Number=" + Id);
You are sending the parameter as {Account_Number}15. It should be 15.

Wcf Rest Service End point Not fount

I am consuming Wcf Rest Service into Angular JS Application. I am trying to retrieve a single record based on string parameter Account_Number.when user enter account number into input filed i want to display single record in angular js application but its not displaying the data.I am facing two problems.
I write the url in local host with the method name .I got the result is Method not allowed .
when i clicked the submit button to retrieve that particular account details then i got following error in google chrome .
angular.js:12701 POST http://localhost:52098/HalifaxIISService.svc/GetAccountDetails16 404 (Not Found)
AccountBalance.js:22 failure loading Employee {data: "<?xml version="1.0" encoding="utf-8"?>
when i click this link it shows error in network tab(preview) that the End point not found and the header section .
Request URL:http://localhost:52098/HalifaxIISService.svc/GetAccountDetails16
Request Method:POST
Status Code:404 Not Found
Remote Address:[::1]:52098
Referrer Policy:no-referrer-when-downgrade
Here is my method interface.
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAccountDetails")]
bool GetAccountDetails(string Account_Number);
Here is the implementation .
public bool GetAccountDetails(string Account_Number)
{
List<object> customers = new List<object>();
string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Number = '"+ Account_Number;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Parameters.AddWithValue("#Account_Number", Account_Number);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new
{
Tittle = sdr["Tittle"],
Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
Account_Holder_DOB = sdr["Account_Holder_DOB"],
Account_Holder_House_No = sdr["Account_Holder_House_No"],
Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],
Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
Account_Number = sdr["Account_Number"]
});
}
}
conn.Close();
}
return true;
}
}
here is the script code .
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
var Id = $scope.Account_Number;
$scope.search = function (Id) {
var promisePostSingle = myService.postbyId(Id);
promisePostSingle.then(function (pl) {
var res = pl.data;
$scope.Account_Number = res.Account_Number;
$scope.Account_Creation_Date = res.Account_Creation_Date;
$scope.Account_Type = res.Account_Type;
$scope.Branch_Sort_Code = res.Branch_Sort_Code;
$scope.Account_Fees = res.Account_Fees;
$scope.Account_Balance = res.Account_Balance;
$scope.Over_Draft_Limit = res.Over_Draft_Limit;
// $scope.IsNewRecord = 0;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
}
}]);
app.service("myService", function ($http) {
this.postbyId = function (Id) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails" + Id);
};
})
Here is the HTML CODE .
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="WebClientModule">
<head>
<meta name="viewport" content="width=device-width" />
<title>AccountBalance</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/RegistrationScript/AccountBalance.js"></script>
</head>
<body>
<div data-ng-controller="Web_Client_Controller">
Enter Account_Number: <input type="text" ng-model="Id" />
<input type="button" value="search" ng-click="search(Id)" />
<table id="tblContainer">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>Account Number</th>
<th>Account Creation Date</th>
<th>Account Type</th>
<th>Branch Sort Code</th>
<th>Account Fees</th>
<th>Account Balance</th>
<th>Over Draft Limit</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="user in Users">
<tr>
<td></td>
<td><span>{{user.Account_Number}}</span></td>
<td><span>{{user.Account_Creation_Date}}</span></td>
<td><span>{{user.Account_Type}}</span></td>
<td><span>{{user.Branch_Sort_Code}}</span></td>
<td><span>{{user.Account_Fees}}</span></td>
<td><span>{{user.Account_Balance}}</span></td>
<td><span>{{user.Over_Draft_Limit}}</span></td>
<td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
</td>
</tr>
</table>
</div>
</body>
</html>
<script src="~/RegistrationScript/AccountBalance.js"></script>
Here is the screen shot when i run the application .
Here is the screen shot on Network Tab.
In network Tab preview section

Invalid length for a Base-64 char array or string c# mvc4 web Api

I am using swift 2.0 and Alamofire 3.0. I made a POST request with Alamofire. Parameters in my request contained text and a base64 encoded image. But I am getting a Message as response saying "An error occurred". Asp.net mmvc4 web api is used as backend. The base64 string seems too long. by using an online text editor editpad. in that I found that the character count of my base64 string is 4405562 Characters (including whitespace)
Image to base64 code (swift 2)
var userProfileImage : String = ""
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let capturedImage : UIImage
if let _image = info["UIImagePickerControllerEditedImage"] as? UIImage
{
capturedImage = _image
self.profilePicture.image = _image
let imagetosave = UIImageJPEGRepresentation(_image, 1.0)
let base64encodedImage = imagetosave!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
}
}
else if let _image = info["UIImagePickerControllerOriginalImage"] as? UIImage
{
capturedImage = _image
var __image = UIImageJPEGRepresentation(_image,1.0)
let base64encodedImage = __image!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
userProfileImage = base64encodedImage
self.profilePicture.image = _image
}
else
{
return
}
dismissViewControllerAnimated(true, completion: nil)
}
Alamofire POST Request
let params = ["userid":"\(user)" , "firstname":"\(String(_firstName))" , "middlename":"\(String(_middlename))","lastname":"\(String(_lastname))","password":"\(String(_pass))","email":"\(String(_email))","oldpassword":"\(_oldpass)","base64String":"userProfileImage"]
Alamofire.request(.POST, App.AppHomeURL() + "Update_Profile", parameters : params , encoding : .JSON).responseJSON{
response in
switch response.result {
case .Success(let data) :
let json = JSON(data)
let _data : String = json["Data"].string!
if (_data == "true")
{
let _storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let _profile = _storyBoard.instantiateViewControllerWithIdentifier("ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(_profile, animated: true)
}
Here I get the JSON response as "Message" : "An error has occurred"
Backend code that receives the POST request
public JsonResult Update_Profile([FromBody]UpdateProfileViewModel updateprofileviewmodel)
{
//code goes here
if (updateprofileviewmodel.base64String != "" && updateprofileviewmodel.base64String != null && updateprofileviewmodel.base64String != "null")
{
byte[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
string filenametosave = usermodel._id + "." + System.Drawing.Imaging.ImageFormat.Jpeg;
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/FridgeUserProfilePictures/" + filenametosave);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
image.Save(path);
usermodel.Photo = filenametosave;
}
}
here in the line byte[] imageBytes = Convert.FromBase64String(updateprofileviewmodel.base64String);
an exception occurs saying
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Invalid length for a Base-64 char array or string.
EDIT :
Just put the Base64 string got from Swift in a variable in webApi method
var base64String = "Base64 string got in ios"
this worked and created an image in server.
I tried using POSTMAN a google extension. on using it I found that the actual String is not getting passed. say the string length is 100 on passing only string with length 50 is send and produced the error mentioned in the Question. later I tried this and the response is
response = Optional(<NSHTTPURLResponse: 0x7fe593618b30> { URL: http://app.appurl } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 3420;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 01 Dec 2015 11:59:22 GMT";
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} })
<html>
<head>
<title>Runtime Error</title>
<meta name="viewport" content="width=device-width" />
<style>
body {
font-family: "Verdana";
font-weight: normal;
font-size: .7em;
color: black;
}
p {
font-family: "Verdana";
font-weight: normal;
color: black;
margin-top: -5px
}
b {
font-family: "Verdana";
font-weight: bold;
color: black;
margin-top: -5px
}
H1 {
font-family: "Verdana";
font-weight: normal;
font-size: 18pt;
color: red
}
H2 {
font-family: "Verdana";
font-weight: normal;
font-size: 14pt;
color: maroon
}
pre {
font-family: "Consolas", "Lucida Console", Monospace;
font-size: 11pt;
margin: 0;
padding: 0.5em;
line-height: 14pt
}
.marker {
font-weight: bold;
color: black;
text-decoration: none;
}
.version {
color: gray;
}
.error {
margin-bottom: 10px;
}
.expandable {
text-decoration: underline;
font-weight: bold;
color: navy;
cursor: hand;
}
#media screen and (max-width: 639px) {
pre {
width: 440px;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
}
#media screen and (max-width: 479px) {
pre {
width: 280px;
}
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>
)
May not be the answer for you but I did this,
Compress the Image before sending it to the server and now everything works fine.

Categories