Wednesday, September 28, 2011

Infopath - Unique form number/name generation?

This problem is always there when building InfoPath web forms.   As I know, there are many options:

  • Use "user login name" + "current time" as unique id;
Need to create a field for "unique id", and if there are millions of users, it may cause some potential conflict problem.
The "unique id" can be used as part of the file name.
The "unique id" could be quite long.
No coding needed.
  • Generate the unique ID through workflow after the form is submitted
Need to create a field for "unique id", and  need to promote this field to SharePoint column;  this column needs to be editable.
This id normally is based on the "Item ID" of the form file.
Normally cannot use this id as file name.
Can only generate the "unique id" after the form is submitted.
No coding needed
  • Generate the unique ID through coding
Need to create a field for "unique id".
The "unique id" can be used as part of the file name.


The last solution is my favorite. It's very flexible and easy to maintain.  Once the source code is ready, not hard to re-use it.

Below is the code which generate a GUID then convert it into a 11 characters unique ID string.

        public void setFileNameField()
        {
            string strElementPath = string.Empty;

            strElementPath = @"/my:myFields/my:FileName";
            XPathNavigator objFormFileName = MainDataSource.CreateNavigator().SelectSingleNode(strElementPath, NamespaceManager);
            string strFormFileName = objFormFileName.Value;
            if (string.IsNullOrEmpty(strFormFileName))
            {
                strFormFileName = string.Format("{0}", GenerateUniqueId());
                objFormFileName.SetValue(strFormFileName);
            }
        }

        public string GenerateUniqueId()
        {   //http://madskristensen.net/post/Generate-unique-strings-and-numbers-in-C.aspx
            string strId = string.Empty;

            byte[] buffer = Guid.NewGuid().ToByteArray();
            long lUniqueId = BitConverter.ToInt64(buffer, 0);

            StringBuilder sb = new StringBuilder(7);
            while (lUniqueId > 0)
            {
                int mod = (int)(lUniqueId % 62);
                if (mod < 10)
                {
                    sb.Append(mod);
                }
                else if (mod < 36)
                {
                    mod += 87;
                    sb.Append((char)mod);
                }
                else
                {
                    mod += 29;
                    sb.Append((char)mod);
                }
                lUniqueId = lUniqueId / 62;
            }

            strId = sb.ToString();

            return strId;
        }

        public void FormEvents_Loading(object sender, LoadingEventArgs e)
        {
            setFileNameField();
        }

No comments:

Post a Comment