working on it ...

Filters

Explore Public Snippets

Sort by

Found 662 snippets matching: soap

    public by cghersi modified Aug 20, 2013  468554  7  8  2

    Load a SOAP endpoint with Apache CXF using JMS transport provided by Apache ActiveMQ

    This is an example on how to load a SOAP web service in order to be able to invoke its methods via JMS transport
    private JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    public MyInterface loadEndPoint() {
    	//try to load from local, if available:
    	boolean loadOK = false;
    	MyInterface result = null;
    	try {
    		Class<?> c = Class.forName("MyImplClass");
    		Method fact = c.getMethod("get");
    		result = (MyInterface) fact.invoke(null);
    		loadOK = true;
    	} catch (ClassNotFoundException e) {
    		log.info("Cannot find MyImplClass, redirecting to  remote access...", e);		
    	} catch (Exception e) {
    		log.warn("Error searching MyImplClass, , redirecting to remote access. Exception is " + e, e);
    	}
    		
    	//load remote endpoint:
    	if (!loadOK) {
    		//detect transport protocol for web services:
    		String brokerAddr = "127.0.0.1"; //the right broker address
    		String queueName = "MyQueueName";
    		String address = "jms:jndi:dynamicQueues/" + queueName + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=" + brokerAddr;
    
    		log.info("Connecting to " + address);
    		String connString = "tcp://" + brokerAddr + ":61616";
    		ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory("Myusername", "Mypassword", connString);
    
    		SoapBindingConfiguration conf = new SoapBindingConfiguration();
    		//MTOM not supported! .net does not interoperate with cxf mtom impl.
    //		conf.setMtomEnabled(true);
    		conf.setVersion(Soap12.getInstance());
    		factory.setBindingConfig(conf);
    
    		factory.setServiceClass(MyInterface.class);
    		factory.setAddress(address);
    		factory.getFeatures().add(new WSAddressingFeature());
    		factory.getFeatures().add(getJMSConfigFeature(queueName, connFactory, 10000)));
    		Object resObj = factory.create();
    		if ((resObj != null) && (resObj instanceof MyInterface))
    			result = (MyInterface) resObj;
    		}
    
    		return result;
    	}
    }
    
    public static JMSConfigFeature getJMSConfigFeature(String queueName, ActiveMQConnectionFactory connectionFactory, Long receiveTimeout) {
    	JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
    	JMSConfiguration jmsConfig = new JMSConfiguration();
    	jmsConfig.setUseJms11(true);
    	jmsConfig.setTargetDestination(queueName);
    	jmsConfig.setConnectionFactory(connectionFactory);
    	if (receiveTimeout != null)
    		jmsConfig.setReceiveTimeout(receiveTimeout);
    	jmsConfigFeature.setJmsConfig(jmsConfig);
    	return jmsConfigFeature;
    }

    public by lbottaro modified Mar 27, 2014  2941  0  8  7

    Java SOAP server using endpoint

    This code implements a simple SOAP server in java, using the endpoint object to publish the service. Using Endpoint you don't need to run a JBoss instance. The service instance is created invoking the new operator on MyService class, implementing IMyService as public interface, where supported methods are defined.
    package com.mydomain.ws;
    
    import javax.xml.ws.Endpoint;
    
    public class Server {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		IMyService serviceInstance = new MyService();
    		Endpoint.publish("http://localhost/IMyService", serviceInstance);
    	}
    
    }
    

    public by DinhoPutz modified Jan 31, 2019  194  2  3  0

    Consumir dados do RM por PHP via SOAP

    Este código faz uma consulta simples e direta via PHP / SOAP no banco de dados do Totvs RM
    <?php
    	// SOAP client
    	
    	$wsdl ='http://servidor:8051/wsDataServer/MEX?wsdl';
    	
    	$soapParametros = array('login' => 'mestre',
    	'password' => 'totvs',
    	'authentication' => SOAP_AUTHENTICATION_BASIC,
    	'trace' => 1,
    	'exceptions' => true
    	);
    	
    	$paramentros = array('DataServerName' => 'EduAlunoData', 'Filtro'=>'1=1', 'Contexto'=>'?'); 
    	
    	try{
    		$client = new SoapClient($wsdl, $soapParametros);
    		$retorno = $client->ReadView($paramentros);
    		$retorno2 =  $client->__getLastResponse();
    		echo "<pre>" . $retorno2 . "</pre>";
    	}	
    	catch (Exception $e)
    	{
    		echo "<h4>Error!</h4>";
    		echo $e -> getMessage ();
    		echo '<pre>Last response: '. $client->__getLastResponse() . '</pre>';
    	}
    

    public by DinhoPutz modified Feb 1, 2019  36  1  3  0

    Criando / Atualizado dados no RM via SOAP com PHP

    Atualizando dados no Totvs Corpore RM via PHP com SOAP utilizando o método SaveRecord do WebServices
    <?php
    	// chamada para o webservice via Soap
    	$wsdl ='http://SERVIDOR:8051/wsDataServer/MEX?wsdl';
    	
    	// Paramêtros para iniciar a sessão
    	$soapParametros = array('login' => 'mestre',
    	'password' => 'totvs',
    	'authentication' => SOAP_AUTHENTICATION_BASIC,
    	'trace' => 1,
    	'exceptions' => true
    	);	
    	
    	// Criando objeto para fazer chamada
    	$client = new SoapClient($wsdl, $soapParametros);
    	$function = 'SaveRecord';
    	
    	// Argumentos para atualização de dados via SOAP/XML 
    	$arguments = array(array( 'SaveRecord',
    	'DataServerName' => 'RhuPessoaData',
    	'XML' => '<RhuPessoa><PPessoa><CODIGO>12</CODIGO><APELIDO>Aninha =)</APELIDO></PPessoa><VPCompl><CODPESSOA>12</CODPESSOA><IDADE>26</IDADE><PESO>62</PESO></VPCompl></RhuPessoa>',
    	'Contexto' => '?' ));
    	
    	// Converter para XML, não utilizado nesse momento é apenas um teste
    	// $xml = simplexml_load_string($arguments[0]["XML"]) or die("Erro");	
    
    	//var_dump($xml);	
    	
    	// Anotações para lembrar 
    	// $options = array('location' => 'http://350z:8051/wsDataServer.asmx');
    	// (String xmlContexto, Boolean checkRoot) em RM.Con.Conector.ConWSDataServer.
    	// SaveRecord(String DataServerName, String XML, String UserName, String UserPassword, String contexto, String emailUsuarioContexto) ) 
    	
    	// Chamada para salvamento
    	$result = $client->__soapCall($function, $arguments);
    
    	// Retorno da execução 
    	// Se tudo ocorrer como deve, vai retorno a chama primaria o objeto
    	print_r($result);
    ?>

    public by cghersi modified Mar 18, 2014  3116  0  7  1

    Expose an Apache CXF Server in Java

    Apache CXF make VERY simple the exposure of a basic web service. Then, a lot of other feature may be added, like security, REST-ification, re-routing, etc.
    import javax.jws.WebService;
    
    @WebService(targetNamespace = "http://com.snip2code.api")
    public interface IMyAPI {
    
    	public boolean save(String values);
    
    	public String getStringVal();
    }
    
    
    @WebService(serviceName="MyAPIService", portName="apiName")
    public class MyAPI implements IMyAPI {
    	public boolean save(String values) {
    		//do stuff here...
    	}
    
    	public String getStringVal() {
    		return "Hello world";
    	}
    }
    

    public by cghersi modified Mar 18, 2014  3144  1  7  0

    Consume a web service using Apache CXF client library

    Apache CXF may also be used to consume a web service. Obviously, the match of client and server both with CXF make the development very simple, as the same IMyAPI interface may be used as a contract between server and client.
    import java.net.MalformedURLException;
    import java.net.URL;
    
    
    public class CxfClientImpl {
    
        private static final QName SERVICE_NAME = new QName("http://com.snip2code.api", "MyAPIService");
        private static final QName PORT_NAME_DB = new QName("http://com.snip2code.api", "apiName");
    	
    	private IMyAPI portAPI;
    
    	public CxfClientImpl() {
    		//initialize web service utilities:
    		URL wsdlURL = null;
    		String location = "http://192.168.1.5:1572/MyAPIService";
    		try {
    			wsdlURL = new URL(location);
    		} catch (MalformedURLException e) {
    			log.error("Malformed Url:" + location + ", due to:" + e.getMessage());
    			return;
    		}
            Service service = Service.create(SERVICE_NAME);
            service.addPort(SERVICE_NAME, SOAPBinding.SOAP11HTTP_BINDING, wsdlURL.toString());
    
            portAPI = service.getPort(PORT_NAME, IMyAPI.class); 
    	}
    }
    

    public by PLAT.ONE @ PLAT.ONE modified Sep 18, 2015  2829  1  6  0

    How to publish a Web Service (either SOAP and REST) with interceptors that can help you in build custom authentication

    The two classes SecurityInterceptor and RestSecurityInterceptor should be implemented to provide the custom authentication you need. More ways to publish web services with options can be found in overloads of the methods of com.abodata.plat1.wsutils.IWSUtils.
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.cxf.binding.soap.SoapMessage;
    import org.apache.cxf.interceptor.Fault;
    import org.apache.cxf.interceptor.Interceptor;
    import org.apache.cxf.interceptor.StaxInInterceptor;
    import org.apache.cxf.message.Message;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;
    
    import com.abodata.plat1.configuration.IConfigReader;
    import com.abodata.plat1.ws.velocity.IProxyPubEndPoint;
    import com.abodata.plat1.wsutils.EPPublishResult;
    import com.abodata.plat1.wsutils.IWSUtils;
    import com.abodata.plat1.xsd.config.CxfDocument.Cxf.SoapPort;
    import org.apache.cxf.endpoint.Server;
    import org.apache.cxf.jaxws.EndpointImpl;
    
    public class SecuredWSExample implements ISecuredWS {
    	
    	private EndpointImpl endpoint;
    	private Server endpointRest;
    	
    	@Override
    	public List<IProxyPubEndPoint> publishEndpoint() {
    		//retrieve some useful services:
    		IWSUtils wsUtils = YourServiceActivator.getWSUtils();
    		IConfigReader cfg = YourServiceActivator.getConfig();
    		
    		//get configuration parameters:
    		com.abodata.plat1.xsd.config.CxfDocument.Cxf[] cxfConfigs = cfg.getMirroredServiceEndpoints();	
    		if (cxfConfigs == null) 
    			return null;
    		
    		String address = "127.0.0.1";
    		int soapPort = 8160;
    		int restPort = 8161;
    		for (com.abodata.plat1.xsd.config.CxfDocument.Cxf cxf : cxfConfigs) {
    			if((cxf.isSetLan() && !cxf.getLan())) {
    				address = cfg.getValue(cxf.getAddress());
    				soapPort = cxf.getSoapPort().getIntValue();
    				restPort = cxf.getRestPort().getIntValue();
    				break;
    			}
    		}
    		
    		//publish a SOAP endpoint:
    		List<Interceptor<? extends Message>> inInterceptors = new ArrayList<Interceptor<? extends Message>>();
    		inInterceptors.add(new SecurityInterceptor());	
    		EPPublishResult pubRes = wsUtils.publishEndPoint(new SecuredWSExample(), //implementor of the WS
    				address, soapPort, "HelloWorld", //URL of the WS
    				false, 	//let's do security thru the interceptor
    				false,	//reachable also from outside LAN 
    				true, 	//use WS addressing
    				false,	//don't register a policy interceptor
    				inInterceptors,	//interceptors to validate the incoming requests
    				null //no outbound interceptors required 
    				);	
    		endpoint = pubRes.getEndpoint(); //store the endpoint in order to be able to unpublish it
    		
    		//publish a REST endpoint:
    		List<Interceptor<? extends Message>> inRestInterceptors = new ArrayList<Interceptor<? extends Message>>();
    		inRestInterceptors.add(new RestSecurityInterceptor());	
    		EPPublishResult pubResRest = wsUtils.publishRestServer(new SecuredWSExample(), //implementor of the WS
    				address, restPort, "HelloWorldRest", //URL of the WS
    				inRestInterceptors,	//interceptors to validate the incoming requests
    				null, //no outbound interceptors required 
    				null, //no software load balancers in the middle required
    				false //don't use https for now
    				);		
    		endpointRest = pubResRest.getEndPointRest();
    	}
    
    	@Override
    	public List<IProxyPubEndPoint> unpublishEndpoint() {
    		IWSUtils wsUtils = YourServiceActivator.getWSUtils();
    		wsUtils.closeEndPoint(endpoint, "HelloWorld");
    		wsUtils.closeRestServer(endpointRest, "HelloWorldRest");
    	}
    
    	@Override
    	public boolean probe() {
    		return true;
    	}
    
    	@Override
    	public String helloWorld() {
    		return "Hello world";
    	}
    	
    	public static class SecurityInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    		public SecurityInterceptor() {
    			super(Phase.POST_STREAM);
    			addBefore(StaxInInterceptor.class.getName());
    		}
    		
    		@Override
    		public void handleMessage(SoapMessage message) {
    			// TODO: play with message: retrieve parameters, check credentials, etc.
    		}
    	}
    	
    	public static class RestSecurityInterceptor extends AbstractPhaseInterceptor<Message> {
    		public RestSecurityInterceptor() {
    			super(Phase.POST_STREAM);
    			addBefore(StaxInInterceptor.class.getName());
    		}
    
    		@Override
    		public void handleMessage(Message msg) throws Fault {
    			// TODO: play with msg: retrieve parameters, check credentials, etc.
    		}
    	}
    }
    
    
    import javax.jws.WebService;
    import com.abodata.plat1.wsconst.annotations.CxfWSAuthorization;
    import com.abodata.plat1.ws.endpoints.IPublishable;
    import com.abodata.plat1.ws.velocityInfo.PlatUserLevel;
    import com.abodata.plat1.wsconst.annotations.authRoles;
    
    @WebService(targetNamespace = "http://mycompany.com/helloworld")
    public interface ISecuredWS extends IPublishable {
    
    	@CxfWSAuthorization(group=PlatUserLevel.GUEST, roles={authRoles.all})
    	public String helloWorld();
    
    }
                

    public by msdn modified Jan 12, 2015  1794  2  6  0

    DiscoveryAuthority: Method to get authority URL from organization’s SOAP endpoint. http://msdn.microsoft.com/en-us/library/dn531009.aspx#bkmk_oauth_discovery

    Method to get authority URL from organization’s SOAP endpoint. http://msdn.microsoft.com/en-us/library/dn531009.aspx#bkmk_oauth_discovery The Authority Url returned from HttpResponseMessage.
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Microsoft.Xrm.Sdk.Samples;
    using System;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using Windows.Security.Authentication.Web;
    using Windows.UI.Popups;
    
    // TODO Set these string values as approppriate for your app registration and organization.
    // For more information, see the SDK topic "Walkthrough: Register an app with Active Directory".
    public const string ServerUrl = "https://my-domain.crm.dynamics.com/";
    public static string AuthorityUrl;
    static public OrganizationDataWebServiceProxy proxy;
    // TODO Set these string values as approppriate for your app registration and organization.
    // For more information, see the SDK topic "Walkthrough: Register an app with Active Directory".
    public const string ServerUrl = "https://my-domain.crm.dynamics.com/";
    
    static CRMHelper()
            {
                proxy = new OrganizationDataWebServiceProxy();
                proxy.ServiceUrl = ServerUrl;
                proxy.EnableProxyTypes();
            }
    
    /// <summary>
    /// Method to get authority URL from organization’s SOAP endpoint.
    /// http://msdn.microsoft.com/en-us/library/dn531009.aspx#bkmk_oauth_discovery
    /// </summary>
    /// <param name="result">The Authority Url returned from HttpResponseMessage.</param>
    public static async System.Threading.Tasks.Task DiscoveryAuthority()
    {
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer");
            // need to specify soap endpoint with client version,.
            HttpResponseMessage httpResponse = await httpClient.GetAsync(ServerUrl + "/XRMServices/2011/Organization.svc/web?SdkClientVersion=6.1.0.533");
            // For phone, we dont need oauth2/authorization part.
            AuthorityUrl = System.Net.WebUtility.UrlDecode(httpResponse.Headers.GetValues("WWW-Authenticate").FirstOrDefault().Split('=')[1]).Replace("oauth2/authorize", "");
        }
    }

    public by msdn modified Jan 12, 2015  1430  2  7  0

    CreateVersionAwareSenderFaultCode: Creates a SOAP version aware Fault Code

    Creates a SOAP version aware Fault Code The sub faultcode name. The sub faultcode namespace. A Sender fault appropriate for SOAP 1.1 or SOAP 1.2 From the SOAP 1.1 Spec http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383510 The FaultCode "Client" The Client class of errors indicate that the message was inco
    #region Public Methods
    
    /// <summary>
    ///   Creates a SOAP version aware Fault Code
    /// </summary>
    /// <param name = "name">
    ///   The sub faultcode name.
    /// </param>
    /// <param name = "nameSpace">
    ///   The sub faultcode namespace.
    /// </param>
    /// <returns>
    ///   A Sender fault appropriate for SOAP 1.1 or SOAP 1.2
    /// </returns>
    /// <remarks>
    ///   From the SOAP 1.1 Spec http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383510
    ///   The FaultCode "Client"
    ///   The Client class of errors indicate that the message was incorrectly formed or did not contain the appropriate 
    ///   information in order to succeed. For example, the message could lack the proper authentication or payment information. 
    ///   It is generally an indication that the message should not be resent without change. 
    ///   ---
    ///   From the SOAP 1.2 Spec http://www.w3.org/TR/soap12-part1/#tabsoapfaultcodes
    ///   The FaultCode "Sender" 
    ///   The message was incorrectly formed or did not contain the appropriate information in order to succeed. 
    ///   For example, the message could lack the proper authentication or payment information. 
    ///   It is generally an indication that the message is not to be resent without change 
    ///   (see also 5.4 SOAP Fault for a description of the SOAP fault detail sub-element).
    /// </remarks>
    public static FaultCode CreateVersionAwareSenderFaultCode(string name, string nameSpace)
    {
        // Not invoked from WCF
        if (OperationContext.Current == null)
        {
            // Default to SOAP 1.1
            return new FaultCode("Client");
        }
    
        if (OperationContext.Current.IncomingMessageHeaders.MessageVersion.Envelope == EnvelopeVersion.Soap11)
        {
            // BasicHttpBinding uses SOAP 1.1
            return new FaultCode("Client");
        }
    
        if (OperationContext.Current.IncomingMessageHeaders.MessageVersion.Envelope == EnvelopeVersion.Soap12)
        {
            // Other bindings use SOAP 1.2
            return FaultCode.CreateSenderFaultCode(name, nameSpace);
        }
        throw new InvalidOperationException("Unknown SOAP version");
    }

    public by msdn modified Jan 12, 2015  1212  0  6  0

    ObjectToXml: This mehod genearte xml for Soap request from object value

    This mehod genearte xml for Soap request from object value value you can specify name like a:value, d:entity for header xml pass true when you only need xml without header
    using Microsoft.Crm.Sdk.Messages.Samples;
    using Microsoft.Xrm.Sdk.Samples;
    using Microsoft.Xrm.Sdk.Metadata.Samples;
    using Microsoft.Xrm.Sdk.Metadata.Query.Samples;
    using Microsoft.Xrm.Sdk.Query.Samples;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Xml.Linq;
    using System.Globalization;
    
    /// <summary>
    /// This mehod genearte xml for Soap request from object value
    /// </summary>
    /// <param name="item">value</param>
    /// <param name="action">you can specify name like a:value, d:entity for header xml</param>
    /// <param name="elementOnly">pass true when you only need xml without header</param>
    /// <returns></returns>
    static internal string ObjectToXml(object item, string action, bool? elementOnly = null)
    {
        // If there is no value, then return nil with correct node name.
        if (item == null)
            return String.Format("<{0} i:nil='true' />", action);
        // If the value is array type but no item in it, then return empty.
        // When action is b:value, then you need to do extra.
        if (item.GetType().IsArray && ((Array)item).Length == 0 && action != "b:value")
            return String.Format("<{0} />", action);
    
        // type holds item's type
        string type = "";
        string value = "";
        // Firstly, check if it is Enum Type.
        if (item.GetType().GetTypeInfo().IsEnum)
        {
            //if its Enum, then get value by using helper methods or simply obtain it's name
            switch (item.GetType().Name)
            {
                case "DeletedMetadataFilters":
                    type = "j:" + item.GetType().Name;
                    value = GetDeletedMetadataFiltersAsString((DeletedMetadataFilters)item);
                    break;
                case "EntityFilters":
                    type = "h:" + item.GetType().Name;
                    value = GetEntityFiltersAsString((EntityFilters)item);
                    break;
                case "AccessRights":
                    type = "g:" + item.GetType().Name;
                    value = GetAccessRightsAsString((AccessRights)item);
                    break;
                case "RibbonLocationFilters":
                    type = "g:" + item.GetType().Name;
                    value = GetRibbonLocationFiltersAsString((RibbonLocationFilters)item);
                    break;
                case "PrivilegeDepth":
                case "PropagationOwnershipOptions":
                case "RollupType":
                case "SearchDirection":
                case "TargetFieldType":
                case "TimeCode":
                    type = "g:" + item.GetType().Name;
                    break;
                case "AssociatedMenuBehavior":
                case "AssociatedMenuGroup":
                case "AttributeTypeCode":
                case "CascadeType":
                case "DateTimeFormat":
                case "ImeMode":
                case "OptionSetType":
                case "OwnershipTypes":
                case "PrivilegeType":
                case "StringFormat":
                    type = "h:" + item.GetType().Name;
                    break;
                case "ConditionOperator":
                case "EntityRole":
                case "JoinOperator":
                case "LogicalOperator":
                case "OrderType":
                case "RelationshipType":
                case "SecurityTypes":
                    type = "a:" + item.GetType().Name;
                    break;
                case "MetadataConditionOperator":
                    type = "j:" + item.GetType().Name;
                    break;
            }
            // Set value for types which does not have spcecial rule.
            if (value == "")
                value = item.ToString();
        }
        // if its not Enum, then check if it is Array type.
        else if (item.GetType().IsArray)
        {
            //if it is Array type, then check what array it is.
            string arrayType = ""; // Specify Array Type
            bool valueOnlyForDataCollection = false; // True for Class inherited from DataCollection
            //check if it is Enum Array.
            if (item.GetType().GetTypeInfo().IsEnum)
                type = "a:ArrayOf" + ReturnTypeNameForArray(item);
            // if it is not Enum Array then check actual class.
            switch (item.GetType().Name)
            {
                case "ActivityParty[]":
                    //Firstly convert ActivityParty[] to EntityCollection
                    EntityCollection entityCollection = new EntityCollection();
                    foreach (Entity record in (Array)item)
                    {
                        entityCollection.Entities.Add(record);
                    }
                    //Then ToXml()
                    return Util.ObjectToXml(entityCollection, "b:value");
                case "ConditionExpression[]":
                case "Entity[]":
                case "FilterExpression[]":
                case "LinkEntity[]":
                case "Money[]":
                case "OptionSetValue[]":
                case "OrderExpression[]":
                case "QueryExpression[]":
                    type = "a:ArrayOf" + ReturnTypeNameForArray(item);
                    arrayType = "a:" + ReturnTypeNameForArray(item);
                    break;
                case "EntityReference[]":
                case "LocalizedLabel[]":
                    arrayType = "a:" + ReturnTypeNameForArray(item);
                    valueOnlyForDataCollection = true;
                    break;
                case "AppointmentsToIgnore[]":
                case "ConstraintRelation[]":
                case "ObjectiveRelation[]":
                case "RequiredResource[]":
                case "RolePrivilege[]":
                case "TimeCode[]":
                    type = "g:ArrayOf" + ReturnTypeNameForArray(item);
                    arrayType = "g:" + ReturnTypeNameForArray(item);
                    break;
                case "ManyToManyRelationshipMetadata[]":
                case "OneToManyRelationshipMetadata[]":
                case "SecurityPrivilegeMetadata[]":
                    type = "h:ArrayOf" + ReturnTypeNameForArray(item);
                    arrayType = "h:" + ReturnTypeNameForArray(item);
                    break;
                case "OptionMetadata[]":
                    arrayType = "h:" + ReturnTypeNameForArray(item);
                    valueOnlyForDataCollection = true;
                    break;
                case "MetadataConditionExpression[]":
                case "MetadataFilterExpression[]":
                    type = "j:ArrayOf" + ReturnTypeNameForArray(item);
                    arrayType = "j:" + ReturnTypeNameForArray(item);
                    break;
                case "Byte[]":
                    type = "c:base64Binary";
                    value = System.Convert.ToBase64String((byte[])item);
                    break;
                case "Boolean[]":
                    type = "f:ArrayOfboolean";
                    arrayType = "f:boolean";
                    break;
                case "DateTime[]":
                    type = "f:ArrayOfdateTime";
                    arrayType = "f:dateTime";
                    break;
                case "Int32[]":
                    type = "f:ArrayOfint";
                    arrayType = "f:int";
                    break;
                case "Int64[]":
                    type = "f:ArrayOflong";
                    arrayType = "f:long";
                    break;
                default: // string, guid
                    type = "f:ArrayOf" + ReturnTypeNameForArray(item).ToLower();
                    arrayType = "f:" + ReturnTypeNameForArray(item).ToLower();
                    break;
            }
            // If there is no item in it, return no items value
            if (((Array)item).Length == 0)
                return String.Format("<{0} i:type='{1}' />", action, type);
            // If arrayType has value, then you need to get XML value of each item in it.
            if (arrayType != "")
            {
                foreach (var obj in (Array)item)
                {
                    // call ObjectToXml method again, but get it without header.
                    value += ObjectToXml(obj, arrayType, true);
                }
                if (valueOnlyForDataCollection)
                    return value;
            }
        }
        // if it is not Enum nor Array.
        else
        {
            string objType = item.GetType().Name;
            // Check if it's Early Bound Entity Class, which inherit from Entity class
            if (item.GetType().GetTypeInfo().BaseType == typeof(Entity))
            {
                // Then set objType as Entity
                objType = "Entity";
            }
            switch (objType)
            {
                case "AppointmentRequest":
                    type = "g:AppointmentRequest";
                    value = ((AppointmentRequest)item).ToValueXml();
                    break;
                case "AppointmentsToIgnore":
                    type = "g:AppointmentsToIgnore";
                    value = ((AppointmentsToIgnore)item).ToValueXml();
                    break;
                case "AssociatedMenuConfiguration":
                    type = "h:AssociatedMenuConfiguration";
                    value = ((AssociatedMenuConfiguration)item).ToValueXml();
                    break;
                case "AttributeQueryExpression":
                    type = "j:AttributeQueryExpression";
                    value = ((AttributeQueryExpression)item).ToValueXml();
                    break;
                case "AttributeRequiredLevelManagedProperty":
                    type = "a:AttributeRequiredLevelManagedProperty";
                    value = ((AttributeRequiredLevelManagedProperty)item).ToValueXml();
                    break;
                case "AttributeTypeDisplayName":
                    type = "k:AttributeTypeDisplayName";
                    value = ((AttributeTypeDisplayName)item).ToValueXml();
                    break;
                case "BigIntAttributeMetadata":
                    type = "h:BigIntAttributeMetadata";
                    value = ((BigIntAttributeMetadata)item).ToValueXml();
                    break;
                case "BooleanAttributeMetadata":
                    type = "h:BooleanAttributeMetadata";
                    value = ((BooleanAttributeMetadata)item).ToValueXml();
                    break;
                case "BooleanOptionSetMetadata":
                    type = "h:BooleanOptionSetMetadata";
                    value = ((BooleanOptionSetMetadata)item).ToValueXml();
                    break;
                case "BooleanManagedProperty":
                    type = "a:BooleanManagedProperty";
                    value = ((BooleanManagedProperty)item).ToValueXml();
                    break;
                case "CascadeConfiguration":
                    type = "h:CascadeConfiguration";
                    value = ((CascadeConfiguration)item).ToValueXml();
                    break;
                case "ColumnSet":
                    type = "a:ColumnSet";
                    value = ((ColumnSet)item).ToValueXml();
                    break;
                case "ConstraintRelation":
                    type = "g:ConstraintRelation";
                    value = ((ConstraintRelation)item).ToValueXml();
                    break;
                case "ConditionExpression":
                    type = "a:ConditionExpression";
                    value = ((ConditionExpression)item).ToValueXml();
                    break;
                case "DateTimeAttributeMetadata":
                    type = "h:DateTimeAttributeMetadata";
                    value = ((DateTimeAttributeMetadata)item).ToValueXml();
                    break;
                case "DecimalAttributeMetadata":
                    type = "h:DecimalAttributeMetadata";
                    value = ((DecimalAttributeMetadata)item).ToValueXml();
                    break;
                case "DoubleAttributeMetadata":
                    type = "h:DoubleAttributeMetadata";
                    value = ((DoubleAttributeMetadata)item).ToValueXml();
                    break;
                case "Entity":
                    type = "a:Entity";
                    value = ((Entity)item).ToValueXml();
                    break;
                case "EntityCollection":
                    type = "a:EntityCollection";
                    value = ((EntityCollection)item).ToValueXml();
                    break;
                case "EntityNameAttributeMetadata":
                    type = "h:EntityNameAttributeMetadata";
                    value = ((EntityNameAttributeMetadata)item).ToValueXml();
                    break;
                case "EntityMetadata":
                    type = "h:EntityMetadata";
                    value = ((EntityMetadata)item).ToValueXml();
                    break;
                case "EntityQueryExpression":
                    type = "j:EntityQueryExpression";
                    value = ((EntityQueryExpression)item).ToValueXml();
                    break;
                case "EntityReference":
                    type = "a:EntityReference";
                    value = ((EntityReference)item).ToValueXml();
                    break;
                case "EntityReferenceCollection":
                    type = "a:EntityReferenceCollection";
                    // if there is no item in it, then return no items value
                    if (((EntityReferenceCollection)item).Count == 0)
                    {
                        if (action == "b:value")
                            return String.Format("<{0} i:type='{1}' />", action, type);
                        else
                            return String.Format("<{0} />", action);
    
                    }
                    else
                        value = ((EntityReferenceCollection)item).ToValueXml();
                    break;
                case "FetchExpression":
                    type = "a:FetchExpression";
                    value = ((FetchExpression)item).ToValueXml();
                    break;
                case "FilterExpression":
                    type = "a:FilterExpression";
                    value = ((FilterExpression)item).ToValueXml();
                    break;
                case "ImageAttributeMetadata":
                    type = "k:ImageAttributeMetadata";
                    value = ((ImageAttributeMetadata)item).ToValueXml();
                    break;
                case "IntegerAttributeMetadata":
                    type = "h:IntegerAttributeMetadata";
                    value = ((IntegerAttributeMetadata)item).ToValueXml();
                    break;
                case "Label":
                    type = "a:Label";
                    value = ((Label)item).ToValueXml();
                    break;
                case "LabelQueryExpression":
                    type = "j:LabelQueryExpression";
                    value = ((LabelQueryExpression)item).ToValueXml();
                    break;
                case "LinkEntity":
                    type = "a:LinkEntity";
                    value = ((LinkEntity)item).ToValueXml();
                    break;
                case "LocalizedLabel":
                    type = "a:LocalizedLabel";
                    value = ((LocalizedLabel)item).ToValueXml();
                    break;
                case "LocalizedLabelCollection":
                    type = "a:LocalizedLabelCollection";
                    // if there is no item in it, then return no items value
                    if (((LocalizedLabelCollection)item).Count == 0)
                    {
                        if (action == "b:value")
                            return String.Format("<{0} i:type='{1}' />", action, type);
                        else
                            return String.Format("<{0} />", action);
    
                    }
                    else
                        value = ((LocalizedLabelCollection)item).ToValueXml();
                    break;
                case "LookupAttributeMetadata":
                    type = "h:LookupAttributeMetadata";
                    value = ((LookupAttributeMetadata)item).ToValueXml();
                    break;
                case "ManagedPropertyAttributeMetadata":
                    type = "h:ManagedPropertyAttributeMetadata";
                    value = ((ManagedPropertyAttributeMetadata)item).ToValueXml();
                    break;
                case "ManyToManyRelationshipMetadata":
                    type = "h:ManyToManyRelationshipMetadata";
                    value = ((ManyToManyRelationshipMetadata)item).ToValueXml();
                    break;
                case "MetadataConditionExpression":
                    type = "j:MetadataConditionExpression";
                    value = ((MetadataConditionExpression)item).ToValueXml();
                    break;
                case "MetadataFilterExpression":
                    type = "j:MetadataFilterExpression";
                    value = ((MetadataFilterExpression)item).ToValueXml();
                    break;
                case "MetadataPropertiesExpression":
                    type = "j:MetadataPropertiesExpression";
                    value = ((MetadataPropertiesExpression)item).ToValueXml();
                    break;
                case "MemoAttributeMetadata":
                    type = "h:MemoAttributeMetadata";
                    value = ((MemoAttributeMetadata)item).ToValueXml();
                    break;
                case "Money":
                    type = "a:Money";
                    value = ((Money)item).ToValueXml();
                    break;
                case "MoneyAttributeMetadata":
                    type = "h:MoneyAttributeMetadata";
                    value = ((MoneyAttributeMetadata)item).ToValueXml();
                    break;
                case "OneToManyRelationshipMetadata":
                    type = "h:OneToManyRelationshipMetadata";
                    value = ((OneToManyRelationshipMetadata)item).ToValueXml();
                    break;
                case "ObjectiveRelation":
                    type = "g:ObjectiveRelation";
                    value = ((ObjectiveRelation)item).ToValueXml();
                    break;
                case "OptionMetadata":
                    type = "h:OptionMetadata";
                    value = ((OptionMetadata)item).ToValueXml();
                    break;
                case "OptionMetadataCollection":
                    type = "h:OptionMetadataCollection";
                    // if there is no item in it, then return no items value
                    if (((OptionMetadataCollection)item).Count == 0)
                    {
                        if (action == "b:value")
                            return String.Format("<{0} i:type='{1}' />", action, type);
                        else
                            return String.Format("<{0} />", action);
    
                    }
                    else
                        value = ((OptionMetadataCollection)item).ToValueXml();
                    break;
                case "OptionSetMetadata":
                    type = "h:OptionSetMetadata";
                    value = ((OptionSetMetadata)item).ToValueXml();
                    break;
                case "OptionSetValue":
                    type = "a:OptionSetValue";
                    value = ((OptionSetValue)item).ToValueXml();
                    break;
                case "OrderExpression":
                    type = "a:OrderExpression";
                    value = ((OrderExpression)item).ToValueXml();
                    break;
                case "PagingInfo":
                    type = "a:PagingInfo";
                    value = ((PagingInfo)item).ToValueXml();
                    break;
                case "QueryByAttribute":
                    type = "a:QueryByAttribute";
                    value = ((QueryByAttribute)item).ToValueXml();
                    break;
                case "QueryExpression":
                    type = "a:QueryExpression";
                    value = ((QueryExpression)item).ToValueXml();
                    break;
                case "PicklistAttributeMetadata":
                    type = "h:PicklistAttributeMetadata";
                    value = ((PicklistAttributeMetadata)item).ToValueXml();
                    break;
                case "PrincipalAccess":
                    type = "g:PrincipalAccess";
                    value = ((PrincipalAccess)item).ToValueXml();
                    break;
                case "Relationship":
                    type = "a:Relationship";
                    value = ((Relationship)item).ToValueXml();
                    break;
                case "RelationshipQueryExpression":
                    type = "j:RelationshipQueryExpression";
                    value = ((RelationshipQueryExpression)item).ToValueXml();
                    break;
                case "RequiredResource":
                    type = "g:RequiredResource";
                    value = ((RequiredResource)item).ToValueXml();
                    break;
                case "RolePrivilege":
                    type = "g:RolePrivilege";
                    value = ((RolePrivilege)item).ToValueXml();
                    break;
                case "SecurityPrivilegeMetadata":
                    type = "h:SecurityPrivilegeMetadata";
                    value = ((SecurityPrivilegeMetadata)item).ToValueXml();
                    break;
                case "StateAttributeMetadata":
                    type = "h:StateAttributeMetadata";
                    value = ((StateAttributeMetadata)item).ToValueXml();
                    break;
                case "StatusAttributeMetadata":
                    type = "h:StatusAttributeMetadata";
                    value = ((StatusAttributeMetadata)item).ToValueXml();
                    break;
                case "StringAttributeMetadata":
                    type = "h:StringAttributeMetadata";
                    value = ((StringAttributeMetadata)item).ToValueXml();
                    break;
                case "StringFormatName":
                    type = "k:StringFormatName";
                    value = ((StringFormatName)item).ToValueXml();
                    break;
                case "DateTime":
                    type = "c:dateTime";
                    value = ((DateTime)item).ToString("o");
                    break;
                case "Boolean":
                    type = "c:boolean";
                    value = item.ToString().ToLower();
                    break;
                case "Guid":
                    type = "e:guid";
                    break;
                case "Int16":
                    type = "c:int";
                    break;
                case "Int32":
                    type = "c:int";
                    break;
                case "Int64":
                    type = "c:long";
                    break;
                case "Decimal":
                    type = "c:decimal";
                    break;
                case "String":
                    type = "c:string";
                    // value might be xml. so encode it just in case.
                    value = Util.EncodeXML(item.ToString());
                    break;
                default:
                    type = "c:" + item.GetType().Name.ToLower();
                    break;
            }
            // Set value for types which does not have spcecial rule.
            if (value == "")
                value = item.ToString();
        }
                
        // return just value without type information
        if (elementOnly != null && (bool)elementOnly)
        {
            return String.Format("<{0}>{1}</{0}>", action, value);
        }
        // return with type information
        else
        {
            return String.Format("<{0} i:type='{1}'>{2}</{0}>", action, type, value);
        }
    }
    • Public Snippets
    • Channels Snippets