How To Fix "The maximum string content length quota (8192) has been exceeded while reading XML data." error when calling WCF



TODO:

How to fix the error "The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader"

 

SOLUTION:

1.  Open your web.config. 

2.  Look for the binding entry for your Service. (<basicHttpBinding><binding name=...)

3.  Replace the value in the attribute maxStringContentLength="8192" with "2147483647"

 

NOTES:

There are no notes on this topic.

How To Create An Case Or Incident In Microsoft Dynamics CRM Online 2011 Programatically



TODO:

Have you ever wanted to create an Incident or Case in Micosoft Dynamics CRM Online programatically?


SOLUTION:

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using System.Runtime.Serialization;

using System.Configuration;
namespace My.CRM
{   
    public class MicrosoftCRMOnline
    {
        public void CreateIncident()
        {
            try
            {
                //BEGIN CONNECTION STUFF
                var connection = CrmConnection.Parse("Authentication Type=Passport; Server=https://YOUR-ORG.crm.dynamics.com; Username=user; Password=xxx; DeviceID=xxx-ws00001; DevicePassword=xxxx");
                var service = new OrganizationService(connection);
                var context = new CrmOrganizationServiceContext(connection);
                IOrganizationService _service = (IOrganizationService)service;


                //BEGIN LATE BOUND CREATION SAMPLE
                Entity incident = new Entity();
                incident.LogicalName = "incident";
                incident["title"] = "Test Case Creation";
                incident["description"] = "This is a test incident";

                //Set customerid with an existing contact guid 
                Guid customerid = new Guid("9BA22E13-1149-E211-8BE3-78E3B5107E67");     //the actual contact GUID.

                //Set customerid as contact to field customerid 
                EntityReference CustomerId = new EntityReference("contact", customerid);
                incident["customerid"] = CustomerId;

                //create the incident
                _service.Create(incident);


                //BEGIN EARLY BOUND CREATION SAMPLE

                //create a contact and assign the id to the Id above
                Contact newContact = new Contact();
                newContact.Id = customerid;

                Incident newIncident = new Incident();
                newIncident.Title = "Test Created With Proxy";                    //set the title
                newIncident.Description = "This is a test incident";               //set the description
                newIncident.CustomerId = newContact.ToEntityReference(); //set the Customer Id to the Entity Reference of the Contact

                //create the incident
                _service.Create(newIncident);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}

 

NOTES:

In order to create the Proxy Class (Early Bound Objects), you need to execute the following command, and add the .cs file to your project:

CrmSvcUtil.exe /url:https://YOUR-ORG.crm.dynamics.com/XRMServices/2011/Organization.svc /out:MicrosoftCRM2011OnlineProxy.cs /username:"username" /password:"xxxxxx"

 

**The CrmSvcUtil.exe is located in the bin folder of the SDK.

**Note that you use the same user and pass as in the code above, which is the windows live id you created to log into CRM Online.

How To Replace ScriptManager With RadScriptManager When



TODO:

Have you ever wanted to replace the ScriptManager that is in the master page with the RadScriptManager?  The code below will do just this for you!

 

SOLUTION:

protected override void OnInit(EventArgs e)
{
      Page.Init += delegate(object sender,EventArgs e_Init)
      {
            if(ScriptManager.GetCurrent(Page) != null)
            {
                    Page.Items.Remove(typeof(ScriptManager));
                    Telerik.Web.UI.RadScriptManagerscriptManager = new RadScriptManager();
                    Page.Form.Controls.AddAt(0, scriptManager);
             }
       };
       base.OnInit(e);
}

NOTES:

There are no notes on this topic.

How To Get The Public Key Of An Assembly In Visual Studio



 TODO:

Have you ever needed the public key for an assembly that is the output of a project in Visual Studio?

 

SOLUTION:

The solution is to tie the strong name tool (sn.exe) to a menu item under External Tools in Visual Studio.  There is a working solution on this link.  I tried it and it does exactly what I needed it to do.  The public key is written to the output window!

 

NOTES:

There are no notes on this topic.

How To Create a Custom App.Config File With Nested Elements



TODO:

Have you ever wanted a custom config, that had nested elements in it?  For example, I need a config file like such:

 

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="EmailServiceSettings" type="Donnie.Wishard.Configuration.EmailServiceSettings, EmailServiceSettings" />
  </configSections>

  <EmailServiceSettings Name="Test Site">
    <EmailServers>
      <Server Name="Local Server" IpAddress="127.0.0.1" />
    </EmailServers>
  </EmailServiceSettings>
</configuration>

 

And to accomplish that, you need the 2 pieces of code.

 

SOLUTION:

EmailServiceSettings.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Donnie.Wishard.Configuration
{
    /// <summary>
    /// Email service settings configuation section
    /// </summary>
    public sealed class EmailServiceSettings: ConfigurationSection
    {
        #region Member Variables
        private static EmailServiceSettings settings = ConfigurationManager.GetSection("EmailServiceSettings") as EmailServiceSettings;
        #endregion
        
        #region Fields
        /// <summary>
        /// Settings Property
        /// </summary>
        public static EmailServiceSettings Settings
        {
            get { return settings; }
        }

        /// <summary>
        /// The Id
        /// </summary>
        [ConfigurationProperty("Name", DefaultValue = "", IsRequired = true)]
        public string Name
        {
            get { return(string)this["Name"]; }
            set { this["Name"] = value; }
        }
        
        /// <summary>
        /// The collection of services / methods
        /// </summary>
        [ConfigurationProperty("EmailServers", IsDefaultCollection=true, IsKey=false, IsRequired=true)]
        public EmailServersCollection EmailServers
        {
            get { return base["EmailServers"] as EmailServersCollection; }
        }
        #endregion
        #region Methods
        #endregion
    }  
    /// <summary>
    /// The EmailServersCollection class
    /// </summary>
    public sealed class EmailServersCollection : ConfigurationElementCollection
    {
        #region Member Variables
        #endregion
        #region Fields
        /// <summary>
        /// Create method
        /// </summary>
        /// <returns></returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new EmailServerElement();
        }
        /// <summary>
        /// Get element key
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return((EmailServerElement)element).Name;   //key is method name for us
        }
        /// <summary>
        /// Name element
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        new public EmailServerElement this[string name]
        {
            get { return(EmailServerElement)base.BaseGet(name); }
        }
        /// <summary>
        /// Collection type setting
        /// </summary>
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }
       /// <summary>
        /// Index element
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public EmailServerElement this[int index]
        {
            get { return(EmailServerElement)base.BaseGet(index); }
        }
        /// <summary>
        /// Override the name
        /// </summary>
        protected override string ElementName
        {
            get
            {
                return "Server"; //force name of Server for elements
            }
        }
        #endregion
        #region Methods
        #endregion
    }

    /// <summary>
    /// The EmailServerElement class
    /// </summary>
    public sealed class EmailServerElement: ConfigurationElement
    {
        #region Member Variables
        #endregion
        #region Fields
        /// <summary>
        /// The Name
        /// </summary>
        [ConfigurationProperty("Name", DefaultValue = "", IsRequired = true)]
        public string Name
        {
            get { return (string)base["Name"]; }
            set { base["Name"] = value; }
        }
        /// <summary>
        /// The Method
        /// </summary>
        [ConfigurationProperty("IpAddress", DefaultValue = "", IsRequired = true)]
        public string Method
        {
            get { return (string)base["IpAddress"]; }
            set { base["IpAddress"] = value; }
        }
        #endregion
        #region Methods
        #endregion
    }
}

 

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Donnie.Wishard.Configuration
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Donnie.Wishard.Configuration.EmailServiceSettings s = Donnie.Wishard.Configuration.EmailServiceSettings.Settings;
            }
            catch (Exception x)
            {
                x = x;
            }
        }
    }
}

 

NOTES:

1.  Create a console application, and replace your Program.cs contents with the contents above.

2.  Create a class library in the solution, and put the EmailServiceSettings.cs code in it

3.  Add an app.config to the console application, using the config data from the top.

How To Add A Document As An Attachment To A New SharePoint List Item In C#



TODO:

Have you ever wanted to add a file, as an attachment to a new item in a SharePoint list?

 

SOLUTION:

        /// <summary>Add the contents of a file to a document library</summary>
        /// <param name="DocumentData">byte[] of the document data</param>
        /// <param name="SharePointUrl">The URL to the sharepoint server</param>
        /// <param name="SharePointSite">The name of the site the document library resides</param>
        /// <param name="DocumentLibrary">The name of the document library</param>
        /// <param name="MetaData">Any meta data you want to add.  For instance if there are other columns, you can specify them here.</param>
        /// <param name="OverWriteFile">Overwrite flag.  true or false, self explanatory</param>
        /// <returns></returns>
        public bool AddFileToList(byte[] DocumentData, string SharePointUrl, string SharePointSite, string List, Hashtable MetaData)
        {
            try
            {
                //get the site
                using (SPSite mysiteCollection = new SPSite(SharePointUrl))
                {
                    // Alternately you can use oSite.RootWeb if you want to access the main site
                    // but we will just do a find so we do not need to worry about levels
                    SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title.ToUpper() == SharePointSite.ToUpper(); });
                    //get the site by title (need to because name could be site/site...)              
                    using (SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id])   //now get the web by GUID
                    {
                        SPList incompleteList = rootSite.Lists[List];               //the list by display name
                        SPListItem newItem = incompleteList.Items.Add();            //get the item from the file just uploaded

                        //now add each item to the properties
                        if (MetaData != null)
                        {
                            //take each piece of meta data, and apply it to the item
                            foreach (object key in MetaData.Keys)
                            {
                                //newItem.Properties.Add(key, MetaData[key]);
                                newItem[key.ToString()] = MetaData[key];
                            }
                        }

                        newItem.Attachments.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData);   //add attachments to the list item
                        newItem.Update();   //update the item
                    }
                }
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }

 

NOTES:

The meta data are columns on the item.  You can populate those during the add, by passing them in in a Hashtable.

How To Add Document To A SharePoint Document Library C#



TODO:

Have you ever wanted to add a document to a SharePoint document library?  The below example, is a method that will allow you to do just that.

 

SOLUTION:

        /// <summary>
        /// Add the contents of a file to a document library
        /// </summary>
        /// <param name="DocumentData">byte[] of the document data</param>
        /// <param name="SharePointUrl">The URL to the sharepoint server</param>
        /// <param name="SharePointSite">The name of the site the document library resides</param>
        /// <param name="DocumentLibrary">The name of the document library</param>
        /// <param name="MetaData">Any meta data you want to add.  For instance if there are other columns, you can specify them here.</param>
        /// <param name="OverWriteFile">Overwrite flag.  true or false, self explanatory</param>
        /// <returns></returns>
        public bool AddFileToDocumentLibrary(byte[] DocumentData, string SharePointUrl, string SharePointSite, string DocumentLibrary, Hashtable MetaData, bool OverWriteFile)
        {
            try
            {
                //get the site
                using (SPSite mysiteCollection = new SPSite(SharePointUrl))
                {
                    //get web info by title (i need to do it this way)
                    SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title.ToUpper() == SharePointSite.ToUpper(); });
                    
                    //get the site by title (need to because name could be site/site...)              
                    using (SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id])   //now get the web by GUID
                    {
                        SPFile newFile = null;
                        SPFolder incompleteLibrary = rootSite.Folders[DocumentLibrary]; //the list by display name
                        
                        //now create a hash of our fields we want to set, and do it in one shot.
                        if (MetaData == null || MetaData.Count == 0)
                            newFile = incompleteLibrary.Files.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData, OverWriteFile);  //add it to the library
                        else
                            newFile = incompleteLibrary.Files.Add(string.Format("{0}.xml", Guid.NewGuid()), DocumentData, MetaData, OverWriteFile);  //add it to the library
                    }
                }
                
                return true;
            }
            catch (Exception x)
            {
                return false;
            }
        }

 

NOTES:

In my case, I was only adding XML files.  Therefore you can change the file name generation to use an extension that is passed in potentially.

How To Update Each Item In A SharePoint List Or Document Library When A Feature Is Activated



TODO:

Have you ever created an Event Receiver, and you would like to have it fire for all items in a list?  To do this, I created a Feature, that upon activation, will open a list or document library, and call Update() on each item in the list.  That will cause the Event Receiver to fire, thus applying its logic to each item in the list.

 

SOLUTION:

/// <summary>
/// Feature activated method
/// </summary>
/// <param name="properties"></param>
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
       try
       {
           //check the context
           if (SPContext.Current == null || SPContext.Current.Web == null || string.IsNullOrEmpty(SPContext.Current.Web.Url))
               return;

           // Use using to make sure resources are released properly  
           using (SPSite mysiteCollection = new SPSite(SPContext.Current.Web.Url))
           {
               // Alternately you can use oSite.RootWeb if you want to access the main site  
               SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title == "My Site Name"; });  //get the site by title (need to because name could be site/site)
               SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id];  //now get the web by GUID
                    
               SPList oList = rootSite.Lists["My List Name"];         //the list by display name
               foreach (SPListItem oItem in InputList.Items)
               {
                     //now just update it, so the event reciever fires
                     oItem.Update();
               }
           }
       }
       catch (Exception x)
       {   
       }
 }

 

NOTES:

There are no notes on this topic

 

How To Remove "Log In" link from BlogEngine.Net Sites



TODO:

Have you ever wanted to get rid of the "log in" link that appears on sites created with BlogEngine.Net?

 

SOLUTION:

1.  Edit the PageMenu.cs page that is located in BlogEngine.Net\App_Code\Controls\PageMenu.cs

2.  Chagne the BindPages() method to be the code below.

3.  Build BlogEngine.Net, and copy the DLLs to your "bin" folder.

 

private HtmlGenericControl BindPages()
{
            // recursivly get all children of the root page
            HtmlGenericControl ul = GetChildren(Guid.Empty);

            // items that will be appended to the end of menu list
            AddMenuItem(ul, Contact, "~/contact.aspx");

            if (Security.IsAuthenticated)
            {
                AddMenuItem(ul, Logoff, "~/Account/login.aspx?logoff");
            }
            else
            {
                //AddMenuItem(ul, Logon, "~/Account/login.aspx");
            }

            return ul;
}

 

 

NOTES:

All I did was comment out the else so that "log in" never appears.  If you navigate to http://site/account/login.aspx, you can log in.  In the event you do log in, you will get a "log out" link, but will never get the "log in" link.

How To Get The Value Of A Lookup Field Column In SharePoint



TODO:

Have you ever had a lookup column, and you want to get its value programatically using C#?

1.  I have a column that is called, Task Id.  

2.  "Task Id" in #1, is a lookup to the "ID" column of a list called "Tasks"

3.  I have an event receiver that needs to get the "Task Id" from the form.

 

SOLUTION:

 

//my event receiver code....
public override void ItemAdded(SPItemEventProperties properties)
{
     SPFieldLookup lookupField = properties.ListItem.Fields["Task ID"] as SPFieldLookup;
     SPFieldLookupValue taskIdVal = null;

     object obj = properties.ListItem["Task ID"];
     if (lookupField != null)
          taskIdVal = lookupField.GetFieldValue(obj.ToString()) as SPFieldLookupValue;

     string taskId = taskIdVal.LookupValue;
}

 

 

NOTES:

There are no notes on this topic.