How to create custom action for list items using Client Object Model

Requirement – …You need to add custom action to list items using client object model. This user custom action menu item will be added to drop-down menu which is displayed for list items.

using Microsoft.SharePoint.Client;
string urlWebsite = “http://xxxxxxxx:9999/”;
ClientContext clientContext = new ClientContext(urlWebsite);
Web oWebsite = clientContext.Web;
List oList = oWebsite.Lists.GetByTitle(“TestList”);
UserCustomActionCollection collUserCustomAction = oList.UserCustomActions;
UserCustomAction oUserCustomAction = collUserCustomAction.Add();
oUserCustomAction.Location = “EditControlBlock”;
oUserCustomAction.Sequence = 100;
oUserCustomAction.Title = “How to in SharePoint”;
oUserCustomAction.Url = @”http://howtoinsharepoint.blogspot.in/”;
oUserCustomAction.Update();
clientContext.Load(oList,
list => list.UserCustomActions);
clientContext.ExecuteQuery();

 

Location property specifies EditControlBlock,
Sequence specifies an order of placement in relation to other user custom actions,
Url specifies an absolute path to a page that defines the action.

Hope this helps…Happy Coding!!!!

SharePoint CAML Query and Scope attributes

Below article is above understanding scope attribute in CAML query. Suppose you have a document library where documents are stored with some folder structure.

Understanding Scope and its possible values

Default  – No specifying scope attributes, it will only returns all the files under root folder of document library. It won’t go return any files under a folder though applicable based on where condition

Recursive – By specifying scope as Recursive, it will returns files under document library including files under sub folders but not at second  level folder(folder inside folder).

FilesOnly – By specifying scope as FilesOnly, it will returns files only and exclude folders.

RecursiveAll – By specifying scope as RecursiveAll, it will returns all the files under document library including all the folder and sub folder inside folder.

Below are couple of scenarios to understand the same.

Scenario 1 – Retrieve file under specific folder, here folder path is “/folder/subfolder1” is relative path. Please note here example is based on Managed CSOM

List DocumentsList = clientContext.Web.Lists.GetByTitle("SharedDocuments");
CamlQuery camlQuery = new CamlQuery();
camlQuery = new CamlQuery();
camlQuery.ViewXml = @"<View Scope='RecursiveAll'>
                        <Query>
                            <Where>
                                <eq>
                                    <FieldRef Name='FileDirRef'/>
                                    <Value Type='Text'>
                                        /folder1/subfolder1
                                    </Value>
                                </eq>
                            </Where>
                        </Query>
                        <RowLimit Paged='TRUE'> 30 </RowLimit>
                    </View>";
ListItemCollection listItems = DocumentsList.GetItems (camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();

Scenario 2 – Find all zip files within a document library, please note here example is based on JSOM.

var files = [];
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('SharedDocuments');    
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View Scope='RecursiveAll'><Query><Where>" + 
                "" +
                "<Contains><FieldRef Name='FileLeafRef' /><Value Type='Text'>.zip</Value></Contains>" + 
                "</Where></Query></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));        

function onQuerySucceeded(sender, args) {
    var listItemEnumerator = collListItem.getEnumerator();
    while (listItemEnumerator.moveNext()) {
        var oListItem = listItemEnumerator.get_current();  
        files.push(oListItem.get_item("FileLeafRef"));
    }    
    console.log(files);
}

function onQueryFailed(sender, args) {
    //Handle Error
}

Hope this  helps…Happy Coding..!!!

How to Test Your Local Web Sites on Your Mobile Devices Using XAMPP

Undoubtedly, every one of us would agree that Smart phone and new mobile devices have changed the world we live in. Everyone is so much dependent on smart phone that it has become very much necessary for the web site designers to make sure that the website being developed works well on
mobile devices also.
This smart phones and tablets have changed the development methodology or approach towards user experience and design. It won’t be incorrect to say that website designers and developers have yet not found a profound solution for challenge to keep same look and feel across different browsers
(IE, Firefox, chrome, safari etc…). And here comes a new one, support your website on various mobile devices and tablets at different resolutions.

To meet this challenge we have two design methods “Responsive web design” and “Adaptive”. Also it does not matter which one you are using until and unless the user is able to view website easily and effectively. But one of the problem designers/developers face is how to test their web application on actual devices during development. All web developers today should be testing their websites on mobile devices. I don’t mean simulators or emulators; I mean real-life devices that you hold in your hand. Simulator does not give us actual results because it is still running on desktop system.

Wouldn’t it be nice to test your local website on local computer from actual mobile devices? Let us see how we can do that.

Perquisites/Assumptions
1. It is being assumed that XAMP/WMAP or MAMP is installed in you system and you are doing local development using any of the Apache, MySQL and PHP webserver.
2. Your local computer and your mobile device is connected to same network via WIFI or any other connection. (Both desktop and mobile has to be on same network).
Step 1 – Go to XMAPP control panel and make sure you apache and MySQL is working. Also make
sure your website is running.

Step 2
Find your IP address of local computer.
Run CMD as administrator
And on CMD screen type ipconfig and the screen will appear with text

Step 3
Browse you site with URL on your local browser, this is to make sure site is working with IP address also.

Suppose you website is located at localhost/demosite/
It should be brows able with http://192.168.1.4/demosite.
Note – Make sure you setup BASE URL with IP ADDRESS
Step 4
Point your iPad or iPhone web browser to your IP address
You now have your IP address. It may look something like 192.168.1.4. Now, for the moment of truth, open a browser on your device at try browsing to the  directory using the IP address. In my case, I entered http://192.168.1.4/demosite. You’re now testing a website on your
computer from a remote device like an iPad.

That was easy, now you can do test and fix responsive mobile specific bugs easily before moving site to internet.

Hope this will help. Happy coding..!!!

Set Your Magento Up For Middle East (United Arab Emirates, Saudi Arabia).

Recently while working on Magento site for a friend in Middle East, I came across an article on Ecommerce Statistics and Trend in Middle East written in 2013. Below are the some of the take away

90 Million Internet Users in Middle East

15% on online business has online presence

B2C ecommerce sales was estimated $15 billion in 2015(which is current year)

47% of consumers in Middle East own a payment card.

70 to 80% of online physical good transaction are paid through COD and 30% online payment

Most commonly used payment method in Middle East

  1. 47% – Prepaid Card
  2. 30% – Credit Card
  3. 28% – COD
  4. 30% – Bank Transfer
  5. 27% – Paypal

 

So according to above stats, it is equally understandable to say “The Middle East and North Africa is the fastest growing e-commerce market in the world.” With this great potential and while you recognize this massive opportunity, you are fully aware of the challenges of doing business online in the region – logistics, Cash on Delivery, language barriers, segmented market, to name a few.

The article is intended to provide most of the functionality and commonly required features needed to run a Magento store in Middle East. This includes all essential payment and shipping methods configuration as well as small enhancements especially for MENA region.

First the basic information for the store must be configured.

Setting up Countries Options

Go to System – Configuration – General – Countries Option Tab

Default Country – Iran (choose country of your choice)

Allowed Countries – Make sure you select countries which you wanted to allow.

Setting up Local Language

Magento by default supports Arabic and have provided extension also for localization. You can follow below URL for steps and configuring local Arabic language.

http://magentosupport.help/knowledgebase/does-magento-support-arabic/

Adding Regions/States to be displayed on checkout Page.

Adding country or selecting country is not enough because Magento only supports regions/states dropdown for few countries like USA, Canada. For other countries when selected it will remove dropdown and display free text box for region/stage. Next step here is to add states or regions for different countries.

There are 2 options here

Option 1 – Use free Magento Connect Extension to add states/regions for required countries. This is very useful extension for any Magento store outside of USA, Canada. It supports latest Magento and its free so go ahead and install using Magento Connect.

http://www.magentocommerce.com/magento-connect/regions-manager.html

Option 2 – Manually adding to Database

To manually add the information to the tables in your database. Magento will then pick up on this and populate a drop down list. Follow below link which will give idea on SQL.

http://magento.stackexchange.com/questions/34259/how-add-indian-state

Adding City Dropdown.

You can follow a great article from MagePschyo on how to Configure City as dropdown option in checkout page.

http://www.blog.magepsycho.com/tag/city-dropdown/

Currency Configuration

Next this is to setup currency for our Magento store, we need to enable multiple currency and also set default currency. To display currency selector at frontend, couple of steps needs to be followed.

Go to System – Configuration – Current Setup

Base currency as United Arab Emirates Dirham

Default Currency as United Arab Emirates Dirham

Allowed Currencies – Add all the currencies you wanted to allow for your Magento store.

Next step is to setup currency exchange rates

Go to System – Manage Currency – Rates

Click on Import button at top, this will pull the exchange rates from WebServiceEx. Below is the screen how it should look like

Mangento current rate

Next is to check Currency Symbol

Go to System- Manage Currency – Symbols

Manage currency symbol

Setting up Payment methods

What good is your online store if it does not collects payments.  Next step is to setup up payment methods. I have researched and found some of popular payment gateways in MENA regions. Assuming you have opted for any of below merchant accounts it should be easy to setup.

 

Paypal – Magento has built in support for Paypal and you should be able to configure paypal with no time. More about Magento and Paypal can also be found on official Magento site.

http://magento.com/paypal/overview

One Card – If you have opted for One Card payment gateway for your Magento store. Shopgo has provided extension for Magento store for integration. “OneCard Payment Gateway”.

By installing OneCard Payment Extension, you will be able to accept instant and secure payments from your customers; even if they do not have a credit/debit card or bank account. This extension will make use of all OneCard payment features. Additionally, it has a lot of customization settings in the admin area

http://www.magentocommerce.com/magento-connect/onecard-payment-gateway.html

CashU – There are thousands of merchants using CASHU′s payment gateway, If you are one of them and want to setup for your magento store. There is a free Magento extension which can be used for integrating CashU.

http://www.magentocommerce.com/magento-connect/cashu-payment-gateway-1.html

Though it says it compatible till Magento version 1.7 but it can be tried with latest version. Also if you already have merchant account you can connect with CashU support to API integration with Magento, they should be able to help for any technical details.

Faturah –It provides best ecommerce solutions for Saudi Arabia. If you have subscribed for Faturah payment gateway for your Magento store.  Again ShopGo has provided extension for Magento for integrating Faturah payment gateway.

This extension adds (Faturah Payment Gateway) option to your store payment methods. Upon adding this extension to your store, your customers will be able to complete payment through Faturah Gateway. This extension is customizable as you can configure it to meet your needs. Additionally, it allows you to add the requirements settings for your Faturah merchant account.

http://www.magentocommerce.com/magento-connect/faturah-payment-gateway.html

Gate2Play – Another option is Gate2Play, Gate2Play provides you with all available payment options instantly: PayPal, Visa, MasterCard, OneCard, cashU, Cashna, UKash and many others. Setting up Gate2Play payment gateway with Magento store can be done by a Free Extension “Gate2Play Payment Gateway”

This extension adds (Gate2play Payment Gateway) option to your store payment methods. Upon adding this extension to your store, your customers will be able to complete payment through Gate2play Gateway. This extension is customizable as you can configure it to meet your needs. Additionally, it allows you to add the requirements settings for your Gate2play merchant account.

http://www.magentocommerce.com/magento-connect/gate2play-payment-gateway.html

 

Innovate Payments – Innovate Payments specialise in providing online payment solutions to merchants in regions where ecommerce is still emerging and finding a reliable and cost effective payments partner is often difficult. Based in Dubai, our key focus is the development of ecommerce in the Middle East where we believe there will be exponential growth over the coming years.

This extension adds Innovate Payments to the supported payment methods.

http://www.magentocommerce.com/magento-connect/innovate-payments.html

Local Shipping Solutions

COD – Magento have built in support.

Free Shipping – Magento have built in support.

Aramex Shipping – Aramex Shipping and Tracking Extension allows direct communication between the admin portal of Magento Store and Aramex Shipping and Tracking Systems. This extension requires that you have an Aramex account and complete the account information in the Aramex Global Settings.

For installation step and configuration details visit below url

http://www.magentocommerce.com/magento-connect/aramex-shipping-and-tracking-extension.html

Speedex Courier Dubai – Unfortunately there is no extension available and you would have to use expertise of your developer to integrate with your Magento Store.

If you are using any other Payment/Shipping solution, leave in comment. I can research and edit the articles for everyone’s information.

After doing all the above changes you’ll have addressed all the essentials for running a Magento store for Middle East. Hope this article is informative and details as it was intended to. Feel free to provide feedback/comment and suggestions.

Magento – Hide Other Shipping Methods when free shipping is applicable

With your e-commerce store, there might be scenario that where we have to offer Free Shipping over some minimum order to customers. Magento provides this configuration from admin panel but has a little usability issue. Though free shipping is applicable on check out page it also displays other shipping methods(paid) and customer has to select Free Shipping Method as option.  Good news is that we can override this behavior  and hide other shipping method when free shipping is applicable. Below are steps to do.

  1. Go to Below Path and find available.phtml

app/ design/ frontend/ default/ youtheme/ template/ checkout/ onepage/ shipping_method/ available.phtml

  1.  Paste the below code right before <dl> tag
<?php

if ( array_key_exists('freeshipping', $_shippingRateGroups )) {

$_shippingRateGroups = array('freeshipping' => $_shippingRateGroups['freeshipping']);

}

?>

Basically we are overriding $_shippingRateGroups array variable with only one element as free shipping when we found ‘freeshipping’ in array.

Hope this helps!!! Happy Coding!

Magento:Display current category and sub categories within current category on layered navigation

Today we will see how to “Display current category and sub categories within current category on layered navigation” , In Magento Suppose you have below categories structure

  • Category 1
    • Category 1a
    • Category 1b
    • Category 1c
      • Category 1c1
      • Category 1c2
  •  Category 2
    • Category 2a
    • Category 2b

Now when user id on Category 1c2 page, in layered left navigation it will display Shop By category strcutre including Category 1 and Category 2 and everything inside it.

If you want to filter your layered left navigation so that it only display the the structure of from Root parent category(Category 1 in our case) and all sub categories within this parent category. So in our example like if you wan to display left navigation like below(note category 2 is hidden)

  • Category 1a
  • Category 1b
  • Category 1c
    • Category 1c1
    • Category 1c2

Below is the code you can use to filter,

<?php $currentCategory = Mage::registry("current_category"); ?>

<?php $path = $currentCategory->getPath(); $ids = explode('/', $path); ?>

<?php $_helper = Mage::helper('catalog/category') ?>

<?php $_categories = $_helper->getStoreCategories() ?>

<div class="block block-right-nav block-yt-layered-nav">

 <div class="block-layered-nav-inner">

 <div class="block-title">

<strong>

<span><?php echo $this->__('Categories'); ?></span>

</strong>

 </div>

 <div class="block-content clearfix">

<?php if (count($_categories) > 0): ?>

 <ul id="yt_sidenav" class="dropdow-nav">



 <?php foreach($_categories as $_category): ?>

 <?php if (in_array($_category->getId(),$ids)): ?>

<?php echo $this->drawItem($_category) ?>

<?php endif; ?>

 <?php endforeach ?>

 </ul>

<?php endif; ?>

 <script type="text/javascript">

 decorateList('yt_sidenav')

</script>

 </div>

 <?php echo $this->getChildHtml('topLeftLinks'); ?>

 </div>

</div>

Basically what we are doing here, that we are getting current category path(getPath())  and spiting it in to array by ‘/’ and before displaying category inside each loop we are comparing the current category index id is within the array, if so display category else don’t display

Hope this helps…Happy Coding!!!!

Customizing Sort by drop down options in Magento in Listing Page

In Magento, let us say you want to make your sort by dropdown menu options in product listing page to add some custom options( like price low to high and vice versa). This is very basic functionality and it seems Magento’s by default only have 3 options Position, Price and Name and give a arrow image for ascending and descending. Below steps will help you to understand and add your own custom sort by option in magento in listing page. “Customizing sort by drop down options in Magento in Listing Page”

Step 1 – Go to below file

app/design/frontend/base/default/template/catalog/product/list/toolbar.phtml

if you are using some custom theme, this file can also be found at below path.

app/design/frontend/default/your_custom_theme/template/catalog/product/list/toolbar.phtml

 Step 2 – Search for below code

<fieldset class="sort-by">

        <label><?php echo $this->__('Sort by') ?></label>

        <select onchange="setLocation(this.value)">

        <?php foreach($this->getAvailableOrders() as $_key=>$_order): ?>

            <option value="<?php echo $this->getOrderUrl($_key, 'asc') ?>"<?php if($this->isOrderCurrent($_key)): ?> selected="selected"<?php endif; ?>>

                <?php echo $_order ?>

            </option>

        <?php endforeach; ?>

        </select>

        <?php if($this->getCurrentDirection() == 'desc'): ?>

            <a href="<?php echo $this->getOrderUrl(null, 'asc') ?>"><img src="<?php echo $this->getSkinUrl('images/sort_desc_arrow.gif') ?>" alt="<?php echo $this->__('Set Ascending Direction') ?>" class="v-middle" /></a>

        <?php else: ?>

            <a href="<?php echo $this->getOrderUrl(null, 'desc') ?>"><img src="<?php echo $this->getSkinUrl('images/sort_asc_arrow.gif') ?>" alt="<?php echo $this->__('Set Descending Direction') ?>" class="v-middle" /></a>

        <?php endif; ?>

    </fieldset>

Step 3 – Replace or use below code as per your requirement

<fieldset class="sort-by">

        <label><?php echo $this->__('Sort by') ?></label>

        <select onchange="setLocation(this.value)">

  <option value="<?php echo $this->getOrderUrl('entity_id', 'desc') ?>"<?php if($this->isOrderCurrent('entity_id') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>

                New to Old

            </option>

            <option value="<?php echo $this->getOrderUrl('entity_id', 'asc') ?>"<?php if($this->isOrderCurrent('entity_id') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>

                Old to New

            </option>

            <option value="<?php echo $this->getOrderUrl('position', 'asc') ?>"<?php if($this->isOrderCurrent('position') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>

                Postion

            </option>

            <option value="<?php echo $this->getOrderUrl('price', 'asc') ?>"<?php if($this->isOrderCurrent('price') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>

                Price Low to High

            </option>

            <option value="<?php echo $this->getOrderUrl('price', 'desc') ?>"<?php if($this->isOrderCurrent('price') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>

                Price High to Low

            </option>

            <option value="<?php echo $this->getOrderUrl('name', 'asc') ?>"<?php if($this->isOrderCurrent('name') && $this->getCurrentDirection() == 'asc'): ?> selected="selected"<?php endif; ?>>

                By Name A-Z

            </option>

            <option value="<?php echo $this->getOrderUrl('name', 'desc') ?>"<?php if($this->isOrderCurrent('name') && $this->getCurrentDirection() == 'desc'): ?> selected="selected"<?php endif; ?>>

                By Name Z-A

            </option>

          

        </select>

    </fieldset>

Step 4 – Save file, clear cache and check again, you would have got new options added.

Note – If you want you can replace dropdown with custom html structure like to display anchor tag next to each other.

Hope this helps…Happy Coding!!!!

Magento : send file attachments in Emails

Below code can be used to Send file attachement in emails with magento, bascially we will use zend email to do so.

public function sendMail($errorCod = "", $errorMsg = "")
{

    $mail = new Zend_Mail('utf-8');

    $recipients = array(
        Mage::getStoreConfig('trans_email/ident_custom1/name') => Mage::getStoreConfig('trans_email/ident_custom1/email'),
        Mage::getStoreConfig('trans_email/ident_custom2/name') => Mage::getStoreConfig('trans_email/ident_custom2/email'),
    );
    $mailBody   = "<b>Error Code: </b>" . $errorCod . "<br />";
    $mailBody .= "<b>Error Massage: </b>" . $errorMsg . "<br />";
    $mail->setBodyHtml($mailBody)
        ->setSubject('My Subject')
        ->addTo($recipients)
        ->setFrom(Mage::getStoreConfig('trans_email/ident_general/email'), "FromName");

    //file content is attached
    $file       = Mage::getBaseDir('var') . DS . 'log' . DS . 'exception.log';
    $attachment = file_get_contents($file);
    $mail->createAttachment(
        $attachment,
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        'myattach.txt'
    );
    $file       = Mage::getBaseDir('var') . DS . 'log' . DS . 'system.log';
    $attachment = file_get_contents($file);
    $mail->createAttachment(
        $attachment,
        Zend_Mime::TYPE_OCTETSTREAM,
        Zend_Mime::DISPOSITION_ATTACHMENT,
        Zend_Mime::ENCODING_BASE64,
        'myattach2.txt'
    );

    try {
        $mail->send();
    } catch (Exception $e) {
        Mage::logException($e);
    }
}

Hope this helps…Happy Coding!!!

How to use K2Soap Library on android platform to consume Magento SOAP API v2.

While working one of project, we had to do some research on how to consume Magento soap api from android and found a very nice library K2soap, which allows us to connect with Magento soap api. We won’t go in to details about android programming and it is assumed you are an android programming expert. Basically article is about How to use K2Soap Library on android platform to consume Magento SOAP API v2.

If you had not gone through first article of this series, please go through for basic understanding.

Basic steps are as follows

  1. Download K2soap library from this link
  2. Include library jar file to your project
  3. Add library path to Build Path for your project
  4. Set permission.INTERNET in AndroidManifest.xml file.
  5. For purpose of article, add your code to main Activity’s OnCreate Method
  6. Below piece of code will just add required references and set up methods and class which will be executed when android app will run. readingData() method would be our main method under which we would be calling Magento webservice.
package com.example.hello; 
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.MarshalHashtable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
 
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
 
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
 
public class MainActivity extends Activity {
 
private static final String NAMESPACE = "urn:Magento";
private static final String URL = "http://yourdomain.com/index.php/api/v2_soap";
private static final String METHOD_NAME = "shoppingCartProductAdd";
ProgressBar pBar;
 
@Override
public void onCreate(Bundle savedInstanceState) {
 
super.onCreate(savedInstanceState);
new AccessTask().execute();
}
 
class AccessTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
//pBar.setVisibility(View.VISIBLE);
Log.e("onPreExecute",
"----------------onPreExecute-----------------");
}
 
@Override
protected Void doInBackground(Void... params) {
readingData();
return null;
}
 
@Override
protected void onPostExecute(Void unused) {
 
//pBar.setVisibility(View.INVISIBLE);
 
}
 
}
 
}

7. Below would be the stub for readingData method

public void readingData() {try {



} catch (Exception e) {

e.printStackTrace();

}

}

8. Now let us start by creating  SoapSerializationEnvelope

public void readingData() {try {
SoapSerializationEnvelope env = new  SoapSerializationEnvelope(SoapEnvelope.VER11);
 
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
 
} catch (Exception e) {
e.printStackTrace();
}
 
}

9. Now we will create request object and assign it to above envelope. We will first make call tp “login” method from Magento API in order to authenticate and retrieve the sessionId.

10. We then will add request parameters to login method, and it’s can be done withaddProperty and then assign our request object to envelope.
After that, we need to call SOAP method and retrieve result.

public void readingData() {
try {
SoapSerializationEnvelope env = new  SoapSerializationEnvelope(SoapEnvelope.VER11);
 
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
 
SoapObject request = new SoapObject(NAMESPACE, "login");
 
request.addProperty("username", "soapusername");
request.addProperty("apiKey", "soapapikey");
env.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call("", env);
Object result = env.getResponse();
Log.d("sessionId", result.toString());
String sessionId = result.toString();
} catch (Exception e) {
e.printStackTrace();
}
}

11. Please check then retrieved SessionId is logged in LogCat window or not. If you get SessionId then congrats your basic configuration is ready and you are able to connect to magento web service from your android application

12. Now after this, we can make actual service call method to perform all the supported operations. For this article we will call catalogCategoryAssignedProductsmethod which will return us list of products under a particular category id.

public void readingData() {try {
SoapSerializationEnvelope env = new  SoapSerializationEnvelope(SoapEnvelope.VER11);
 
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject request = new SoapObject(NAMESPACE, "login");
 
request.addProperty("username", "soapusername");
request.addProperty("apiKey", "soapapikey");
 
env.setOutputSoapObject(request);
 
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
 
androidHttpTransport.call("", env);
Object result = env.getResponse();
Log.d("sessionId", result.toString());
 
String sessionId = result.toString();
 
SoapObject requestCart = new SoapObject(NAMESPACE, "catalogCategoryAssignedProducts");
requestCart.addProperty("sessionId", sessionId);
requestCart.addProperty("categoryId", 321);
env.setOutputSoapObject(requestCart);
androidHttpTransport.call("", env);
result = env.getResponse();
Log.d("List of Products", result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

13. if call is successful, it will return you list of products in form of array.

Hope this helps!!!! Happy Coding!!!!

Connect IOS and Andriod app to magento store

Well, if you are having Magento ecommerce store and looking for direction to on creating a mobile application for android and IOS which is tightly coupled with your Magento store, you should be lucky to have found this article.  This article will give you background on Magento api and which library can be used from android and IOS to connect to Magento.

Business case – To create online ecommerce mobile app for android and IOS where customer can browse through products, add to cart and checkout to purchase required product and customers profile functionality like register, login, order history, edit user information etc. This mobile app should perform CRUD operation from Magento site or Magento backend database. Basically connect ios and andriod app to magento store.

If you would have done some research you would already know that Magento has provided API to work with Magento’s resources like products, categories, customers, sales and order etc. This API can be used by any external application developer who would like to operate Magento store from outside of native Magento application.

Magento provides SOAP and REST API to connect with Magento backend database. More details on this can be found on below links (Magento Official)

http://www.magentocommerce.com/api/soap/introduction.html

http://www.magentocommerce.com/api/rest/introduction.html

Magento REST api is missing some of features which we have in SOAP api, we would choose SOAP api because it provides almost all the functionality which is required for creating a external application for your magento store.  Please note I have marked “almost” word as bold this is to highlight Magento SOAP api also is missing some feature which would required but more on this later, I am planning to write different article on missing features and how to achieve it with custom api. Read this article on How to enable Magento SOAP API to be consumed by external application

Basic Flow to Call Magento SOAP webservice

Basic steps to call magneto web service from any SOAP client,

To connect to Magento SOAP web services, load the WSDL into your SOAP client from either of these URLs:

http://yourdomain.com/api/v2_soap?wsdl=1

  • Create new SoapClient object by passing WSDL url of your web service(say proxy/client)
  • Authenticate Web service by passing API user key and password with use of login method- this will give us Session Id which will be used in our further calls.
  • Call any Magento API method by passing Session object and other required parameters to call this method.

Library to use to consume Magento SOAP api from Android.

We have used Ksoap2 library consume Magento soap api from android platform.  This client library provides everything to call Magento SOAP service from android.

Library Name – Ksoap2-android library

Library Home URL – https://code.google.com/p/ksoap2-android/

Direct Library Download URL – http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/3.3.0/ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar

A follow up article can be found How to use this library on Andriod platform.

Library to use to consume Magento SOAP api from Ios.

We have used LogN Magento library from github to consume Magento soap api from IOS platform, This client library has worked well for our purpose and provides and easy way to call Magento SOAP service methods from IOS.

Library Name – LogN Magento

Library home url  –   https://github.com/lognllc/LogNMagento

Download URL – https://github.com/lognllc/LogNMagento

Hope this helps!! Happy Coding!!!!