Showing posts with label Tridion 2013. Show all posts
Showing posts with label Tridion 2013. Show all posts

Thursday 10 March 2016

Forms in DD4T MVC and SDL Tridion

How to create forms in DD4T MVC and SDL Tridion using Schema and components

Here we have used only two different schema to create forms.

·         Form field Schema: - Is used to create the controls such as text box, radio button etc.

o   Here i have field type ,field name and label text
o   You can create field Type as category,Keywords to list down all the possible controls





·         Form Builder Schema: - Is used to give the title, Description and here we also linked all our components which was created using Schema Form Field.

o   In This component we will linked all are component created using Form Field  Schema which contains all the different types of fields type Components “First Name, Last Name”.
o   Insert this component as component presentation in your page .





In your DD4T application you can using following sample code lines to render the controls 

@if (FormBuilder.Fields.ContainsKey("title"))
  {
     @FormBuilder.Fields["title"].Value
   }
 @if (FormBuilder.Fields.ContainsKey("description"))
 {
   @FormBuilder.Fields["description"].Value

  }

First Read EmbeddedValues ["sections"] and then LinkedComponentValues

@foreach (var fieldComp in FormBuilder.Fields["fields"].LinkedComponentValues)

{

var fieldType = fieldComp.Fields.ContainsKey("type") ? fieldComp.Fields["type"].Keywords[0].Key : string.Empty;

//In our case it’s a text field

var fieldName = fieldComp.Fields.ContainsKey("name") ? fieldComp.Fields["name"].Value : string.Empty;



var fieldValue = (fieldComp.Fields.ContainsKey("label") && fieldComp.Fields["label"].EmbeddedValues[0].ContainsKey("text")) ? fieldComp.Fields["label"].EmbeddedValues[0][" text"].Values[0] : string.Empty;




<label for=\"{0}\">{1}</label> .FormatArgs(fieldname,fieldname)

//We are using Switch cases to check the field Type and generate control accordingly

switch (fieldType)
{
case "text":
<input type="text" name="@fieldName" />
Break;
case "button":
<button type="button">@fieldValue</button>
}
 }



Happy Coding and keep Sharing !!!!

Tuesday 2 February 2016

Create component in Tridion 2013 using core service and SQL data feed

We have this requirement to consume data from SQL and create Tridion components and automate this process as well like schedule this in task scheduler and run periodically  

Create WCF RestFull service
·         Create Service contract which are exposed by the service to the outside world
In IRestService.cs
[ServiceContract]
    public interface IRestService
    {

        [OperationContract(Name = "CallServiceData")]
        [WebGet(UriTemplate = "/CallServiceData")]
        string CallServiceData();
        
    } 
·         Implement interface member .Here we will call our Business layer SQL stored procedure and serializing the data
  
    public class RestService : IRestService
    {
        public string CallServiceData ()
        {

            try
            {                
             NameSearchGeneration.Process();
             Logger.WriteLog(Logger.LogLevel.ERROR, " Successfully executed CallServiceData ");
                    Output = "True";              
            }
            catch (Exception ex)
            {
                Logger.WriteLog(Logger.LogLevel.ERROR, ex.Message + "Error While Calling CallServiceData ");

            }
            return Output;
        }

    }
·         In Business layer create a class NameSearchGeneration and method process() from here we will import sql data
List<Articles> Articles = Helper.GetImportXmlData();
·         Create model for Article get all the SQL data and bind in article model
    [DataContract]
    [Serializable]
    public class Articles
    {
         
        [XmlElement("title")]
        [DataMember]
        public string Title { getset; }

        [XmlElement("Description")]
        [DataMember]
        public string Description { getset; }
    }
·         Serialize article data using Serialize using System.Xml.Serialization;
foreach (Articles p in ArticlesList)
            {
                    string serializeXml = "";
                    bool bln = Serialize<Articles>(p, ref serializeXml);
                }
          And return the list to List<Articles> Articles

·         Create your core service client ISessionAwareCoreService

coreService = CoreServiceFactory.GetCoreServiceContext(new Uri(ConfigurationManager.AppSettings["CoreServiceURL"].ToString()), new NetworkCredential(ConfigurationManager.AppSettings["UserName"].ToString(), ConfigurationManager.AppSettings["Password"].ToString(), ConfigurationManager.AppSettings["Domain"].ToString()));


       public static class CoreServiceFactory
       {
public static ICoreServiceFrameworkContext GetCoreServiceContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials)
        {
            switch (endpointUri.Scheme.ToLower())
            {
                case CoreServiceConnectionScheme.wsHttp:
                    return GetWsHttpContext(endpointUri, windowsNetworkCredentials);
                case CoreServiceConnectionScheme.netTcp:
                    return GetNetTcpContext(endpointUri, windowsNetworkCredentials);
                default:
                    throw new ArgumentException("The uri connection scheme specified [{0}] is invalid; a valid scheme (ie. http for WsHttp, or net.tcp for NetTcp must be specified).");
            }
        }

        public static ICoreServiceFrameworkContext GetWsHttpContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials)
        {
            return new CoreServiceFrameworkWsHttpContext(endpointUri, windowsNetworkCredentials);
        }

        public static ICoreServiceFrameworkContext GetNetTcpContext(Uri endpointUri, NetworkCredential windowsNetworkCredentials)
        {
            return new CoreServiceFrameworkNetTcpContext(endpointUri, windowsNetworkCredentials);
        }
    }


·         Read schema using coreservic client
SchemaFieldsData schemaFieldData = coreService.Client.ReadSchemaFields(ConfigurationManager.AppSettings["SchemaID"].ToString(), truenew ReadOptions());
·         Using foreach on article list we will create component in Tridion using coreservice client and publish them .
foreach (Articles p in Articles)
                    {
                        string serializeXml = "";
                        bool bln = Helper.Serialize<Articles>(p, ref serializeXml);
                        string xml = serializeXml;

                        string tcmuri = TridionComponent.GenerateComponent(coreService, xml, Helper.SetPublication(ConfigurationManager.AppSettings["FolderLocation"].ToString(), ConfigurationManager.AppSettings["SchemaID"].ToString()), Helper.SchemaType.Component, ConfigurationManager.AppSettings["FolderLocation"].ToString);
                        try
                        {
                            TridionComponent.Publish(tcmuri, ConfigurationManager.AppSettings["PublicationFolderLocation"].ToString(), coreService);
                            Logger.WriteLog(Logger.LogLevel.ERROR, "Component is published successfully");
                        }
·        In GenerateComponent method we will first check if component exist or not
o   If exist we will update and re-publish
o   If not then we will create and publish

·        Here I am searching component based on its title
TridionObjectInfo tridionObjectInfo = Helper.GetTridionObject(coreService, ItemType.Component, folderUri, Title);

if (tridionObjectInfo.TcmUri != null)
                { componentData = (ComponentData)coreService.Client.Update(componentData, new ReadOptions());
}
  else
                {
                    componentData = (ComponentData)coreService.Client.Create(componentData, new ReadOptions());return componentData.Id.ToString();}
·         You need to have following configurable values in your config files
<appSettings>
   
    <!--Tridion User credentials UserName/Password to run the core service-->
    <add  key="UserName" value="" />
    <add  key="Password" value=" " />
    <add  key="Domain" value=" " />
    <add  key="CoreServiceURL" value="http://domain/webservices/CoreService2011.svc/wsHttp" />
    <!-- publication ID is requried-->
    <add  key="PublicationID" value="21" />
    <!-- publication target ID is requried-->
    <add  key="PublicationFolderLocation" value="tcm:0-1-65538" />
    <!-- Connection String is requried-->
    <add key ="ConnectionString" value="Data Source=localhost;Initial Catalog=SQLTridionData;User ID=article;Password=123456;"/>
    <!-- Name of the SP requried-->
    <add  key="SqlProcedureTogetData" value="spName" />   
    <!--Folder TcmId where components gets saved/created-->
    <add  key="FolderLocation" value="tcm:0-111-2" />   
    <!--Schema Id of Article Schema-->
    <add  key="SchemaID" value="tcm:1-1111-8" />
  </appSettings>
This way you can automate the process of creating component and publish from SQL data feed 
Happy Coding and keep Sharing !!!!