Example #1
0
        /**
         * This is taken from https://gist.github.com/afawcett/8dbfc0e1d8c43c982881.
         *
         * This method works on the principle that serializing and deserialising child records is supported
         *
         *   System.assertEquals(1, ((List<Master__c>)
         *    JSON.deserialize(
         *	    JSON.serialize(
         *         [select Id, Name,
         *            (select Id, Name from Children__r) from Master__c]), List<Master__c>.class))
         *               [0].Children__r.size());
         *
         * This method results internally in constructing this JSON, before deserialising it back into SObject's
         *
         *		[
         *		    {
         *		        "attributes": {
         *		            "type": "Master__c",
         *		            "url": "/services/data/v32.0/sobjects/Master__c/a0YG0000005Jn5uMAC"
         *		        },
         *		        "Name": "Fred",
         *		        "Id": "a0YG0000005Jn5uMAC",
         *		        "Children__r": {
         *		            "totalSize": 1,
         *		            "done": true,
         *		            "records": [
         *		                {
         *		                    "attributes": {
         *		                        "type": "Child__c",
         *		                        "url": "/services/data/v32.0/sobjects/Child__c/a0ZG0000006JGPAMA4"
         *		                    },
         *		                    "Name": "Bob",
         *		                    "Id": "a0ZG0000006JGPAMA4",
         *		                    "Master__c": "a0YG0000005Jn5uMAC"
         *		                }
         *		            ]
         *		        }
         *      ]
         */
        public static object makeRelationship(Type parentsType, List <SObject> parents, SObjectField relationshipField, List <List <SObject> > children)
        {
            // Find out more about this relationship...
            string relationshipFieldName = relationshipField.getDescribe().getName();
            DescribeSObjectResult           parentDescribe     = parents.getSObjectType().getDescribe();
            List <Schema.ChildRelationship> childRelationships = parentDescribe.getChildRelationships();
            string relationshipName = null;

            foreach (Schema.ChildRelationship childRelationship in childRelationships)
            {
                if (childRelationship.getField() == relationshipField)
                {
                    relationshipName = childRelationship.getRelationshipName();
                    break;
                }
            }

            // Stream the parsed JSON representation of the parent objects back out, injecting children as it goes
            JSONParser    parentsParser  = JSON.createParser(JSON.serialize(parents));
            JSONParser    childrenParser = JSON.createParser(JSON.serialize(children));
            JSONGenerator combinedOutput = JSON.createGenerator(false);

            streamTokens(parentsParser, combinedOutput, new InjectChildrenEventHandler(childrenParser, relationshipName, children));

            // Derserialise back into SObject list complete with children
            return(JSON.deserialize(combinedOutput.getAsString(), parentsType));
        }
        /// <summary>
        /// Gets fields list of specified object.
        /// </summary>
        /// <param name="objectTypeName">Object type name.</param>
        /// <returns>List of fields.</returns>
        public List <FieldDescriptor> GetFields(string objectTypeName)
        {
            var result = new List <FieldDescriptor>();

            if (this.CheckConnected())
            {
                if (String.IsNullOrEmpty(objectTypeName))
                {
                    throw (new ArgumentNullException("objectTypeName"));
                }

                // Get fields of specified object type

                DescribeSObjectResult describeResult = this._binding.describeSObject(objectTypeName);

                // Get field descriptors

                if (describeResult != null)
                {
                    result = describeResult.fields.Select
                             (
                        q => new FieldDescriptor()
                    {
                        Name = q.name,
                        Type = q.type
                    }
                             )
                             .ToList();
                }
            }

            return(result);
        }
Example #3
0
        private void field(string line)
        {
            //parse the line
            string[] parts = line.Split(' ');
            string   entity = ""; string filter = "";

            if (parts.Length > 1)
            {
                entity = parts[1];
            }
            if (parts.Length > 2)
            {
                filter = parts[2];
            }
            Console.WriteLine("\nListing all fields for " + entity + "\n");
            if (parts.Length < 2)
            {
                Console.WriteLine("Oops...you are missing some things.");
            }
            else
            {
                try
                {
                    DescribeSObjectResult[] dsrArray;
                    client.describeSObjects(
                        header,                  // session header
                        null,                    // package version header
                        null,                    // locale options
                        new string[] { entity }, // passes the entity name into the array for the query
                        out dsrArray
                        );
                    // Since we described only one sObject, we should have only
                    // one element in the DescribeSObjectResult array.
                    DescribeSObjectResult dsr = dsrArray[0];
                    for (int x = 0; x < dsr.fields.Length; x++)
                    {
                        if ((dsr.fields[x].name.Contains(filter)) || (filter == ""))
                        {
                            Field field = dsr.fields[x];
                            Console.Write("\n" + field.name + "  -  " + translateSalesForceType(field.type.ToString()));
                            if (field.relationshipName != null)
                            {
                                Console.Write("  -  *" + field.relationshipName);
                            }
                        }
                    }
                    Console.Write("\n");
                }
                catch (Exception e)
                {
                    Console.WriteLine("An unexpected error has occurred: " + e.Message);
                    Console.WriteLine(e.StackTrace);
                }
            }
        }
        /// <summary>
        /// Gets fields list of specified object.
        /// </summary>
        /// <param name="objectTypeName">Object type name.</param>
        /// <param name="attribute">Field attribute flags.</param>
        /// <returns>List of fields.</returns>
        public List <FieldDescriptor> GetFields(string objectTypeName, FieldAttribute attribute = FieldAttribute.DontCare)
        {
            var result = new List <FieldDescriptor>();

            if (CheckConnected())
            {
                if (String.IsNullOrEmpty(objectTypeName))
                {
                    throw (new ArgumentNullException("objectTypeName"));
                }

                DescribeSObjectResult describeResult = _binding.describeSObject(objectTypeName);

                if (describeResult != null)
                {
                    IEnumerable <Field> filteredFields = describeResult.fields;

                    if (attribute != FieldAttribute.DontCare)
                    {
                        if (attribute.HasFlag(FieldAttribute.Custom))
                        {
                            filteredFields = filteredFields.Where(f => f.custom);
                        }
                        if (attribute.HasFlag(FieldAttribute.Updatable))
                        {
                            filteredFields = filteredFields.Where(f => f.updateable);
                        }
                        if (attribute.HasFlag(FieldAttribute.Filterable))
                        {
                            filteredFields = filteredFields.Where(f => f.filterable);
                        }
                    }

                    result = filteredFields.Select
                             (
                        q => new FieldDescriptor()
                    {
                        Name = q.name, Type = q.type
                    }
                             )
                             .ToList();
                }
            }

            return(result);
        }
Example #5
0
        public List <ADFField> ExtractSimpleMetadata(DescribeSObjectResult sfobject)
        {
            List <ADFField> simpleFields = new List <ADFField>();

            foreach (var field in sfobject.fields)
            {
                // check to go around ADF unsupported fields
                if (field.type != fieldType.address &&
                    field.type != fieldType.location &&
                    SupportedField(field))
                {
                    var newField = new ADFField();
                    var rawField = field.type;
                    newField.name = field.name.ToLowerInvariant();
                    var cleanedField = field.type.ToString().Contains('@') ? field.type.ToString().Replace('@', ' ') : field.type.ToString();
                    var netType      = TypeMapper.SalesforceToDotNet.Where(p => p.Key == cleanedField).FirstOrDefault();
                    Debug.WriteLine(string.Concat(field.name, ", ", rawField, ", ", cleanedField, ", ", netType.Value));
                    if (netType.Key != null)
                    {
                        if (netType.Value == "int")
                        {
                            if (field.digits <= 5)
                            {
                                newField.type = "Int16";
                            }
                            if (field.digits > 5 && field.digits <= 10)
                            {
                                newField.type = "Int32";
                            }
                            if (field.digits > 10 && field.digits <= 19)
                            {
                                newField.type = "Int64";
                            }
                        }
                        else
                        {
                            newField.type = netType.Value;
                        }
                        simpleFields.Add(newField);
                    }
                }
            }
            return(simpleFields);
        }
Example #6
0
        /**
         * The following method illustrates the type of metadata
         * information that can be obtained for each object available
         * to the user. The sample client application executes a
         * describeSObject call on a given object and then echoes
         * the returned metadata information to the console. Object
         * metadata information includes permissions, field types
         * and length and available values for picklist fields
         * and types for referenceTo fields.
         */
        private void describeSObjectsSample()
        {
            Console.Write("\nType the name of the object to " +
                          "describe (try Account): ");
            string objectType = Console.ReadLine();

            try
            {
                // Call describeSObjects() passing in an array with one object type name
                DescribeSObjectResult[] dsrArray =
                    binding.describeSObjects(new string[] { objectType });

                // Since we described only one sObject, we should have only
                // one element in the DescribeSObjectResult array.
                DescribeSObjectResult dsr = dsrArray[0];

                // First, get some object properties
                Console.WriteLine("\n\nObject Name: " + dsr.name);

                if (dsr.custom)
                {
                    Console.WriteLine("Custom Object");
                }
                if (dsr.label != null)
                {
                    Console.WriteLine("Label: " + dsr.label);
                }

                // Get the permissions on the object
                if (dsr.createable)
                {
                    Console.WriteLine("Createable");
                }
                if (dsr.deletable)
                {
                    Console.WriteLine("Deleteable");
                }
                if (dsr.queryable)
                {
                    Console.WriteLine("Queryable");
                }
                if (dsr.replicateable)
                {
                    Console.WriteLine("Replicateable");
                }
                if (dsr.retrieveable)
                {
                    Console.WriteLine("Retrieveable");
                }
                if (dsr.searchable)
                {
                    Console.WriteLine("Searchable");
                }
                if (dsr.undeletable)
                {
                    Console.WriteLine("Undeleteable");
                }
                if (dsr.updateable)
                {
                    Console.WriteLine("Updateable");
                }

                Console.WriteLine("Number of fields: " + dsr.fields.Length);

                // Now, retrieve metadata for each field
                for (int i = 0; i < dsr.fields.Length; i++)
                {
                    // Get the field
                    Field field = dsr.fields[i];

                    // Write some field properties
                    Console.WriteLine("Field name: " + field.name);
                    Console.WriteLine("\tField Label: " + field.label);

                    // This next property indicates that this
                    // field is searched when using
                    // the name search group in SOSL
                    if (field.nameField)
                    {
                        Console.WriteLine("\tThis is a name field.");
                    }

                    if (field.restrictedPicklist)
                    {
                        Console.WriteLine("This is a RESTRICTED picklist field.");
                    }

                    Console.WriteLine("\tType is: " + field.type.ToString());

                    if (field.length > 0)
                    {
                        Console.WriteLine("\tLength: " + field.length);
                    }

                    if (field.scale > 0)
                    {
                        Console.WriteLine("\tScale: " + field.scale);
                    }

                    if (field.precision > 0)
                    {
                        Console.WriteLine("\tPrecision: " + field.precision);
                    }

                    if (field.digits > 0)
                    {
                        Console.WriteLine("\tDigits: " + field.digits);
                    }

                    if (field.custom)
                    {
                        Console.WriteLine("\tThis is a custom field.");
                    }

                    // Write the permissions of this field
                    if (field.nillable)
                    {
                        Console.WriteLine("\tCan be nulled.");
                    }
                    if (field.createable)
                    {
                        Console.WriteLine("\tCreateable");
                    }
                    if (field.filterable)
                    {
                        Console.WriteLine("\tFilterable");
                    }
                    if (field.updateable)
                    {
                        Console.WriteLine("\tUpdateable");
                    }

                    // If this is a picklist field, show the picklist values
                    if (field.type.Equals(fieldType.picklist))
                    {
                        Console.WriteLine("\tPicklist Values");
                        for (int j = 0; j < field.picklistValues.Length; j++)
                        {
                            Console.WriteLine("\t\t" + field.picklistValues[j].value);
                        }
                    }

                    // If this is a foreign key field (reference),
                    // show the values
                    if (field.type.Equals(fieldType.reference))
                    {
                        Console.WriteLine("\tCan reference these objects:");
                        for (int j = 0; j < field.referenceTo.Length; j++)
                        {
                            Console.WriteLine("\t\t" + field.referenceTo[j]);
                        }
                    }
                    Console.WriteLine("");
                }
            }
            catch (SoapException e)
            {
                Console.WriteLine("An exception has occurred: " + e.Message +
                                  "\nStack trace: " + e.StackTrace);
            }
            Console.WriteLine("Press ENTER to continue...");
            Console.ReadLine();
        }
 public void SetUp()
 {
     _testEntity    = new DescribeSObjectResult();
     _privateObject = new PrivateObject(_testEntity);
 }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string        objects    = request.DataStore.GetValue("ObjectTables");
            string        sfUsername = request.DataStore.GetValue("SalesforceUser");
            string        sfPassword = request.DataStore.GetValue("SalesforcePassword");
            string        sfToken    = request.DataStore.GetValue("SalesforceToken");
            string        sfTestUrl  = request.DataStore.GetValue("SalesforceUrl");
            List <string> sfObjects  = objects.Split(',').ToList();

            SoapClient binding = new SoapClient("Soap");

            if (!string.IsNullOrEmpty(sfTestUrl) && sfTestUrl.Contains("test"))
            {
                binding.Endpoint.Address = new System.ServiceModel.EndpointAddress(binding.Endpoint.Address.ToString().Replace("login", "test"));
            }

            LoginResult lr;

            SecurityHelper.SetTls12();

            binding.ClientCredentials.UserName.UserName = sfUsername;
            binding.ClientCredentials.UserName.Password = sfPassword;

            lr =
                binding.login(null, null,
                              sfUsername,
                              string.Concat(sfPassword, sfToken));

            dynamic metadata = new ExpandoObject();

            binding          = new SoapClient("Soap");
            metadata.Objects = new List <DescribeSObjectResult>();
            SessionHeader    sheader = new SessionHeader();
            BasicHttpBinding bind    = new BasicHttpBinding();

            bind = (BasicHttpBinding)binding.Endpoint.Binding;
            bind.MaxReceivedMessageSize              = int.MaxValue;
            bind.MaxBufferPoolSize                   = int.MaxValue;
            bind.MaxBufferSize                       = int.MaxValue;
            bind.CloseTimeout                        = new TimeSpan(0, 0, 5, 0);
            bind.OpenTimeout                         = new TimeSpan(0, 0, 5, 0);
            bind.SendTimeout                         = new TimeSpan(0, 0, 5, 0);
            bind.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            bind.ReaderQuotas.MaxDepth               = int.MaxValue;
            bind.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;
            bind.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            bind.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
            bind.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;

            binding.Endpoint.Binding = bind;
            binding.Endpoint.Address = new EndpointAddress(lr.serverUrl);

            sheader.sessionId = lr.sessionId;

            binding.Endpoint.ListenUri = new Uri(lr.metadataServerUrl);

            foreach (var obj in sfObjects)
            {
                DescribeSObjectResult sobject;

                binding.describeSObject(sheader, null, null, null, obj, out sobject);

                var trimObject = new DescribeSObjectResult();
                trimObject.fields = sobject.fields;
                trimObject.name   = sobject.name;

                metadata.Objects.Add(trimObject);
            }

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetJObjectFromObject(metadata)));
        }
Example #9
0
        private void add(string line)
        {
            string[]  parts     = line.Split(' ');
            string    entity    = "";
            string    eField    = "";
            EntityDef entityDef = null; //working with a specific entitydef

            if (parts.Length > 1)
            {
                entity = parts[1];
            }
            if (entity.Contains("."))
            {
                parts  = entity.Split('.');
                entity = parts[0];
                eField = parts[1];
            }
            if (proceed(entity, eField)) //proceed with a little extra care
            {
                try
                {
                    // Call describeSObjects() passing in an array with one object type name
                    DescribeSObjectResult[] dsrArray;
                    client.describeSObjects(
                        header,                  // session header
                        null,                    // package version header
                        null,                    // locale options
                        new string[] { entity }, // object name array
                        out dsrArray
                        );
                    // one element in the DescribeSObjectResult array.
                    DescribeSObjectResult dsr = dsrArray[0];
                    if (ruleAppDef.Entities.Contains(entity) == false) //make new or use existing entitydef
                    {
                        entityDef = new EntityDef(entity);
                        ruleAppDef.Entities.Add(entityDef);
                    }
                    else
                    {
                        foreach (EntityDef ed in ruleAppDef.Entities)
                        {
                            if (ed.Name == entity)
                            {
                                entityDef = ed;
                            }
                        }
                    }
                    // Now, retrieve metadata for each field
                    for (int i = 0; i < dsr.fields.Length; i++)
                    {
                        if ((eField != "") && (eField != dsr.fields[i].name))
                        {
                            continue;
                        }
                        // Get the field
                        Field    field = dsr.fields[i];
                        FieldDef fd    = new FieldDef();
                        fd.Name        = field.name;
                        fd.DataType    = translateSalesForceType(field.type.ToString());
                        fd.DisplayName = field.label;
                        fd.ValueList   = null;
                        // Add Fields

                        entityDef.Fields.Add(fd);
                        // Add entity fields
                        if (field.relationshipName != null)
                        {
                            //Does this Entity exist in the ruleapp?
                            if (ruleAppDef.Entities.Contains(field.relationshipName))
                            {
                                //confirming the entinty exists in the rule app
                                foreach (EntityDef ed in ruleAppDef.Entities)
                                {
                                    if (ed.Name == field.relationshipName.Trim())
                                    {
                                        FieldDef ef = new FieldDef();
                                        ef.Name               = field.relationshipName;
                                        ef.DataType           = DataType.Entity;
                                        ef.DataTypeEntityName = field.relationshipName;
                                        ef.DisplayName        = field.relationshipName;
                                        //add the field to the current entityDef
                                        entityDef.Fields.Add(ef);
                                    }
                                }
                            }
                        }
                        //Translte types
                        Console.WriteLine("Add Field: " + field.name + "  Type: " +
                                          translateSalesForceType(field.type.ToString()));
                        // TODO generate any helpers for the rule editor
                        // If this is a picklist field, show the picklist values
                        //RuleApplicationDef.

                        /*
                         * if (field.type.Equals(fieldType.picklist))
                         * {
                         *  Console.WriteLine("\tPicklist Values");
                         *  for (int j = 0; j < field.picklistValues.Length; j++)
                         *
                         *      Console.WriteLine("\t\t" + field.picklistValues[j].value);
                         *  } */
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("An exception has occurred: " + e.Message +
                                      "\nStack trace: " + e.StackTrace);
                }
            }
        }