Friday, June 8, 2018

Exm sending email programmatically

Exm is built into Sitecore 9 Experience Platform, You no longer need to install it as a package. 

We can specify target language when sending automated messages through the client API.
To send email programmatically through EXM, follow the below steps.

Step1: Create Exm model with necessary properties as show below.
    public class ExmModel
    {
        public string MessageTemplateId { get; set; }

        public Dictionary<string, object> CustomTokens { get; set; }  

        public string UserName { get; set; }

        public string Email { get; set; }

        public MediaItem Attachment { get; set; }
       
        public string FilePath { get; set; }

        public string FileStream { get; set; }

        public string FileName { get; set; }       

        public string MediaItemID { get; set; }
    }

Step2: Create the instance exm model as below
// Send Mail.
   ExmModel exmModel = new ExmModel();
   exmModel.MessageTemplateId = “email message template id”
   exmModel.MediaItemID =”Sitecore MediaItemID”;

Step3: Add the custom token like (body content for the email) and prepare email content

exmModel.CustomTokens = new Dictionary<string, object>();
exmModel.CustomTokens.Add(token, “heading”);
exmModel.CustomTokens.Add(token, “Address”);
exmModel.CustomTokens.Add(token name, “any content you wish to add”);

Step4: Create the contact and Add recipient
       Create the contact, List Manager in sitecore.
       Please refer the sitecore exm blog post to create the List manager and contacts      

Step5: Create the contract and Add recipient

MessageItem message = Sitecore.Modules.EmailCampaign.Factory.GetMessage(exmModel.MessageTemplateId);
List<RecipientId> recipients = new List<RecipientId>();

Var contact = contactRepository.LoadContactReadOnly(userName);
Var lockAttempt = contactManager.TryLoadContact(contact.ContactId);

GetOrCreateContact(userName, lockAttempt, contactRepository, contactManager, name);
            }­­
                            recipients.Add(RecipientRepository.GetDefaultInstance().ResolveRecipientId("xdb:" + contact.ContactId));




Step6: Replace Custom Tokens.            

Step7: Attachment: Sitecore media item.
a.     Store the attachment as media item in the sitecore
b.     Retrieve the media item from sitecore
                       
exmModel.Attachment = "get the media item from sitecore"
message.Attachments.Add(exmModel.Attachment);
message.FromAddress = exmModel.Email;


Step8: Sending email
      if (recipients != null && recipients.Any())
        {
                           
          foreach (var recipient in recipients)
            {
               New AsyncSendingManager(message).SendStandardMessage(recipient);

             }
          }
2. Piece of code to store uploaded file as a media item in sitecore

     private static MediaItem AddingFile(ExmModel exmModel)
        {

            byte[] fileStreamDecoded = System.Convert.FromBase64String(exmModel.FileStream);


            using (MemoryStream ms = new MemoryStream(fileStreamDecoded))
            {
                StreamWriter writer = new StreamWriter(ms);
                writer.Write(fileStreamDecoded);

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                // Create the options
                Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
                options.FileBased = false;
                options.IncludeExtensionInItemName = false;

                options.Versioned = false;

                options.Database = ContextDatabase;
                options.Destination =”exm file path”

                Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
                using (new Sitecore.SecurityModel.SecurityDisabler())
                {

                    // Item mediaItem = Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream()
                    Item mediaItem = creator.CreateFromStream(ms, exmModel.FilePath, options);
                    mediaItem.Editing.BeginEdit();
                    mediaItem.Name = Path.GetFileNameWithoutExtension(exmModel.FileName);
                    mediaItem.Editing.EndEdit();
                    return mediaItem;
                }
            }


        }
3. Reference





Monday, November 20, 2017

Cannot use DataAdapterProvider as xDB is disabled

Ans --> Even i ran into the similar issue,  Fixed this issue by running MongoDB Server.
Please make sure your MongoDB server is up and running.

Thursday, February 9, 2017

Sitecore Interview Questions for 4+ year exp guys

1. What are sticky and non-sticky sessions?
Sticky session:
     What: A method used with Application Load Balancing, to achieve server-affinity.

     Why: If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

* All your requests will be directed to the same physical web server.            
* Only single session object will be there

Non Sticky session:
* In case of a non-sticky load balancer may choose any webserver to serve your requests.
* Session object for each server node

2. What is Areas in Sitecore Mvc?
What: MVC areas are choice for organizing and separating assets belonging to each tenant, or for breaking up a large single tenant project into multiple modules.
MVC Areas actually do far more than just organize your files into separate directories.  Runtime resolution of assets based on directory convention is also great, and support for this by Visual Studio IntelliSense is even better.

Why: Sitecore offers support for multiple tenants from a single running instance, but it does not provide process or file system isolation for assets developed for each tenant website

Where:  sitecore will by default registers all the areas in the initialize pipeline. You can register area in sitecore.mvc.config file
<mvc>
<areas>
<area type=”namespace.classname, assembly name”>
</area>

<excludeareas>
     <area type=”namespace.classname, assembly name” />
</excludeareas>
</areas>
          </mvc>
To determine the area for each rendering and layout view, Sitecore uses the ResolveArea processor early in the mvc.renderRendering pipeline

When invoking a rendering in code, for example: @Html.Sitecore().ViewRendering("Index", new { area = "MyArea" })

4. What is Helix and Habitat?
      Helix is a set of overall design principles and conventions for Sitecore development.

      Habitat is a real Sitecore project implemented on the Sitecore Experience Platform using   Helix. It is an example that allows developers to see how Helix is applied and lets developers experience a project based on these principles.
http://helix.sitecore.net/introduction/what-is-helix.html

5. How to Replace space and underscore with a dash (-) in the URL Sitecore?
    Go to sitecore.config file and add the below settings 
   <encodeNameReplacements>
    <replace mode="on" find=" " replaceWith="-" /> 
<replace mode="on" find="_" replaceWith="-"/>
 </encodeNameReplacements>

6. How to delete history of source code check-in? For example suppose say you have wrongly committed some configuration changes, how do you delete its check-in history? so that other person should not be able to see it in the history.

7. What is path Analyzer?

8. Why Federated Experience Manager?
    Click on this Link and go page number 259 to read.

8. How do you set up mongoDb? Does Sitecore 9 update1 support Mongodb for xDB.
    Sitecore 9 update1 doesn't support MongoDb or oracle db for xDB( it prefers SQL db), Sitecore has again started it supports to Mongodb in sitecore 9 update2 release.




.Net Interview Questions
1. Difference between Html.BeginForm() and Ajax.BeginForm()?

Ajax.BeginForm() creates a form that submits its values using an asynchronous ajax request. This allows a portion of the page to be update without requiring that the entire page be refreshed. Html.BeginForm() will use simple posting on page, it means your page will be refreshed when you post your form

Saturday, August 20, 2016

Sitecore Interview Ques for 1-3+ Years experience guys


I have listed out the questions which were asked when I was changing my job.

1.      What is TDS ? Can we have two TDS projects in solutions? If yes how do you configure?  

2.     Solr-Schema vs Schemaless file? (Use of Schema.xml file in sitecore)

2.      How do you configure solr and what is the advantage of solr over lucene search?

4.       Sitecore Item alias (Alternate URL for an item)
5.       How to speed up Sitecore application startup?
6.      What are Differnt types of Cache settings in Sitecore?
7.      Media Items are getting created in multiple languages Sitecore?
   http://sitecoreblog.patelyogesh.in/2013/08/sitecore-media-item-created-in-multiple-languages.html

a
What is  versioned and un-versioned template in sitecore?   
Media items uploaded using the Upload media dialog box are created as Versioned and in the default language only, regardless of the Media.UploadAsVersionableByDefault setting value.
Ø   If Media.UploadAsVersionableByDefault  setting in your sitecore.config set to false, then uploaded media item will be created in all those languages which exist under /sitecore/system/languages. This media item will use unversioned template /sitecore/templates/System/Media/Unversioned/File template, so the Blob(Media) and its common details would be shared across all language versions.

Ø  This option is really helpful when you want to use common media files across multiple languages content pages as the media is shared across all languages.
Ø  If this setting is true, then each media item will be generated in default language only. This media item will use versioned template /sitecore/templates/System/Media/Versioned/File template, so the Blob(Media) and its all details would be distinct across languages.
Ø  This option is really helpful when you want to use different media files for different language content pages.

8.   Upload Sitecore media items in selected languages
9.   Sitecore workflow to auto publish media items





10.   What is Partial language fall back?
        References :

        
·         The VisitorIdentification Web control helps the Sitecore analytics engine identify robots. TheVisitorIdentification Web control generates an HTML <link> element that references an empty CSS resource. The Sitecore analytics engine uses this request to help differentiate robots from actual users.

·         To assist the analytics engine in robot identification, include the VisitorIdentification Web control in all of your layouts. For example:

12.   Branch Template in Sitecore
This blog post describes how to use branch templates to create multiple pages at once.

Branch template consists of a branch template definition item, which can contain a single item, a hierarchy of items, or multiple hierarchies of items. When a user invokes a branch template, Sitecore duplicates the item(s) beneath the branch template definition item, including any field values, and then performs token substitution on item names and field values.
13.    Configure Web Deployment
To configure Web Deployment of file media from CM to CD, on the publishing instance or all CM instances:
1.       In the /App_Config/Include subdirectory, rename the WebDeploy.config.example file to WebDeploy.config (remove the .example extension).
2.       In the /App_Config/Include/WebDeploy.config file, configure parameters for the /configuration/sitecore/events/event/handler element as follows: 
14.   What to do if the Sitecore analytics does not track

If you are thinking about migrating or deploying Sitecore 8 (or 7.5) and use xDB as your new platform for analytics and personalization, Solr will be an essential requirement to make everything work. Continue reading Why is Solr essential in xDB 


16.   How to remove default sitecore media request extension(.ashx )
References :

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll

17.   What is the difference between sitecore placeholder and asp.net place holder? And use of sitecore placeholder
--> The placeholder is simply an area of the page to support the user adding controls
           A placeholder is a Sitecore-specific tag within a layout or sublayout which allows the dynamic placement of components within it.

Reference :

18.   What is the use of Scalability Settings config file?
19.   What is computed field in sitecore?
A computed index field allows you to perform additional processing before adding data to an index. For example, you may want to store the contents of a droplink field (the raw value being a GUID) as the target item's name, or a particular field value from the target item.

21.   How do you override web.config setting in sitecore
22.   Glass mapper module in sitecore
23.   In which db sitecore roles and users will be getting stored?
24.   What is index sharding?
25.   Replicated shards----- replicated shards are useful for handling failure and failover scenario
26.   Switching indexes in solr
27.   How to deploy Sitecore solution to Microsoft Azure using Visual Studio?https://sdn.sitecore.net/upload/sdn5/products/azure/310/getting_started_with_sitecore_azure_310-a4.pdf

28.   What is Page code component in speak?
The PageCode component injects the base JavaScript and CSS that a page needs ---http://mhwelander.net/2014/06/27/speak-for-newbies-part-1-creating-a-new-application/

29.  What is item cloning in sitecore?
30.  Difference between DropList and Droplink?
31. Difference between TreeListEx and TreeList?
For performance, you should use the TreelistEx field type in your data templates instead of the Treelist field type.
With a Treelist, the client renders the selection tree and the list of selected items whenever the user selects an item that contains the field.
With a TreelistEx, the client renders only the list of selected items, and does not render the selection tree until the user clicks the Edit command above the field. This is especially important for Treelists that invoke queries that can consume processing time on the server
32.   Difference between sitecore standard query and fast query?
Sitecore Query: Sitecore Query is most flexible in terms of filtering items right in the query using XPath functions. However, the more complex your query is, the longer it will take to run. This should be used when we try to query less than 100 items.

Fast QuerySitecore fast query is designed for retrieving and filtering items from the Sitecore database. Sitecore Fast Query uses the database engine to execute queries. Sitecore Fast Query has the following benefits compared to the standard SitecoreQuery
Improved performance – queries are executed by the SQL engine and as a result the scalability and performance of the SQL engine is not limited by .NET or by Sitecore.

 
Consumes less memory – Sitecore Query loads every item that it touches into memory (cache) and this can fill the cache with unnecessary information. Sitecore Fast Query only loads the items from the result set and this minimizes the pressure on the cache.
Sitecore Fast Query is similar to XPath and Sitecore Query statements in many ways. The most notable difference in using Fast Query is that you use the fast: keyword. Sitecore fast query should be used when we try to query more between 100 to 1000 items.

33.   What is Item Rendering in Sitecore?
What is shared layout and final layout in Sitecore8?
In Sitecore, you can specify shared presentation details for all versions of an item, in all    languages, and you can specify different presentation details for each individual version of an   item and for each language.
Shared Layout
Shared layout is like a shared field. All the controls added in this layout are shared among all the language ad numbered versions.

Final Layout
All the changes made to this layout are specific to that language and numbered version. Initially all the controls from shared layout are imported to the final layout. Once you start making any changes in the final layout, these changes will remain here and become specific to that particular language version and numbered version.

34.  Difference between Sitecore.Context.ContentDatabase and Sitecore.Context.Database
35. Mongo dB querying and reporting in sitecore
36. There is a sitecore indexing job running on sitecore if we install sitecore package will it impact indexing job
37. How to get the result of a first processor in the next processor in sitecore pipeline 
38. Sitecore Field extensions
39.  Add Single Item To Index. 
   Ref:  http://mikerobbins.co.uk/2013/09/03/sitecore-7-add-single-item-to-index/