Uploading large files from android to c# WCF Rest Service - c#

i am developing an android application where i can upload video,audio and images from android device to WCF REST Service. it is uploading a video file of 10MB size perfectly, but when i tried to upload a video file of 1GB it is not uploading to server. i want to make an application where i can upload a file size upto 3gb to 4gb.how can i achieve this can anyone please guide me to achieve this scenario.
wcf Service Code :
public string PostImage(Stream stream)
{
MultipartParser parser = new MultipartParser(stream);
if (parser.Success)
{
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
FileStream fileToupload = new FileStream("D:\\FileUpload\\" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
stream.Close();
return "Success !!!";
}
else
{
return "Exception!!!";
}
}
web.config file:
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="Upload.Service1" behaviorConfiguration="default">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Service1" contract="Upload.IService1" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="default">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="RestBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="544096" />
<security mode="None">
</security>
</binding>
</webHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</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"/>
</system.webServer>
</configuration>
My Android Code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://192.169.3.34/Service1.svc/upload");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("fileContents", new FileBody(new File("/mnt/sdcard/hi.mp4")));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
i am getting the status code as 404 when i tried to upload a file of 1GB.
where i need to do changes to make my code to upload a file size of 2gb to 5gb. can anyone please help me out in solving the issue.

Related

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.(For basic Authentication)

I want to enable "Basic" Authentication to my service. Disabled anonymous and windows Auth. And enabled "basicAuthentication" in applicationhost.config, but im not able access the service. Getting below error.
HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.
I am using IIS Express 10. Here is my applicationhost.config
<authentication>
<anonymousAuthentication enabled="false" userName="" />
<basicAuthentication enabled="true" />
<clientCertificateMappingAuthentication enabled="false" />
<digestAuthentication enabled="false" />
<iisClientCertificateMappingAuthentication enabled="false">
</iisClientCertificateMappingAuthentication>
<windowsAuthentication enabled="false">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
</authentication>
And here is my Web.config
<?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.2">
<assemblies>
<add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<!--Enable directory browsing in the Server-->
<system.webServer>
<directoryBrowse enabled="true"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpTransportSecurity">
<security mode="Transport">
<transport clientCredentialType="Basic"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="MyWCFServices.DemoREST" behaviorConfiguration="DemoREST">
<!--Define base https base address-->
<host>
<baseAddresses>
<add baseAddress="https://localhost:44300/HelloWorldService.svc/"/>
</baseAddresses>
</host>
<!--webHttpBinding allows exposing service methods in a RESTful manner-->
<endpoint name="rest" address="" binding="webHttpBinding"
contract="MyWCFServices.IDemoREST" bindingConfiguration="webHttpTransportSecurity"
behaviorConfiguration="DemoREST"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="DemoREST">
<!-- To avoid disclosing metadata information, set the value below to
false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="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"/>
<!--Using custom username and Password-->
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyWCFServices.CustomUserNameValidator, HelloWorldService" />
</serviceCredentials>
<serviceAuthenticationManager authenticationSchemes="Basic"/>
</behavior>
</serviceBehaviors>
<!--Required default endpoint behavior when using webHttpBinding-->
<endpointBehaviors>
<behavior name="DemoREST">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
And Custom validator class:
namespace MyWCFServices
{
class CustomUserNameValidator : UserNamePasswordValidator
{
// This method validates users. It allows in two users, user1 and user2
// This code is for illustration purposes only and
// must not be used in a production environment because it is not secure.
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException("You must provide both the username and password to access this service");
}
if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test"))
{
// This throws an informative fault to the client.
throw new FaultException("Unknown Username or Incorrect Password");
// When you do not want to throw an informative fault to the client,
// throw the following exception.
// throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
}
Please guide me if I am wrong anywhere.

Method Not Found using WCF POST Method

<ServiceContract()>
Public Interface IService1
<OperationContract()>
<WebInvoke(Method:="POST", UriTemplate:="InsertData/{name}/{Surname}")>
Function InsertData(ByVal name As String, ByVal surname As String) As String
End Interface
Implemented it
Public Class Service1
Implements IService1
Public Function InsertData(name As String, surname As String) As String Implements IService1.InsertData
' Save name and surname which does work
End Function
End Class
My web.config
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="WcfParameters.Service1">
<endpoint address="http://localhost:12345/Service1.svc" behaviorConfiguration="webHttpBinding"
binding="webHttpBinding" bindingConfiguration="" name="WebHttpw"
contract="WcfParameters.IService1" />
<!--<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />-->
</service>
</services>
<client>
<endpoint address="http://localhost:12345/Service1.svc" binding="webHttpBinding"
bindingConfiguration="" contract="WcfParameters.IService1" />
</client>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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="webHttpBinding">
<webHttp/>
</behavior>
</endpointBehaviors>
</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"/>
</system.webServer>
</configuration>
I am trying to create a service which will accept a few parameters and save the data to my database.
Using the above configuration if i navigate to http://localhost:12345/Service1.svc/InsertData/name/surname i get the error "Method Not Found"
If i do the same POST method and run it in Fiddler then it saves to the database successfully.
I then used this link http://blogs.msdn.com/b/carlosfigueira/archive/2012/03/26/mixing-add-service-reference-and-wcf-web-http-a-k-a-rest-endpoint-does-not-work.aspx as a guide but i think ive used as much info in order to accomplish what i think i need (i could be wrong).
Should i be doing something different?
Using the above configuration if i navigate to
http://localhost:12345/Service1.svc/InsertData/name/surname i get the
error "Method Not Found"
When you do this trough your browser you are actually doing a GET request, which your method does not support.
When you do it trough Fiddler you issue a POST.
You can do a POST using the WebRequest class or HttpRequest trough your code.

Upload Image from iOS to WCF, error 415(unsupported media)

I'm trying to upload a photo taken by the iphone to the WCF RESTful server, i've looked all over the web for examples and other answers around the issue, but i can't give with the solution.
The app is written in iOS6, and i'm using AFNetworking 2.0 to upload the image. As in the simulator the camera doesn't work, i've been trying with a library photo. I think the problem is in format differences, WCF is requesting for a Stream parameter, and i don't know how AFNetworking is sending the info...
Here is the WCF code:
[WebInvoke(Method = "POST", UriTemplate = "FileUpload")]
public void FileUpload(Stream stream)
{
try
{
byte[] buffer = new byte[10000];
stream.Read(buffer, 0, 10000);
FileStream f = new FileStream("C:\\temp\\sample.jpg", FileMode.OpenOrCreate);
f.Write(buffer, 0, buffer.Length);
f.Close();
stream.Close();
System.Console.WriteLine("Recieved the image on server");
}
catch (Exception e)
{
System.Console.WriteLine("ERROR: " + e.ToString());
}
}
iOS code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"Users/juan/Library/Application Support/iPhone Simulator/6.1/Media/DCIM/100APPLE/IMG_0001.JPG"];
[manager POST:#"http://192.168.2.3:8732/wave/FileUpload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Testing the web service in fiddler, it throws the same error by sending an image, 415 unsupported media.
I let the app.config of the server:
<configuration>
<system.web>
<httpRuntime maxRequestLength="2097151"
useFullyQualifiedRedirectUrl="true"
executionTimeout="14400" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfJsonRestService.waveWS">
<endpoint address="http://localhost:8732/wave"
binding="wsHttpBinding"
bindingConfiguration="wsHttp"
contract="WcfJsonRestService.IWaveWS"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="wsHttp" maxReceivedMessageSize ="50000000" messageEncoding="Mtom" maxBufferPoolSize="50000000" >
<readerQuotas maxArrayLength="50000000" />
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
<system.diagnostics>
Any idea or suggestion how to solve this?
Every idea is welcome
EDIT:
Finally i solved myself, the problem was in the app.config.
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebConfiguration"
maxBufferSize="65536"
maxReceivedMessageSize="2000000000"
transferMode="Streamed">
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WcfJsonRestService.waveWS">
<serviceMetadata httpGetEnabled="true" httpGetUrl="" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfJsonRestService.waveWS">
<endpoint address="http://localhost:8732/wave"
binding="webHttpBinding"
behaviorConfiguration="WebBehavior"
bindingConfiguration="WebConfiguration"
contract="WcfJsonRestService.IWaveWS"/>
</service>
</services>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

List method says "No Data Received" (even though it does receive) in WCF Service Application in Visual Studio 10

I've made a WCF Service Application in Visual Studio 2010. Every method works except this one:
public List<Friend> SendFriendList(int id)
{
FyfDataContext db = new FyfDataContext();
List<Friend> friends = db.Friends.Where(P => P.PK_ID == id).ToList();
return friends;
}
It actually receives the data perfectly, but doesn't show it, when I test it in Google Chrome.
Here's the twist: Before this problem, I made the entire WCF Service App in Visual Studio 2012. And it worked perfectly there - but due to some other problems I had to go back to 2010.
Snippet of my IService.cs:
public interface IService2
{
[OperationContract]
[WebGet(UriTemplate = "/Friendlist?id={id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
List<Friend> SendFriendList(int id);
[OperationContract]
[WebGet(UriTemplate = "/Friendloc?id={id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Friendloc SendFriendLoc(int id);
}
The Friendloc method works - but like all the other methods, it returns an object, and not a list.
I suspect that the problem is something with the web.config - but I just can't find out what.
I do realize that VS12 made a 4.5 Framework, and VS10 made a 4.0.
Here's the Visual Studio 2010 Web.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="FyfConnectionString" connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\Fyf.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="Fyf.Service1"
behaviorConfiguration ="servicebehavior" >
<endpoint name ="SOAPEndPoint"
contract ="Fyf.IService1"
binding ="basicHttpBinding"
address ="soap" />
<endpoint name ="RESTEndPoint"
contract ="Fyf.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
<endpoint contract="IMetadataExchange"
binding="mexHttpBinding"
address="mex" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
And here's the Web.config from Visual Studio 2012:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="FyfdbConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Fyfdb.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="Fyf.Service1"
behaviorConfiguration ="servicebehavior" >
<endpoint name ="SOAPEndPoint"
contract ="Fyf.IService1"
binding ="basicHttpBinding"
address ="soap" />
<endpoint name ="RESTEndPoint"
contract ="Fyf.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
<endpoint contract="IMetadataExchange"
binding="mexHttpBinding"
address="mex" />
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</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"/>
</system.webServer>
</configuration>
I've tried copying some of the elements from VS12 version to my VS10; such as aspNetCompatibilityEnabled to "true" and putting directoryBrowse in etc. But without luck.
I'm sorry if it's something extremely simple that I'm missing. This is my first WCF Service. Any help is much appreciated!
Don't quite know why this works, and the other method doesn't.
Made a DataContract called Userlist with (almost) the same attributes (just tested it with ID).
Definitely not as nice code, but it works. Still curious about the other problem though.
public List<Userlist> Friendlist(int id)
{
int i = 0;
FyfDataContext db = new FyfDataContext();
List<Friend> friends = db.Friends.Where(P => P.PK_ID == id).ToList();
List<Userlist> userlist = new List<Userlist>();
while (i < friends.Count)
{
Userlist u = new Userlist();
u.id = Convert.ToInt32(friends[i].FK_ID);
userlist.Add(u);
i++;
}
return userlist;
}

WCF endpoint not found

I'm following a tutorial in a book to implement push notifications for Windows Phone. This is the markup of the service:
<%# ServiceHost Language="C#" Debug="true" Service="Service.PushService" CodeBehind="PushService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
As you see, a factory is added, although I don't really understand what it's for. When running the service, I get a "endpoint not found" error. When I remove the factory from the markup, the error disappears, but I get an empty page.
Any idea what could cause this error or how to fix it? If you need more code, please tell me.
Thanks
EDIT:
My web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</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"/>
</system.webServer>
</configuration>
You are missing the endpoint configuration in your web.config.
Add this to your web.config:
<system.serviceModel>
<services>
<service name="Service.PushService">
<endpoint address="" binding="basicHttpsBinding"
contract="Service.IPushService" />
</service>
</services>
</system.serviceModel>
For those who absently implement the method in Service.svc that its definition is absent in IService causes the same exception.
This is forgotten
[OperationContract]
string CheckHMAC(string hMac);
But implemented
[WebInvoke(Method = "GET", UriTemplate = "/CheckHMAC/{hMac}")]
public string CheckHMAC(string hMac)
{//}

Categories