Windows authentication in android - android

I am using WCF webservice in android... i've to authenticate the user with windows authentication
Here's my java code
public void test3()
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI("http://10.0.2.2/MicrosoftDynamicsAXAif60/testgroup/xppservice.svc");
// Send GET request to <service>/GetText
HttpPost httpget = new HttpPost(uri);
StringEntity se = null;
// declare it as XML
se = new StringEntity(this.returnXML(), HTTP.UTF_8);
se.setContentType("text/xml");
httpget.setHeader("Content-Type", "application/xml;charset=UTF-8");
httpget.setEntity(se);
//NTCredentials nt = new NTCredentials("username", "pass", "", "domain");
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, nt);
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
long intCount = responseEntity.getContentLength();
char[] buffer = new char[(int)intCount];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
try
{
reader.read(buffer);
String str = new String(buffer);
Toast.makeText(this, str, 10);
}
catch (IOException e)
{e.printStackTrace();}
stream.close();
}
catch (Exception e) {e.printStackTrace();}
}
Now am getting HTTP Error 401.2 - Unauthorized
Here's xml config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpBindingWithWindowsAuth">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="Windows" >
<extendedProtectionPolicy protectionScenario="TransportSelected" policyEnforcement="Always" />
</transport>
<message clientCredentialType="Windows" />
</security>
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="basicHttpBindingWithWindowsAuth">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
<netTcpBinding>
<binding name="DefaultServiceGroupBinding" closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:10:00" sendTimeout="00:05:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288" maxBufferSize="81920000" maxConnections="10" maxReceivedMessageSize="81920000">
<readerQuotas maxDepth="32000000" maxStringContentLength="81920000" maxArrayLength="163840000" maxBytesPerRead="4096000" maxNameTableCharCount="16384000" />
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<services>
<!--ROUTING SERVICE -->
<!--Define a routing service. The Behavior Configuration field references the name of the Routing Behavior that this service will use-->
<service name="System.ServiceModel.Routing.RoutingService" behaviorConfiguration="routingData">
<!--
Define and configure the endpoint we want the Router to listen on and the Contract we want it to use
Router provided contracts are: ISimplexDatagramRouter, ISimplexSessionRouter, IRequestReplyRouter, and IDuplexSessionRouter.
-->
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="basicHttpBindingWithWindowsAuth"
name="reqReplyEndpoint"
contract="System.ServiceModel.Routing.IRequestReplyRouter" >
<identity>
<servicePrincipalName />
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="routingData">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="False" />
<!--
Define the Routing Behavior. The routingTableName attribute contains the name of the Routing Table that this behavior will use.
<routing filterTableName="AosRoutingTable" />
-->
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="clientEndpointBehavior">
<clientEndpointBehavior />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add
name="clientEndpointBehavior"
type="Microsoft.Dynamics.Ax.Services.Host.ClientEndpointBehaviorExtension, Microsoft.Dynamics.IntegrationFramework.WebService.Process, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</behaviorExtensions>
</extensions>
<!--
Define the client endpoints that we want the Router to communicate with. These are the destinations that the Router will send messages to.
Note that we always define the client endpoint contract as *. The router will mirror the selected contract defied on the endpoint
on which the message was originally recieved.
-->
<client>
<endpoint name="ServiceCustom" address="net.tcp://AOS_SERVICE_HOST/DynamicsAx/Services/testgroup" binding="netTcpBinding" bindingConfiguration="DefaultServiceGroupBinding" contract="*" behaviorConfiguration="clientEndpointBehavior">
<identity><servicePrincipalName /></identity>
</endpoint>
</client>
<routing>
<!--
Define the filters that we want the router to use. In this example we define a MatchAll message filter, which will match all messages it sees.
-->
<filters>
<filter name="MatchServiceCustom" filterType="Custom" customType="Microsoft.Dynamics.Ax.Services.Host.MatchAxServiceFilter, Microsoft.Dynamics.IntegrationFramework.WebService.Process" filterData="http://tempuri.org/ServiceCustom" />
</filters>
<!-- Define the routing table that contains the matchAll filter defined in the filters section. -->
<filterTables>
<filterTable name="AosRoutingTable">
<!-- Map the filter to a client endpoint that was previously defined. Messages that match this filter will be sent to this destination. -->
<add filterName="MatchServiceCustom" endpointName="ServiceCustom" />
</filterTable>
</filterTables>
</routing>
</system.serviceModel>
</configuration>
The xml that i am sending
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<a:Action>http://tempuri.org/ServiceCustom/CreateMyDataObject</a:Action>
<h:CallContext i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:h="http://schemas.microsoft.com/dynamics/2010/01/datacontracts" />
<a:MessageID>urn:uuid:c70fb5f6-1345-469d-84fd-bb24500d329a</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
</s:Header>
<s:Body>
<ServiceCustomCreateMyDataObjectRequest xmlns="http://tempuri.org">
<_s>23</_s>
</ServiceCustomCreateMyDataObjectRequest>
</s:Body>
</s:Envelope>
Solved!
http://mrrask.wordpress.com/2009/08/21/android-authenticating-via-ntlm/

(The OP answered by posting a web link. Converted to a Community Wiki Answer; Question with no answers, but issue solved in the comments (or extended in chat) )
The link was: http://mrrask.wordpress.com/2009/08/21/android-authenticating-via-ntlm/
A summary of which is:
It uses an HttpClient which needs an AuthScemeFactory that will return the AuthScheme descendant NTLMScheme. NTLMScheme requires an implementation of the NTLMEngine interface to operate on. The JCIFS library has functionality for creating type 1 2 & 3 NTLM messages making it a perfect candidate for implementing the NTLMEngine.

Related

ExoPlayer does not use lower bitrate even there is latency in downloading big chunks and this causes freezing and buffering

In our experience ExoPlayer does not use lower bitrate even there is latency in downloading big chunks and this causes freezing and buffering. However the bandwith is 6 Mbit, because of VBR sometimes the size of one 2 second chunk differs from 1.5 MegeByte to 15 MegaByte. In our experience when there is increase in bitrate the player still tries to download next chunk using same bitrate instead of lowering bitrate. What is causing this problem. Is there a way or configuration to fix this?
We are using default values of buffer sizes and track selection durations.
private const val ADAPTIVE_MIN_DURATION_FOR_QUALITY_INCREASE_MS = 10000
private const val ADAPTIVE_MAX_DURATION_FOR_QUALITY_DECREASE_MS = 25000
private const val ADAPTIVE_MIN_DURATION_TO_RETAIN_AFTER_DISCARD_MS = 25000
private const val ADAPTIVE_BANDWIDTH_FRACTION = 0.70f
private const val ADAPTIVE_BUFFERED_FRACTION_TO_LIVE_EDGE_FOR_QUALITY_INCREASE = 0.75f
public static final int DEFAULT_MIN_BUFFER_MS = 50_000;
public static final int DEFAULT_MAX_BUFFER_MS = 50_000;
public static final int DEFAULT_BUFFER_FOR_PLAYBACK_MS = 2500;
public static final int DEFAULT_BUFFER_FOR_PLAYBACK_AFTER_REBUFFER_MS = 5000;
//MPD File
<?xml version="1.0" encoding="UTF-8"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:cenc="urn:mpeg:cenc:2013" xmlns:mspr="urn:microsoft:playready" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd" profiles="urn:mpeg:dash:profile:isoff-live:2011" type="dynamic" minimumUpdatePeriod="PT500S" suggestedPresentationDelay="PT2S" availabilityStartTime="2020-09-09T00:10:16Z" publishTime="2021-01-23T17:28:55Z" minBufferTime="PT4.0S" timeShiftBufferDepth="PT86400.0S">
<ProgramInformation />
<Period id="0" start="PT0.0S">
<AdaptationSet id="0" contentType="video" segmentAlignment="true" bitstreamSwitching="true" maxFrameRate="50/1">
<Representation id="0" mimeType="video/mp4" codecs="avc1.4d4015" bandwidth="800000" width="480" height="270" frameRate="25/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
<Representation id="1" mimeType="video/mp4" codecs="avc1.4d401e" bandwidth="1400000" width="704" height="396" frameRate="25/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
<Representation id="2" mimeType="video/mp4" codecs="avc1.4d401f" bandwidth="2000000" width="960" height="540" frameRate="25/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
<Representation id="3" mimeType="video/mp4" codecs="avc1.4d4020" bandwidth="3150000" width="1280" height="720" frameRate="50/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
<Representation id="4" mimeType="video/mp4" codecs="avc1.4d402a" bandwidth="6000000" width="1920" height="1080" frameRate="50/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
<Representation id="5" mimeType="video/mp4" codecs="avc1.4d400d" bandwidth="400000" width="416" height="234" frameRate="25/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
<Representation id="6" mimeType="video/mp4" codecs="avc1.4d400d" bandwidth="200000" width="416" height="234" frameRate="25/1">
<SegmentTemplate timescale="12800" duration="25600" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4v?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
</AdaptationSet>
<AdaptationSet id="1" contentType="audio" segmentAlignment="true" bitstreamSwitching="true" lang="tur">
<Representation id="8" mimeType="audio/mp4" codecs="mp4a.40.5" bandwidth="128000" audioSamplingRate="48000">
<AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2" />
<SegmentTemplate timescale="48000" duration="96000" initialization="ExtAst1599610204_init_$RepresentationID$.m4i?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" media="ExtAst1599610204_chunk_20200909T001000_$RepresentationID$_$Number$.m4a?hw_dash=1&servicetype=1&rrsip=izmottrrs.tvplus.com.tr:443&zoneoffset=0&devkbps=190-7000&accounttype=1&limitflux=-1&limitdur=-1&tenantId=9001&validdev=5499,5270&vqe=3&mount=1000001&targetdev=5387&pbf=2_2_2_2331729884" startNumber="1" />
</Representation>
</AdaptationSet>
</Period>
<UTCTiming schemeIdUri="urn:mpeg:dash:utc:http-iso:2014" value="https://time.akamai.com/?iso" />
</MPD>
I made a workaround for this. It works mostly.
protected boolean canSelectFormat(Format format, int trackBitrate, float playbackSpeed, long effectiveBitrate) {
if (lastBufferEvaluationMediaChunk != null && trackBitrate == lastBufferEvaluationMediaChunk.trackFormat.bitrate) {
long chunkDurationInSeconds = (lastBufferEvaluationMediaChunk.endTimeUs - lastBufferEvaluationMediaChunk.startTimeUs) / 1_000_000;
double chunkBitrate = lastBufferEvaluationMediaChunk.bytesLoaded() / chunkDurationInSeconds * 8.0;
double bitrateCoefficient = chunkBitrate / trackBitrate;
if (bitrateCoefficient > 1.0f) {
return Math.round(trackBitrate * playbackSpeed) * bitrateCoefficient <= effectiveBitrate;
}
}
return Math.round(trackBitrate * playbackSpeed) <= effectiveBitrate;
}

Cordova Phonegap - Simple Jquery Call

I can not make wcf calls.
I'm using:
wcf
visual studio cordova
Someone help me?
Interface definition
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string GetAddNumbers(int a, int b);
}
Service, simple method that takes two parameters and returns a value
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service : IService
{
public string GetAddNumbers(int a, int b)
{
return (a + b).ToString();
}
}
Service Web Config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation 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="EndpBehavior">
<enableWebScript/>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="EndpBehavior" bindingConfiguration="crossdomain"/>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
<bindings>
<webHttpBinding>
<binding name="crossdomain" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Cordova App - Using JQuery to call wcf
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="Content/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="scripts/jquery-2.1.3.min.js"></script>
<script src="scripts/jquery.mobile-1.4.5.min.js"></script>
<script src="cordova.js"></script>
<script>
//$.support.cors = true;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$("button").click(function () {
var params = { a: $("#first").val(), b: $("#second").val() };
$.ajax({
url: 'http://*******:***/Service.svc/GetAddNumbers',
data: params,
type: "GET",
dataType: "json",
success: function (data, status, xr) {
$("#results").html(data);
},
error: function (xr, msg, e) {
$("#results").html(msg);
alert(msg);
}
});
});
}
</script>
</head>
<body>
<div>
<input id="first" type="text" />
<input id="second" type="text" />
<button>Call Wcf</button>
<div id="results"></div>
</div>
</body>
</html>
The cross-domain-proxy has 3 settings: "remote", "local" and "disabled".
I set "disabled" and work's fine.
thanks to all
I had the same issue with a WCF service on a remote machine. I changed cross-domain-proxy setting from "local" to "remote" and "disabled" and it didn't work even when I added an Access-Control-Allow-Origin header to every request.
I noticed that the proxy port was different than the port in Chrome address bar;
one was 4400, the other one was http://localhost:4443/index.html?enableripple=cordova-3.0.0-NexusGalaxy
When I the changed the proxy port to match the port in the address bar, the call succeeded.
If they don't match the error was: Failed to load resource: net::ERR_CONNECTION_REFUSED File: xhr_proxy, Line: 0, Column: 0

android magento customer login(authentication) using using SOAP API

i facing problem while i try to login(authentication) magento customer. i cant find proper way for login customer using there email and password. so, can u suggest me that how can i make authentication or login customer in magento store using SOAP API.
i tried this code as given bellow
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, "login");
request.addProperty("username", "xyz");
request.addProperty("apiKey", "xyz");
env.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", env);
Object result = env.getResponse();
Log.d("sessionId", result.toString());
// making call to get list of customers
String sessionId = result.toString();
request = new SoapObject(NAMESPACE, "customerCustomerInfo");
request.addProperty("sessionId", sessionId);
request.addProperty("customerId", "2032");
request.addProperty("email", "abc#def.com");
request.addProperty("password", "password");
env.setOutputSoapObject(request);
androidHttpTransport.call(SOAP_ACTION, env);
androidHttpTransport.debug = true;
result = env.getResponse();
Log.d("Customer List", result.toString());
}
but it does not help me so is there any one who's have solution of my question.
Thank you....
There is no direct option for login the customer to magento.The password you retrieve from API is hash_password and you cant check the equality of password. But you can use the method explained below to login into magento.
Create an external php file and access the magento login there
require_once('../magentosite/app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$id = 1;
try{
$result = Mage::getModel('customer/customer')->setWebsiteId($id)->authenticate($email, $password);
}catch( Exception $e ){
$result = false;
}
Send the username and password from android to that php page using JSON,and get the "result".
if the result is "true" the username and password exist in the DB.
Actually you can check/login user using SOAP, you just need to extend it a little bit. At app/code/core/Mage/Customer/Model/Customer/Api.php add new function
public function login($email, $password){
/** #var $session Mage_Customer_Model_Session */
$session = Mage::getSingleton( 'customer/session' );
Mage::app()->getStore()->setWebsiteId(1);
try
{
$session->login( $email, $password );
$customer = $session->getCustomer();
return json_encode(array('status' => 'OK', 'userData' => $this->info($customer->getId())));
}
catch( Exception $e )
{
return json_encode(array('status' => 'error', 'message' => $e->getMessage()));
}
}
At app/code/core/Mage/Customer/etc/api.xml
<config>
<api>
<resources>
<customer translate="title" module="customer">
<methods>
...
<login translate="title" module="customer">
<title>Login customer</title>
<acl>customer/login</acl>
</login>
also at the end
<acl>
<resources>
<customer translate="title" module="customer">
...
<login translate="title" module="customer">
<title>Login</title>
</login>
And here you can test yout login function
<?php
$host = "http://youmagentohost/index.php";
$client = new SoapClient($host."/api/soap/?wsdl"); //soap handle
$apiuser= "apiuser"; //webservice user login
$apikey = "apikey"; //webservice user pass
$action = "customer.login";
try {
$sess_id= $client->login($apiuser, $apikey);
$params = array('email'=>'email#email.com', 'password'=>'password');
print_r($client->call($sess_id, $action, $params));
}
catch (Exception $e) { //while an error has occured
echo "==> Error: ".$e->getMessage();
exit();
}
?>
Its not nice solution but its better than nothing. Don't forget to rewrite all core files ;)
Actually you can check/login user using SOAP
At app/code/core/local/Envato/Masterapi/etc/api.xml
<?xml version="1.0"?>
<config>
<api>
<resources>
<masterapi_loginmodel translate="title" module="masterapi">
<model>masterapi/loginmodel_api</model>
<title>Demo Custommoduleapi API</title>
<acl>masterapi/loginmodel</acl>
<methods>
<!-- <list translate="title" module="masterapi">
<title>List of masterapi</title>
<method>clogin</method>
</list> -->
<customerlogin translate="title" module="masterapi">
<title>List of masterapi</title>
</customerlogin>
</methods>
</masterapi_loginmodel>
</resources>
<resources_alias>
<loginmodel>masterapi_loginmodel</loginmodel>
</resources_alias>
<v2>
<resources_function_prefix>
<loginmodel>masterapiLoginmodel</loginmodel>
</resources_function_prefix>
</v2>
<acl>
<resources>
<masterapi translate="title" module="masterapi">
<title>Loginmodel</title>
<sort_order>5</sort_order>
<loginmodel translate="title" module="masterapi">
<title>loginmodel data</title>
</loginmodel>
</masterapi>
</resources>
</acl>
</api>
</config>
At app/code/core/local/Envato/Masterapi/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Mycustom_Masterapi>
<version>1.0</version>
</Mycustom_Masterapi>
</modules>
<global>
<models>
<masterapi>
<class>Mycustom_Masterapi_Model</class>
</masterapi>
</models>
<helpers>
<masterapi>
<class>Mycustom_Masterapi_Helper</class>
</masterapi>
</helpers>
</global>
</config>
At app/code/core/local/Envato/Masterapi/etc/wsdl.xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns:typens="urn:{{var wsdl.name}}" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"
name="{{var wsdl.name}}" targetNamespace="urn:{{var wsdl.name}}">
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Magento">
<import namespace="http://schemas.xmlsoap.org/soap/encoding/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/" />
<complexType name="fieldInfo">
<sequence>
<element name="entity_id" type="xsd:string"/>
<element name="name" type="xsd:string"/>
</sequence>
</complexType>
<complexType name="fieldInfoArray">
<complexContent>
<restriction base="soapenc:Array">
<attribute ref="soapenc:arrayType" wsdl:arrayType="typens:fieldInfo[]" />
</restriction>
</complexContent>
</complexType>
</schema>
</types>
<message name="masterapiLoginmodelListRequest">
<part name="sessionId" type="xsd:string" />
<part name="user" type="xsd:string" />
<part name="pass" type="xsd:string" />
</message>
<message name="masterapiLoginmodelListResponse">
<part name="customlogin" type="xsd:string" />
</message>
<portType name="{{var wsdl.handler}}PortType">
<operation name="masterapiLoginmodelCustomerlogin">
<documentation>List of masterapi</documentation>
<input message="typens:masterapiLoginmodelListRequest" />
<output message="typens:masterapiLoginmodelListResponse" />
</operation>
</portType>
<binding name="{{var wsdl.handler}}Binding" type="typens:{{var wsdl.handler}}PortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="masterapiLoginmodelCustomerlogin">
<soap:operation soapAction="urn:{{var wsdl.handler}}Action" />
<input>
<soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body namespace="urn:{{var wsdl.name}}" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
<service name="{{var wsdl.name}}Service">
<port name="{{var wsdl.handler}}Port" binding="typens:{{var wsdl.handler}}Binding">
<soap:address location="{{var wsdl.url}}" />
</port>
</service>
</definitions>
At app/code/local/Mycustom/Masterapi/Model/Loginmodel/Api.php
<?php
// app/code/local/Mycustom/Masterapi/Model/Loginmodel/Api.php
class Mycustom_Masterapi_Model_Loginmodel_Api
{
public function customerlogin($user,$pass)
{
/** #var $session Mage_Customer_Model_Session */
$session = Mage::getSingleton( 'customer/session' );
Mage::app()->getStore()->setWebsiteId(1);
try
{
$session->login( $user, $pass);
$customer = $session->getCustomer();
return json_encode(array('status' => 'valid', 'userData' => $customer->getId()));
}
catch( Exception $e )
{
return json_encode(array('status' => 'invalid', 'userData' => $e->getMessage()));
}
}
}
At /app/code/local/Mycustom/Masterapi/Model/Loginmodel/Api/V2.php
<?php
//app/code/local/Envato/Customapimodule/Model/Product/Api/V2.php
class Mycustom_Masterapi_Model_Loginmodel_Api_V2 extends Mycustom_Masterapi_Model_Loginmodel_Api
{
}
IN android side :
call soap request :
properties.put("sessionId", sessionId);
properties.put("user", "qbc#fgfg.com");
properties.put("pass","pass");
request = new SoapObject(NAMESPACE, "masterapiLoginmodelCustomerlogin");
env.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call("", env);
The simplest way to login as a customer is:
fetch email id of all customer
match it with entered email id
if it match, fetch hash password
split the hash password with ":"
encrypt the entered password with md5 method. MD5 method requires to string, one is "salt"(that is string in hash password after ":") and other entered password.
match the output of MD5 and the hash password (value before ":" )
Here is the code:
email = "xyz.#gmail.com";
string_password = "xyz#123";
request = new SoapObject(NAMESPACE, "customerCustomerList");
request.addProperty("sessionId",sessionId );
env.setOutputSoapObject(request);
androidHttpTransport.call("urn:Magento/customerCustomerList", env);
SoapObject response = (SoapObject) env.getResponse();
for(int i=1;i<lengthofResponse;i++)
{
SoapObject CustomerList = (SoapObject)response.getProperty(i);
Object email_id=CustomerList.getProperty(6);
int CustomerList_length = CustomerList.getPropertyCount();
Object password=CustomerList.getProperty((CustomerList_length));
selected_email_ids.add(email_id.toString());
response_password=(password.toString().split(":"));
selected_password.add(response_password[0]);
selected_salt.add(response_password[1]);
//comparing password
if(email.equals(selected_email_ids.get(j)))
{
System.out.println("Email is currect");
hash = md5( response_password[1] + string_password);
if(hash.equals(selected_password.get(j)))
{
System.out.println("Welcome");
}
}
}

Upload Image using WCF service from Android: Cannot process because of content type

I am getting the error below while trying to upload the image.
Cannot process the message because the content type 'multipart/form-data; boundary=AwQm1pbogJ6qQuZlUZjJ6kNOvbehrlyozA-w' was not the expected type 'text/xml; charset=utf-8'.
Android Code :
HttpPost httppost = new HttpPost("http://192.168.1.111/androidservice/MediaUploadService.svc/uploadFile");
File photo = new File(Environment.getExternalStorageDirectory(), "01.jpg");
MultipartEntity t = new MultipartEntity();
t.addPart("t", new FileBody(photo));
httppost.setEntity(t);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
WCF Code :
namespace AndroidService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MediaUploadService" in code, svc and config file together.
public class MediaUploadService : IMediaUploadService
{
public void UploadFile(Stream fileContents)
{
byte[] buffer = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileContents.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
File.WriteAllText(#"D:\\Vechile\log2.txt", totalBytesRead.ToString());
}
}
}
Binding:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior name="PublishMetadataBehavior">
<serviceMetadata httpGetEnabled="true" policyVersion="Policy15"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="WebHttpDtreaming" transferMode="Streamed" >
</binding>
</webHttpBinding>
</bindings>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name=""
helpEnabled="true"
automaticFormatSelectionEnabled="true"
maxReceivedMessageSize="1000000"/>
</webHttpEndpoint>
</standardEndpoints>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
I would appreciate any help.
Try this
httppost.setHeader("content-type", "application/json")

How to serialize xml in android from another xml changing hierarchy

I've got this source xml:
<source>
<category id="1" />
<item1 />
<item2 />
<category id="2"/>
<item1 />
<item2 />
</source>
As you can see all items have the same hierarchy.
And I need to "translate"/serialize it to another XML like this:
<source>
<category id="1">
<item1 />
<item2 />
</category>
<category id="2">
<item1 />
<item2 />
</category>
</source>
Where "items" are children of "category".
I'm using XmlPullParser and XmlSerializer from Android tools but I don't mind to use another if they are compatible with Android environment
Tx
I've found another way using XSLT:
This way we use XML-only specific tools for transform without handling any data with objects.
create a transform.xsl file to handle transformation:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8" />
<xsl:strip-space elements="*" />
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="source">
<source>
<xsl:apply-templates select="category" />
</source>
</xsl:template>
<xsl:template match="category">
<xsl:variable name="place" select="count(preceding-sibling::category)" />
<category>
<xsl:attribute name="id">
<xsl:value-of select="#id" />
</xsl:attribute>
<xsl:apply-templates select="following-sibling::*[not(self::category)]">
<xsl:with-param name="slot" select="$place" />
</xsl:apply-templates>
</category>
</xsl:template>
<xsl:template match="item1">
<xsl:param name="slot" />
<xsl:choose>
<xsl:when test="count(preceding-sibling::category) = $slot + 1">
<xsl:copy-of select="." />
</xsl:when>
<xsl:otherwise />
</xsl:choose>
</xsl:template>
<xsl:template match="item2">
<xsl:param name="slot" />
<xsl:choose>
<xsl:when test="count(preceding-sibling::category) = $slot + 1">
<xsl:copy-of select="." />
</xsl:when>
<xsl:otherwise />
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
And then write the code to handle transformation to a file with desired output data.xml
AssetManager am = getAssets();
xml = am.open("source.xml");
xsl = am.open("transform.xsl");
Source xmlSource = new StreamSource(xml);
Source xsltSource = new StreamSource(xsl);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/data.xml");
StreamResult result = new StreamResult(f);
trans.transform(xmlSource, result);
And its done.
more info here:
http://www.dpawson.co.uk/xsl/sect2/flatfile.html
For an easy xml format this shouldn't be that hard.
A possible way to read the first xml file with a sax parser would be:
public class MySaxHandler extends DefaultHandler {
private List<Category> items = new LinkedList<Category>();
private Category currentCategory;
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (localName.equals("category")) {
currentCategory = new Category(attributes.getValue("id"));
items.add(currentCategory);
}
if (localName.equals("item1") {
currentCategory.setItem1(new Item1(...));
}
if (localName.equals("item2") {
currentCategory.setItem2(new Item2(...));
}
}
}
For each <category> tag you create a new Category object. The following items will be added to the last category object. While reading the contents you create the hierarchy you need later (items are added to the appropriate category).
It should be easy to transform this code to use XmlPullParser instead of sax parser. I just used sax because I am more familiar with it.
When you finished reading the first file you need to write your hierarchy to a new file.
You can do this in a way like this:
StringBuilder b = new StringBuilder();
for (int i = 0; i < categories.size(); i++) {
b.append(categories.get(i).getXml());
}
// write content of b into file
getXml() for each category could look like:
public String getXml() {
StringBuilder b = new StringBuilder();
b.append("<category id=\"" + this.id + "\">");
for (int i = 0; i < items.size(); i++) {
b.append(items.get(i).getXml());
}
b.append("</category>");
return b.toString();
}
Each item creates its own xml in its getXml() method which could be
public String getXml() {
return "<item1 />";
}
in the easiest case.
Please note that building xml by hand is only suitable if you xml structure stays that simple. If the structure is becoming more complicated you should make use of some lightweight xml libraries that work on Android (like xstream).

Categories

Resources