Monday, June 11, 2012

How to serialize and deserialize any object to a compressed string

How to : Serialize and Deserialize a object into a compressed string

If you have ever needed to serialize some sort of object to a string for whatever reason we always trying to google some example of how to do it correctly. In the example below, I am going to serialize and compress a generic list to a string.

Serialization and Compression

        private static string CompressValue(object serializedValue)
        {
            try
            {
                BinaryFormatter bf = new BinaryFormatter();

                using (MemoryStream ms = new MemoryStream())
                {
                    bf.Serialize(ms, serializedValue);

                    byte[] inbyt = ms.ToArray();

                    using (MemoryStream objStream = new MemoryStream())
                    {
                        using (DeflateStream objZS = new DeflateStream(objStream, CompressionMode.Compress))
                        {
                            objZS.Write(inbyt, 0, inbyt.Length);
                            objZS.Flush();
                            objZS.Close();

                            byte[] b = objStream.ToArray();

                            return Convert.ToBase64String(b);
                        }
                    }
                }
            }
            catch { return string.Empty; }
        }

Deserialize object

        private List DeSerializeStringToObject(string serializedContent)
        {
            List retval = new List();

            byte[] bytCook = Convert.FromBase64String(serializedContent);

            using (MemoryStream inMs = new MemoryStream(bytCook))
            {
                inMs.Seek(0, 0);

                using (DeflateStream zipStream = new DeflateStream(inMs, CompressionMode.Decompress, true))
                {
                    byte[] outByt = ReadFullStream(zipStream);

                    zipStream.Flush();
                    zipStream.Close();

                    using (MemoryStream outMs = new MemoryStream(outByt))
                    {
                        outMs.Seek(0, 0);

                        BinaryFormatter bf = new BinaryFormatter();

                        retval = (List)bf.Deserialize(outMs, null);
                    }
                }
            }

            return retval;
        }

        private static byte[] ReadFullStream(Stream stream)
        {
            byte[] buffer = new byte[32768];

            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
And that is it, you can now serialized any object into a string and deserialize into your object again.

Happy coding guys...

ASP.NET Update Panel not reloading jquery

Issue: asp.net update panel not reloading custom jquery after a partial post back occurs.

Cause: The asp.net update panel reloads all the content within the content template tags, thus your custom jquery is not reloaded and never fired.

Solution: Add your custom jquery at the end of the request by using the page request manager object:

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function () {
        DOSTUFF();
    });

And problem solved, it's as easy as that.

I hope this helped you, it solved my problem.

Wednesday, November 9, 2011

How to Deploy Silverlight XAP file to a Document Library

Okay, so you have developed your silverlight application in SharePoint and you now want to deploy it. So you take your XAP file add it your document library and then reference it from your Silverlight Web Part right? Seems kind of like a long process, if you also had to deploy a whole bunch of web part with.

So we can make it simple by deploying our XAP with the rest of the web parts, lists, etc. All you need to do is follow a few simple steps and your XAP file will be deployed to your site with the rest of your customisations.

Step 1
Add a new module to your solution




Step 2

Right Click on the module you have just added and select properties.
Look for "Project Output References" click on the elipsis and click add.
Set the deployment type to a "ElementFile" and select your project name





Click ok and you should notice your Elements.xml has been modified to something like the following:


You can now proceed to change it to look like the below:

 

Happy coding guys I hope this helps make your deployment alot simpler.

Inserting SharePoint List item using Silverlight Object Model

If you finally came over to the dark side and embraced Silverlight in SharePoint you should familarize yourself with the Client API for Silverlight, I have mentioned in a previous post how to reference these assemblies.

If you want to be more adventourous and insert list items using the Client API you can use the following code:
ClientContext context = ClientContext.Current;

List oList = context.Web.Lists.GetByTitle("HelloWorldList");

ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["Title"] = "Hello World";
oListItem.Update();

context.Load(oList, list => list.Title);
context.ExecuteQueryAsync(OnSuccess, OnFailed);
The above method is done assyncrously so you will have a call back which means if the insert is success code sample A if it is unsuccessful run code sample B, see below:
private void onSuccess(object sender, ClientRequestSucceededEventArgs args)
{
   Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
      MessageBox.Show("successfull");
   });
}
 private void onFailed(object sender, ClientRequestFailedEventArgsargs)
{
   Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
      MessageBox.Show("Failed");
   });
}
As you know these operations are done assyncronously so simply put we have to get the attention of the UI thread to perform our success or failure action.
Happy coding :-)

Getting started with SharePoint 2010 Silverlight Client Object Model

Getting started with SharePoint 2010 Silverlight Client Object Model -

When you want to use the Silverlight Object Model the first thing we are going to is add a reference to silverlight assemblies:
  • Microsoft.SharePoint.Client.Silverlight.dll
  • Microsoft.SharePoint.Client.Silverlight.Runtime.dll
These assemblies can be found at the following location :
  • C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin
Then in your code just reference the assembly and you should be good to go as shown below:
  • using Microsoft.SharePoint.Client; 
    So happy coding guys, hope you enjoy the Silverlight Client Object Model

    Friday, October 7, 2011

    Create custom list using Content Type and Schema.xml file

    Creating a schema for a custom SharePoint list has always been something I think which could be much improved upon, as it is always something that may cause you to pull out your own teeth.

    In my experience the easiest way to do this is to replace the  ContentType tags with the following:

     

    Then it's as simple as adding your fields within the field tags of your schema.xml file, see below:



    You can always use the GUID generator that comes with Visual Studio to generate new GUID's for your different fields.

    Once complete, if you wish for your fields to be displayed in your view, add them to your ViewFields tags, (ViewFields tags can be found within the Views, View tag of your schema.xml file) as shown below:



    You have now successfully created a working schema.xml file, hope this helps in stopping you from tearing your hair out.

    How to access Init Parameters for SharePoint Silverlight Web Part

    Custom initialisation parameters are accessible from within the silverlight web part, these values, are values passed from the Sharepoint Silverlight web part into the Silverlight application.

    These values are passed in the form of a Dictionairy object and they are passed as follows:

    Key=Value,Key1=Value2
    These values can be accessed by using the following code:

    private void Application_Startup(object sender, StartupEventArgs e)
    {
     string value = e.InitParams["Key"];
    }
    Please let me know if this post has helped you, and if you have any improvements or comments please feel free to post them.