Bob Moore, Author at Perficient Blogs https://blogs.perficient.com/author/bmoore/ Expert Digital Insights Tue, 05 Apr 2011 04:18:00 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png Bob Moore, Author at Perficient Blogs https://blogs.perficient.com/author/bmoore/ 32 32 30508587 RSA Encryption using an SSL Certificate https://blogs.perficient.com/2011/04/04/rsa-encryption-using-an-ssl-certificate/ https://blogs.perficient.com/2011/04/04/rsa-encryption-using-an-ssl-certificate/#respond Tue, 05 Apr 2011 04:18:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=23

I was recently engaged on a project where we needed to create our own password vault for the execution of our API calls to external systems. The first cut of the encryption used Triple DES. Triple DES was great except we had to store the key in our code. The thought of storing the key in the code is fine if security is not a concern. Obfuscation was discussed, but I have encountered at least one de-obfuscator that worked well, so that was ruled out. Since our goal was to make the storage of the key maintainable by administrators we decided on RSA encryption using an SSL certificate. The certificate will have to be self signed so that we can use the private key for our encryption needs. I used Microsoft’s Certificate Creation Tool to generate my certificate. The certificate was then installed in the personal folder for the computer account.

Now that we got the certificate installed we can start using it. Below I will describe how to use the certificate for encryption. I have worked a bit with encryption in the past and found it easiest to create a class that encapsulates the functionality for a specific type of encryption. What I am going to show you for RSA is very similar to what I did with the Triple DES. The first thing I did was create a class called “Encryption” The class constructor took one parameter which was the certificate subject. The certificate subject is used in the retrieval of the certificate from the certificate store on the machine. The Constructor looks like the code shown below:

public Encryption(string certSubject)

{

X509Certificate2 cert = GetCert(certSubject);

publicXml = cert.PublicKey.Key.ToXmlString(false);

privateXml = cert.PrivateKey.ToXmlString(true);

}

A private method called GetCert (shown below) is used to get the X509 Certificate:

private X509Certificate2 GetCert(string certSubject)

{

X509Store store = new X509Store(StoreLocation.LocalMachine);

store.Open(OpenFlags.ReadOnly);

X509Certificate2 cert = null;

foreach (X509Certificate2 c in store.Certificates)

{

if (c.Subject == certSubject)

{

cert = c;

break;

}

}

store.Close();

return cert;

}

Now that we have a reference to the certificate and the key’s XML representation we can start using it. The method we use for encrypting is pretty straight forward and uses an RSACryptoProvider. The Encrypt method looks like the following:

public byte[] Encrypt(string data)

{

byte[] arInput = System.Text.Encoding.Unicode.GetBytes(data);

RSACryptoServiceProvider provider = new RSACryptoServiceProvider();

provider.Clear();

provider.FromXmlString(publicXml);

byte[] text = provider.Encrypt(arInput, false);

return text;

}

The first order of business is to convert the string to encrypt into a byte array. Once converted we can create our Crypto Provider. The clear method on the provider is called to clear out any default values. I figured this out the hard way; my provider did not like using the key I was feeding it when I did not call clear. Once the provider is cleared we can now load our key that we got from the SSL certificate. Once that is done we can encrypt our string/byte array.

The encrypt method returns a byte array. You can either store the byte array in its native format or you can do as we did and convert it to a string. This leads us to our next public method in the class. I created the method as static in the event that we wanted to use this functionality elsewhere…I did not want to force the creation of the encryption object to do something that is not related to encryption.

public static string ConvertByteArrayToString(byte[] data)

{

return BitConverter.ToString(data);

}

Now that we have the encrypted data converted to a string we can store it in a database or where ever the application calls for. Now let’s focus on the decryption. The Decrypt method has two signatures; one takes a string and the other takes a byte array. The methods for the decryption are shown below:

public string Decrypt(byte[] data)

{

CspParameters parms = new CspParameters();

parms.Flags = CspProviderFlags.UseMachineKeyStore;

RSACryptoServiceProvider provider = new RSACryptoServiceProvider(parms);

provider.FromXmlString(privateXml);

byte[] unencryptedData = provider.Decrypt(data, false);

return System.Text.Encoding.Unicode.GetString(unencryptedData);

}

public string Decrypt(string data)

{

if (data.Trim() == string.Empty)

return data;

byte[] arData = Encryption.ConvertStringToByteArray(data);

return Decrypt(arData);

}

The method that takes the string parameter should be self explanatory so I am not going to talk about it. The method that accepts the byte array is the one we will discuss. The first that I have to do is Create CspParameters to pass into the crypto provider. The flag we are specifying is for the provider to use the machine key store. Once we create our provider with the specified parameters we can give it our private key information that we retrieved as part of our constructor. Once that is done we can start decrypting.

The only other method I have not discussed is another static method that we will use for converting a string to a byte array. The method looks like the following:

public static byte[] ConvertStringToByteArray(string encryptedData)

{

string[] arData = encryptedData.Split("-".ToCharArray());

byte[] returnData = new byte[arData.Length];

for (int i = 0; i < arData.Length; i++)

returnData[i] = byte.Parse(arData[i], NumberStyles.HexNumber);

return returnData;

}

The code above just takes each byte and converts it one byte at a time to a character.

When coding this there were no issues until we started deploying this to production. One of the major gotchas was the app pool account for the web application needs to have read rights on the certificate. This is a gotcha that only occurs on Windows Server 2008. There are plenty of articles out there that will explain how to set the permissions for a certificate.

]]>
https://blogs.perficient.com/2011/04/04/rsa-encryption-using-an-ssl-certificate/feed/ 0 223700
Personalize Your Publishing Console https://blogs.perficient.com/2010/04/02/personalize-your-publishing-console/ https://blogs.perficient.com/2010/04/02/personalize-your-publishing-console/#respond Sat, 03 Apr 2010 03:51:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=22

Wouldn’t it be nice in SharePoint 2007 if we could put our own buttons into the publishing menu?We can…it just takes a few steps.The steps taken are determined by the master page that is used.If you are using default.master, you will need to create a delegate control.There are plenty of examples for adding your own delegate control, so I will not go into that.My delegate control was copied from the PublishingMenu.ascx.The control we want to change within the publishing console is called the QuickAccessMenu.I wanted to start a custom workflow that was part of an approval process and I wanted users to enter comments when the workflow was started.I created my own check in page that the button redirects the users to when it is clicked. My check in page requires comments and starts a workflow.To do this I created my own QuickAccessMenu control that instantiates the MS QuickAccessMenu.I then use the following code to change the functionality of the Submit for Review button:

 

public override void RenderControl(HtmlTextWriter writer)

{

int location = GetControlLocation();

if (location > 0)

{

Control pub = menu.FindControl(“qaApprovePublish”);

if (pub != null && !SPContext.Current.Web.CurrentUser.IsSiteAdmin)

pub.Visible = false;

 

Control ctrl = (Control)menu.Controls[location];

PublishingButton button = (PublishingButton)ctrl.Controls[0];

button.DisplayText = “Start Custom Workflow”;

string url = string.Format(“{2}/_layouts/CustomLayouts/CustomCheckin.aspx?List={0}&FileName={1}&Publish=true&Source={1}&ListItemID={3}”, SPContext.Current.ListItem.ParentList.ID.ToString(“B”), SPContext.Current.Item[“FileRef”].ToString(), SPContext.Current.Web.Url, SPContext.Current.ListItem.ID);

button.ClientOnClickScript = string.Format(“location.href='{0}'”, url);

}

 

base.RenderControl(writer);

}

 

The code above searched for a control called “qaPublish” and changes the some properties on the button before rendering. When the control is rendered it looks like the following image:

You can add new buttons to the control as well. The button type is PublishingButton. This will allow you to start workflows from these buttons or anything else you want.

]]>
https://blogs.perficient.com/2010/04/02/personalize-your-publishing-console/feed/ 0 223649
The LookupWithPicker is not just for Lookup Fields https://blogs.perficient.com/2010/03/15/the-lookupwithpicker-is-not-just-for-lookup-fields/ https://blogs.perficient.com/2010/03/15/the-lookupwithpicker-is-not-just-for-lookup-fields/#respond Tue, 16 Mar 2010 04:31:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=21

I recently had a client requirement to associate documents and pages within SharePoint to specific pages.The client wanted to associate the documents / pages through metadata. After thinking about this for a while I remembered the lookup with picker control on CodePlex. The picker control on CodePlex was designed to work with lookup fields and I wasn’t prepared to have a metadata field for each pages library or document library in the system.I decided to change the lookup with picker to perform a site query be content type and show the results title and file reference. To do this I had one obstacle to overcome…what kind of field should this be? The easiest way was to make it a note field and require the users edit the field on the page. In this post I will explain what I had to change in the picker to get this to work.

LookupWithPickerField

A custom field control was required for displaying the field control on the page layout. The field control resembles a picker field. While in edit mode the users would see the following:

 

The field displays the selected item along with the icon to open the picker. I removed the icon to validate typed in items and also disabled the ability to type in the item. The custom field also contains the following properties:

·ContentTypeName – This property is used by the picker dialog for the site query

·IsDocLib – Since the site query needs the type of library to search I need to know if it is a pages library or document library

·AllowMultipleValues – Allows for multi select in the picker dialog

CustomLookupEntityEditor

This class is the control that is rendered in the picture above. The class extends the EntityEditorWithPicker class. The code for this class overrides the init method and sets the PickerDialogType, AllowTypeIn, and the CheckButtonImageName. AllowTypeIn is set to false since I do not want users to manually type in the field and the CheckButtonImageName is set to blank.gif because I do not want to show the button.

CustomLookupPickerDialog

The next class I changed was the CustomLookupPickerDialog. I added the fields I wanted to display in the dialog along with the column widths for each field. n this case I am displaying Title and FileRef.

CustomLookupQueryControl

The CustomLookupQueryControl is the class that is doing all of the heavy lifting. This class takes the content type name supplied on the LookupWithPickerField properties and uses it to query the entire site. When a user clicks the book icon that is displayed in the field control the results will appear like the following image:

A user can then select the item(s) they are looking for.If there is a lot of data the search results can be narrowed by typing text in the box at the top and clicking the search button. The two fields that are displayed in the picker are the fields that are saved in the note field as part of the metadata.

]]>
https://blogs.perficient.com/2010/03/15/the-lookupwithpicker-is-not-just-for-lookup-fields/feed/ 0 223663
Access is Denied During stsadm restore https://blogs.perficient.com/2010/02/12/access-is-denied-during-stsadm-restore/ https://blogs.perficient.com/2010/02/12/access-is-denied-during-stsadm-restore/#respond Sat, 13 Feb 2010 05:09:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=20
I was recently trying to restore an environment at a client site and kept getting access is denied. This baffled me because the account I was using had the proper database permissions to perform the task at hand and is a local admin on the server. The user is the account that I was used to create the web application.
 
It turns out the the user performing the restore needs to be a site collection administrator to restore from a backup. So in review the user account must have the proper rights (in my case they were dbo on the database) and be a site collection administrator on the site that you are trying to overwrite.
]]>
https://blogs.perficient.com/2010/02/12/access-is-denied-during-stsadm-restore/feed/ 0 223665
How to create a Document Set using C# https://blogs.perficient.com/2009/12/30/how-to-create-a-document-set-using-c/ https://blogs.perficient.com/2009/12/30/how-to-create-a-document-set-using-c/#respond Wed, 30 Dec 2009 20:13:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=18
I decided to expand on one of Travis Neilson’s posts called Introducing Documents Sets. Being the eternal developer that I am I decided to write a blog on how to create a Document Set using C# and the new object model for SP2010.
 
In trying to figure out how to do this, I though I would try the 2007 way and add a new ListItem to my test document library….well that didn’t work so well. While I was looking at the code for the NewDocSet.aspx page I stumbled upon a new assembly and namespace. The assembly that I am referring to is Microsoft.Office.DocumentManagement and the namespace is Microsoft.Office.DocumentManagement.DocumentSets. Within the new namespace lives the DocumentSet class. The DocumentSet class is makes it pretty easy for creating a DocumentSet. Using the same content types from Travis’ blog I created a quick console application to create the DocumentSet in code. Below are the lines of code necessary to create a DocumentSet using the default content: 
SPSite site = newSPSite(“http://sp2010”);
SPWeb web = site.OpenWeb();
SPList list = web.Lists[“Proposals”];
Hashtable props = newHashtable();
props.Add(“Name”, “Proposal 1”);
props.Add(“Description”, “Proposal 1”);
props.Add(“Customer ID”, “1234”);
props.Add(“Customer Name”, “Customer 1”);
DocumentSet ds = DocumentSet.Create(list.RootFolder, “Proposal 2”, list.ContentTypes[“Proposals”].Id, props, true);
web.Dispose();
site.Dispose();
If you do not want to provision default content then after you create the DocumentSet you can add the desired content by manipulating the Item property (SPListItem) of the DocumentSet.
]]>
https://blogs.perficient.com/2009/12/30/how-to-create-a-document-set-using-c/feed/ 0 223483
How to create Term Store groups and Term Sets in C# https://blogs.perficient.com/2009/12/30/how-to-create-term-store-groups-and-term-sets-in-c/ https://blogs.perficient.com/2009/12/30/how-to-create-term-store-groups-and-term-sets-in-c/#respond Wed, 30 Dec 2009 19:58:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=19
After being shown the Managed Metadata Service and the Term Stores in SharePoint 2010, I felt the need to figure out how to create all of the items that were shown to me in code. Below is a list of new classes that we will be using to accomplish the task:
  • TaxonomySession
  • TermStore
  • Group
  • TermSet

The code below will create a new group called “A Group” and then create a TermSet and populating the TermSet with items. Here is the code:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = new SPSite(http://sp2010);
TaxonomySession ts = new TaxonomySession(site);
TermStore termStore = ts.TermStores[1];
Group group = termStore.CreateGroup(“A Group”);
TermSet termSet = group.CreateTermSet(“Term Set 1”);
termSet.CreateTerm(“Term 1”, 1033);
termSet.CreateTerm(“Term 2”, 1033);
termSet.CreateTerm(“Term 3”, 1033);
termStore.CommitAll();
});

Here is what the final output looks like when looking at it in Central Administration:

]]>
https://blogs.perficient.com/2009/12/30/how-to-create-term-store-groups-and-term-sets-in-c/feed/ 0 223484
How to create a Document Set using C# https://blogs.perficient.com/2009/10/23/how-to-create-a-document-set-using-c-2/ https://blogs.perficient.com/2009/10/23/how-to-create-a-document-set-using-c-2/#respond Fri, 23 Oct 2009 21:47:00 +0000 http://blogs.pointbridge.com/Blogs/2010wave/Pages/Post.aspx?_ID=38
I decided to expand on one of Travis Nielson’s posts called Introducing Documents Sets. Being the eternal developer that I am I decided to write a blog on how to create a Document Set using C# and the new object model for SP2010.
 
In trying to figure out how to do this, I though I would try the 2007 way and add a new ListItem to my test document library….well that didn’t work so well. While I was looking at the code for the NewDocSet.aspx page I stumbled upon a new assembly and namespace. The assembly that I am referring to is Microsoft.Office.DocumentManagement and the namespace is Microsoft.Office.DocumentManagement.DocumentSets. Within the new namespace lives the DocumentSet class. The DocumentSet class makes it pretty easy for creating a DocumentSet. Using the same content types from Travis’ blog I created a quick console application to create the DocumentSet in code. Below are the lines of code necessary to create a DocumentSet using the default content: 
SPSite site = newSPSite(“http://sp2010”);
SPWeb web = site.OpenWeb();
SPList list = web.Lists[“Proposals”];
Hashtable props = newHashtable();
props.Add(“Name”, “Proposal 1”);
props.Add(“Description”, “Proposal 1”);
props.Add(“Customer ID”, “1234”);
props.Add(“Customer Name”, “Customer 1”);
DocumentSet ds = DocumentSet.Create(list.RootFolder, “Proposal 2”, list.ContentTypes[“Proposals”].Id, props, true);
web.Dispose();
site.Dispose();
If you do not want to provision default content then after you create the DocumentSet you can add the desired content by manipulating the Item property (SPListItem) of the DocumentSet.
]]>
https://blogs.perficient.com/2009/10/23/how-to-create-a-document-set-using-c-2/feed/ 0 223510
Multiple Data Items Per ROW Using XSLT https://blogs.perficient.com/2009/05/15/multiple-data-items-per-row-using-xslt/ https://blogs.perficient.com/2009/05/15/multiple-data-items-per-row-using-xslt/#respond Fri, 15 May 2009 21:10:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=17
I had to come up with some XSL for a client to display multiple bios and and pictures per data row. I did a bit of searching and put together my XSL based on some stuff I had read. There was no real example like I am about to show you. Here is the scenario…the client wanted the information stored in a list within SharePoint and wanted to display it in the following manner:
Image 1 Name
Title
Bio Link
Image 2 Name
Title
Bio Link
Image 3 Name
Title
Bio Link
Image 4 Name
Title
Bio Link
Image 5 Name
Title
Bio Link
Image 6 Name
Title
Bio Link
Image 7 Name
Title
Bio Link
Image 8 Name
Title
Bio Link
Once I figure out the solution it seems easy. Here a form of the XSL I used for this. The key is the mod operator. This will determine the number of columns. For this example it is set to 2. I used DIV tags in this case; however it does not matter what the container is. This blog still applies to any side by side data.
<xsl:template name="dvt_1.body">
<xsl:param name="Rows"/>
<xsl:for-each select="$Rows">
<xsl:if test="position()mod 2 = 1">
<div class="styleclass">
<xsl:call-template name="dvt_1.rowview"/>
</div>
</xsl:if>
</xsl:for-each>
</xsl:template>
<xsl:template name="dvt_1.rowview">
<DIV class="containerforitem1">
//fill the container for the first item
</DIV>
<xsl:choose>
<xsl:when test="position() != last()">
<DIV class="containerforitem2">
//fill the second container
</DIV>
</xsl:when>
<xsl:otherwise>
<DIV class="contactitem">
//make the second container empty if it has passed the last item
</DIV>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
If your mod operator is 3 then you will have more code to accomodate the third column…and so on.
]]>
https://blogs.perficient.com/2009/05/15/multiple-data-items-per-row-using-xslt/feed/ 0 223421
Use RPC to create a SharePoint Sub Site https://blogs.perficient.com/2009/05/15/use-rpc-to-create-a-sharepoint-sub-site/ https://blogs.perficient.com/2009/05/15/use-rpc-to-create-a-sharepoint-sub-site/#respond Fri, 15 May 2009 18:37:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=16
I am working on an internal project that requires me to create and delete sites from a remote SharePoint site. My first thoughts were "this will be easy I will use web services to do it". Well I was wrong, the admin service only deals with site collections and not sub sites, so I had to do it the old fashioned way…RPC. I read a blog when I was looking for an example that said SharePoint designer uses RPC. I then started fiddler and SPD and created a site and deleted a site. This gave me everything I needed to make my RPC call. Since there are few examples out there on how to do this, I thought I would provide some actual working ones. Below are code examples for creating and deleting SP sites:
First is the method for creating the site:

private static string CreateSiteRequest(string parentSiteURL, string newSiteRelativeURL, NetworkCredential credential, string spVersion)

{

HttpWebRequest objRequest = (HttpWebRequest)HttpWebRequest.Create(parentSiteURL + "/_vti_bin/_vti_adm/admin.dll");

objRequest.Method = WebRequestMethods.Http.Post;

objRequest.Credentials = credential;

objRequest.Headers.Add("X-Vermeer-Content-Type", "application/x-www-form-urlencoded");

objRequest.ContentType = "application/x-www-form-urlencoded";

StreamWriter sw = new StreamWriter(objRequest.GetRequestStream());

sw.Write(string.Format("method=create service:{0}&service_name={1}&flags=0&lcid=0", spVersion, newSiteRelativeURL));

sw.Close();

HttpWebResponse objResponse = objRequest.GetResponse() as HttpWebResponse;

StreamReader sr = new StreamReader(objResponse.GetResponseStream());

sr.Close();

objResponse.Close();

return string.Empty;

}

After the site has been created, we need to apply the template to the site:

private static string ApplyTemplate(string newSiteAbsoluteURL, NetworkCredential credential, string templateName)

{

HttpWebRequest objRequest = (HttpWebRequest)HttpWebRequest.Create(newSiteAbsoluteURL + "/_vti_bin/owssvr.dll?Cmd=DisplayPost");

objRequest.Method = WebRequestMethods.Http.Post;

objRequest.Credentials = credential;

objRequest.Headers.Add("X-Vermeer-Content-Type", "application/xml");

objRequest.ContentType = "application/xml";

StreamWriter sw = new StreamWriter(objRequest.GetRequestStream());

sw.Write(string.Format("<?xml version="1.0" encoding="UTF-8"?><ows:Batch OnError="Return" Version="12.0.0.000"><Method ID="0,SiteProvision"><SetVar Name="Cmd">SiteProvision</SetVar><SetVar Name="CreateLists">True</SetVar><SetVar Name="SiteTemplate">{0}</SetVar></Method></ows:Batch>", templateName));

sw.Close();

HttpWebResponse objResponse = objRequest.GetResponse() as HttpWebResponse;

StreamReader sr = new StreamReader(objResponse.GetResponseStream());

sr.Close();

objResponse.Close();

return string.Empty;

}

There is some other meta data that can get set, but the purpose of this blog is to provide a good example on creating sites via RPC.

Below illustrated the code on setting the title for a site:

private static void SetSiteTitle(string newSiteAbsoluteURL, NetworkCredential credential, string siteTitle)

{

HttpWebRequest objRequest = (HttpWebRequest)HttpWebRequest.Create(newSiteAbsoluteURL + "/_vti_bin/owssvr.dll?Cmd=DisplayPost");

objRequest.Method = WebRequestMethods.Http.Post;

objRequest.Credentials = credential;

objRequest.Headers.Add("X-Vermeer-Content-Type", "application/xml");

objRequest.ContentType = "application/xml";

StreamWriter sw = new StreamWriter(objRequest.GetRequestStream());

sw.Write(string.Format("<?xml version="1.0" encoding="UTF-8"?><ows:Batch OnError="Return" Version="12.0.0.000"><Method ID="0,UpdateProject"><SetVar Name="Cmd">UpdateProject</SetVar><SetVar Name="NewListTitle">{0}</SetVar><SetVar Name="owshiddenversion">-1</SetVar></Method></ows:Batch>", siteTitle));

sw.Close();

HttpWebResponse objResponse = objRequest.GetResponse() as HttpWebResponse;

StreamReader sr = new StreamReader(objResponse.GetResponseStream());

sr.Close();

objResponse.Close();

}

Finally, here is how you delete a site:

public static bool DeleteSite(string parentSiteURL, string relativeURLToDelete, NetworkCredential credentials, string spVersion)

{

HttpWebRequest objRequest = (HttpWebRequest)HttpWebRequest.Create(parentSiteURL + "/_vti_bin/_vti_adm/admin.dll");

objRequest.Method = WebRequestMethods.Http.Post;

objRequest.Credentials = credentials;

objRequest.Headers.Add("X-Vermeer-Content-Type", "application/x-www-form-urlencoded");

objRequest.ContentType = "application/x-www-form-urlencoded";

StreamWriter sw = new StreamWriter(objRequest.GetRequestStream());

sw.Write(string.Format("method=remove service:{0}&service_name={1}&flags=default", spVersion, relativeURLToDelete));

sw.Close();

HttpWebResponse objResponse = objRequest.GetResponse() as HttpWebResponse;

StreamReader sr = new StreamReader(objResponse.GetResponseStream());

sr.Close();

objResponse.Close();

return true;

}

]]>
https://blogs.perficient.com/2009/05/15/use-rpc-to-create-a-sharepoint-sub-site/feed/ 0 223422
Intallation Error. IdentityNotMappedException: Some or all identity references could not be translated. https://blogs.perficient.com/2009/04/14/intallation-error-identitynotmappedexception-some-or-all-identity-references-could-not-be-translated/ https://blogs.perficient.com/2009/04/14/intallation-error-identitynotmappedexception-some-or-all-identity-references-could-not-be-translated/#respond Tue, 14 Apr 2009 17:58:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=15
I recently got a new laptop and installed SharePoint on it. All was working well until I had to rename my laptop. After renaming my laptop I thought I could remove the farm and rerun the SharePoint Configuration Wizard. After doing so, the wizard kept erroring out on the creation of the config database. The error message that I was getting was:
Intallation Error: System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated.
As it turns out, when you remove a farm from a machine, the process does not remove the application pools that SharePoint previously used. The application pools had the identity of the old service account in it so that caused the exception.
After deleting the old application pools the configuration wizard completed succesfully.
]]>
https://blogs.perficient.com/2009/04/14/intallation-error-identitynotmappedexception-some-or-all-identity-references-could-not-be-translated/feed/ 0 223442
Pain in the AssetUploader.aspx https://blogs.perficient.com/2008/09/02/pain-in-the-assetuploader-aspx/ https://blogs.perficient.com/2008/09/02/pain-in-the-assetuploader-aspx/#respond Tue, 02 Sep 2008 16:21:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=14

Well actually it was the alternate access mappings that were messing this up. We are using AAMs for our public internet site. Normally you think that this would not cause a problem, but it did with the assetuploader.aspx page. In a nut shell the images were uploaded via https and are viewed via http in the uploader. The uploader was expecting the images via https and not http. This would cause the uploader not to show the thumbnail of the image. Needless to say, our end users did not like that, so I came up with the following solution:

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public partial class AssetUploader : AssetThumbnailerPage
{
#region OnLoad
protected override void OnLoad(EventArgs e)
{
int thumbSmallSize = 70;
int normalSize = 140;
string imageSize = string.Empty;

if (Request["ImageUrl"] == null || Request["ImageUrl"].StartsWith("http"))
{
base.OnLoad(e);
return;
}

if (Request["Size"] == null || Request["Size"] == string.Empty)
imageSize = "Small";
else
imageSize = Request["Size"];

if (Request["ImageUrl"] != null && Request["ImageUrl"].StartsWith("/"))
{
SPSite site = null;
SPWeb web = null;

try
{
Uri uri = new Uri(SPContext.Current.Web.Url);
site = new SPSite(SPContext.Current.Web.Url);
web = site.OpenWeb();
string url = uri.Scheme + "://" + uri.Host + Request["ImageUrl"];
SPFile file = MyAssetThumbnailer.RetrieveFile(url, out web);
byte[] fileByes = file.OpenBinary();
if (imageSize.ToLower().Equals("small"))
Response.BinaryWrite(JLLAssetThumbnailer.CreateThumbnail(fileByes, thumbSmallSize));
else
Response.BinaryWrite(JLLAssetThumbnailer.CreateThumbnail(fileByes, normalSize));
}

catch(Exception ex)
{
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex, "General");
base.OnLoad(e);
}

finally
{
web.Close();
web.Dispose();
site.Close();
site.Dispose();
}
}
}

internal class MyAssetThumbnailer
{
#region Constructor
private MyAssetThumbnailer()
{

}
#endregion

#region CreateThumbnail
public static byte[] CreateThumbnail(byte[] inputBuffer, int thumbMaxDimension)
{
MemoryStream stream = new MemoryStream(inputBuffer);
Bitmap bitmap = new Bitmap(stream);
Size imageSize = bitmap.Size;
Size size2 = getThumbnailDimensions(imageSize, thumbMaxDimension);
if (size2 == imageSize)
{
object[] objArray = new object[] { thumbMaxDimension.ToString(CultureInfo.InvariantCulture), imageSize.Width.ToString(CultureInfo.InvariantCulture), imageSize.Height.ToString(CultureInfo.InvariantCulture), inputBuffer.Length.ToString(CultureInfo.InvariantCulture) };
//ULS.SendTraceTag(ULSTagID.tag_6osl, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Medium, "No thumbnail made – thumbnail size [%s] is greater than image dimensions[%sx%s] bytes: %s", objArray);
return inputBuffer;
}
object[] data = new object[] { size2.Width.ToString(CultureInfo.InvariantCulture), size2.Height.ToString(CultureInfo.InvariantCulture), imageSize.Width.ToString(CultureInfo.InvariantCulture), imageSize.Height.ToString(CultureInfo.InvariantCulture), inputBuffer.Length.ToString(CultureInfo.InvariantCulture) };
//ULS.SendTraceTag(ULSTagID.tag_6osm, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Medium, "Generating thumbnail with dimensions[%sx%s] for image with dimensions[%sx%s] bytes: %s", data);
return imageObjectToBytes(bitmap.GetThumbnailImage(size2.Width, size2.Height, new System.Drawing.Image.GetThumbnailImageAbort(JLLAssetThumbnailer.thumbnailCallback), IntPtr.Zero));
}
#endregion

#region getThumbnailDimensions
private static Size getThumbnailDimensions(Size imageSize, int thumbMaxDimension)
{

if ((imageSize.Height > thumbMaxDimension) || (imageSize.Width > thumbMaxDimension))
{
SizeF ef = new SizeF((float)thumbMaxDimension, (float)thumbMaxDimension);
if (imageSize.Height <= imageSize.Width)
{
ef.Height = (imageSize.Height * thumbMaxDimension) / imageSize.Width;
}
else
{
ef.Width = (imageSize.Width * thumbMaxDimension) / imageSize.Height;
}
if (ef.Width < 1f)
{
ef.Width = 1f;
}
if (ef.Height < 1f)
{
ef.Height = 1f;
}
if (ef.Width > thumbMaxDimension)
{
ef.Width = thumbMaxDimension;
}
if (ef.Height > thumbMaxDimension)
{
ef.Height = thumbMaxDimension;
}
return Size.Ceiling(ef);
}
return imageSize;
}
#endregion

#region imageObjectToBytes
private static byte[] imageObjectToBytes(System.Drawing.Image imageObject)
{
MemoryStream stream = new MemoryStream();
imageObject.Save(stream, ImageFormat.Jpeg);
return stream.ToArray();
}
#endregion

#region RetrieveFile
public static SPFile RetrieveFile(string imageSPFileUrl, out SPWeb web)
{
SPFile fileOrFolderObject = null;
SPSite site = null;
web = null;
try
{
Uri uri2 = new Uri(HttpContext.Current.Request.Url, imageSPFileUrl);
site = SPContext.Current.Site;
SPSecurity.CatchAccessDeniedException = false;
web = site.OpenWeb();
fileOrFolderObject = web.GetFileOrFolderObject(uri2.AbsoluteUri) as SPFile;
}
catch (UnauthorizedAccessException exception)
{
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(exception, "General");
// ULS.SendTraceTag(ULSTagID.tag_7fl7, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.High, "Access was denied to the object when trying to thumbnail the following URL: [%s] [%s]", new object[] { imageSPFileUrl, exception.ToString() });
}
catch (SPException exception2)
{
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(exception2, "General");
// ULS.SendTraceTag(ULSTagID.tag_7fl8, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.High, "Could not retrieve file when trying to generate a thumbnail for the following URL : [%s] [%s]", new object[] { imageSPFileUrl, exception2.ToString() });
}
return fileOrFolderObject;
}
#endregion

#region thumbnailCallback
private static bool thumbnailCallback()
{
return false;
}
#endregion
}

The class MyAssetThumbnailer came from disassembling the code that the original asset uploader uses. I was unable to use the actual assembly because the class is marked internal. Microsoft did not make it easy on me, but .net reflector gave me what I needed to get this done.

]]>
https://blogs.perficient.com/2008/09/02/pain-in-the-assetuploader-aspx/feed/ 0 223248
Userdisp.aspx not Redirecting to Public Profile Page https://blogs.perficient.com/2008/09/01/userdisp-aspx-not-redirecting-to-public-profile-page/ https://blogs.perficient.com/2008/09/01/userdisp-aspx-not-redirecting-to-public-profile-page/#respond Tue, 02 Sep 2008 03:07:00 +0000 http://blogs.pointbridge.com/Blogs/Moore_Bob/Pages/Post.aspx?_ID=13

I found out that when your intranet site and your my sites have different URLs, the userdisp.aspx page is not aware enough to redirect you to the public profile page within it’s own farm. This is a little surprising to me considering you set the my site URL within the shared service provider. After disassembling the code for userdisp and a little digging, I realized that there is a control on userdisp that handles the profile redirection. The control name is ProfileRedirect. ProfileRedirect contains a user control called MySiteRedirectionUserControl. MySiteRedirectionUserControl is what does all of the work, unfortunately for me the code that does the work id obfuscated. So…based on this I decided to write my own code that will be used by userdisp. Not knowing what is really going on I decided to override the oninit method of userdisp. The code looks like the following:

public class MyUserDisplayPage :UserDisplayPage

{

protected override void OnInit(EventArgs evtargs)

{

base.OnInit(evtargs);

try

{

UserProfileManager pm = new UserProfileManager(ServerContext.Current);

UserProfile p = pm.GetUserProfile(this.UserListForm.Item["Account"].ToString());

if (p != null)

Page.Response.Redirect(p.PublicUrl.ToString());

}

catch { }

}

}

Notes:

  • You must call the base oninit first, otheriste the UserListForm object will be null
  • The namespaces used are Microsoft.SharePoint.AppkicationPages, Microsoft.Office.Server, and Microsoft.Office.Server.UserProfiles
  • If a user does not exist in the profile store then you will not see the public profile page, the userdisp.aspx page will show.

I am currently working with Microsoft on a resolution that does not involve this code change, so I they have something for me other than setting the portal URL (yes they did suggest that and I said that was unacceptable), I will post another blog regarding how to fix it.

]]>
https://blogs.perficient.com/2008/09/01/userdisp-aspx-not-redirecting-to-public-profile-page/feed/ 0 223250