public static SearchInputs GetInputs(Property[] inputs)
        {
            SearchInputs InputValues = new SearchInputs();

            string search = string.Empty;
            var searchProp = inputs.Where(p => p.Name.Equals("search", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (searchProp != null && searchProp.Value != null && !string.IsNullOrWhiteSpace(searchProp.Value.ToString()))
            {
                search = searchProp.Value.ToString();
                InputValues.Search = search;
            }
            else
            {
                throw new Exception("Search is a required property");
            }

            string searchsiteurl = string.Empty;
            var searchsiteurlprop = inputs.Where(p => p.Name.Equals("searchsiteurl", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (searchsiteurlprop != null && searchsiteurlprop.Value != null && !string.IsNullOrWhiteSpace(searchsiteurlprop.Value.ToString()))
            {
                searchsiteurl = searchsiteurlprop.Value.ToString();
                InputValues.SiteUrl = searchsiteurl;
            }
            //else
            //{
            //    throw new Exception("Site Url is a required property");
            //}


            string properties = string.Empty;
            var propertiesprop = inputs.Where(p => p.Name.Equals("properties", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (propertiesprop != null && propertiesprop.Value != null && !string.IsNullOrWhiteSpace(propertiesprop.Value.ToString()))
            {
                properties = propertiesprop.Value.ToString();
                InputValues.Properties = properties;
            }

            int startRow = -1;
            var startRowProp = inputs.Where(p => p.Name.Equals("startrow", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (startRowProp != null && startRowProp.Value != null && !string.IsNullOrWhiteSpace(startRowProp.Value.ToString()))
            {
                if (int.TryParse(startRowProp.Value.ToString(), out startRow) && startRow > -1)
                {
                    InputValues.StartRow = startRow;
                }
            }

            int rowLimit = -1;
            var rowLimitProp = inputs.Where(p => p.Name.Equals("rowlimit", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (rowLimitProp != null && rowLimitProp.Value != null && !string.IsNullOrWhiteSpace(rowLimitProp.Value.ToString()))
            {
                if (int.TryParse(rowLimitProp.Value.ToString(), out rowLimit) && rowLimit > 0)
                {
                    InputValues.RowLimit = rowLimit;
                }
            }

            Guid sourceid = Guid.Empty;
            var sourceidProp = inputs.Where(p => p.Name.Equals("sourceid", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (sourceidProp != null && sourceidProp.Value != null && !string.IsNullOrWhiteSpace(sourceidProp.Value.ToString()))
            {
                if (Guid.TryParse(sourceidProp.Value.ToString(), out sourceid))
                {
                    InputValues.SourceId = sourceid;
                }
            }

            bool enablenicknames = false;
            var enablenicknamesProp = inputs.Where(p => p.Name.Equals("enablenicknames", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (enablenicknamesProp != null && enablenicknamesProp.Value != null && !string.IsNullOrWhiteSpace(enablenicknamesProp.Value.ToString()))
            {
                if (bool.TryParse(enablenicknamesProp.Value.ToString(), out enablenicknames))
                {
                    InputValues.EnableNicknames = enablenicknames;
                }
            }

            bool enablephonetic = false;
            var enablephoneticProp = inputs.Where(p => p.Name.Equals("enablephonetic", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (enablephoneticProp != null && enablephoneticProp.Value != null && !string.IsNullOrWhiteSpace(enablephoneticProp.Value.ToString()))
            {
                if (bool.TryParse(enablephoneticProp.Value.ToString(), out enablephonetic))
                {
                    InputValues.EnablePhonetic = enablephonetic;
                }
            }


            string fileext = string.Empty;
            var fileextprop = inputs.Where(p => p.Name.Equals("fileextensionsfilter", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (fileextprop != null && fileextprop.Value != null && !string.IsNullOrWhiteSpace(fileextprop.Value.ToString()))
            {
                InputValues.FileExtensions = new List<string>();
                fileext = fileextprop.Value.ToString();
                string[] sortsArray = fileext.Split(',');

                foreach (string fx in sortsArray)
                {
                    InputValues.FileExtensions.Add(fx.Trim());
                }

                string filter = string.Empty;
                for (int i = 0; i < InputValues.FileExtensions.Count; i++)
                {
                    filter += "\"" + InputValues.FileExtensions[i] + "\"";
                    if (i <= InputValues.FileExtensions.Count - 2)
                    {
                        filter += ",";
                    }
                }
                InputValues.FileExtensionsString = filter;
            }


            string sorts = string.Empty;
            Dictionary<string, string> sort = new Dictionary<string, string>();
            var sortProp = inputs.Where(p => p.Name.Equals("sort", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (sortProp != null && sortProp.Value != null && !string.IsNullOrWhiteSpace(sortProp.Value.ToString()))
            {
                sorts = sortProp.Value.ToString();
                string[] sortsArray = sorts.Split(',');
                foreach (string s in sortsArray)
                {
                    string[] ss = s.Split(':');
                    string prop = string.Empty;
                    string direction = string.Empty;
                    if (ss.Length > 1)
                    {
                        // JJK: can we check if the supplied property exists?
                        prop = ss[0].Trim();
                        string dir = ss[1].Trim();
                        switch (dir.ToLower())
                        {
                            case "descending":
                            case "desc":
                            case "des":
                                direction = "descending";
                                break;
                            case "ascending":
                            case "asc":
                                direction = "ascending";
                                break;
                            default:
                                direction = "ascending";
                                break;
                        }

                        if (!string.IsNullOrWhiteSpace(prop))
                        {
                            sort.Add(prop, direction);
                        }
                    }
                }
                //returns.Where(p => p.Name.Equals("sort", StringComparison.OrdinalIgnoreCase)).First().Value = sorts;
            }

            if (sort.Count > 0)
            {
                string sortstring = string.Empty;
                InputValues.Sort = sort;

                int o = 0;
                foreach (KeyValuePair<string, string> s in sort)
                {
                    InputValues.SortString += s.Key + ":" + s.Value;
                    if (o <= sort.Count - 2)
                    {
                        InputValues.SortString += ",";
                    }
                    o++;
                }
            }

            bool enablestemming = false;
            var enablestemmingprop = inputs.Where(p => p.Name.Equals("enablestemming", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (enablestemmingprop != null && enablestemmingprop.Value != null && !string.IsNullOrWhiteSpace(enablestemmingprop.Value.ToString()))
            {
                if (bool.TryParse(enablestemmingprop.Value.ToString(), out enablestemming))
                {
                    InputValues.EnableStemming = enablestemming;
                }
            }

            bool trimduplicates = false;
            var trimduplicatesprop = inputs.Where(p => p.Name.Equals("trimduplicates", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (trimduplicatesprop != null && trimduplicatesprop.Value != null && !string.IsNullOrWhiteSpace(trimduplicatesprop.Value.ToString()))
            {
                if (bool.TryParse(trimduplicatesprop.Value.ToString(), out trimduplicates))
                {
                    InputValues.TrimDuplicates = trimduplicates;
                }
            }

            bool enablequeryrules = false;
            var enablequeryrulesprop = inputs.Where(p => p.Name.Equals("enablequeryrules", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (enablequeryrulesprop != null && enablequeryrulesprop.Value != null && !string.IsNullOrWhiteSpace(enablequeryrulesprop.Value.ToString()))
            {
                if (bool.TryParse(enablequeryrulesprop.Value.ToString(), out enablequeryrules))
                {
                    InputValues.EnableQueryRules = enablequeryrules;
                }
            }

            bool processbestbets = false;
            var processbestbetsprop = inputs.Where(p => p.Name.Equals("processbestbets", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (processbestbetsprop != null && processbestbetsprop.Value != null && !string.IsNullOrWhiteSpace(processbestbetsprop.Value.ToString()))
            {
                if (bool.TryParse(processbestbetsprop.Value.ToString(), out processbestbets))
                {
                    InputValues.ProcessBestBets = processbestbets;
                }
            }

            bool processpersonal = false;
            var processpersonalprop = inputs.Where(p => p.Name.Equals("processpersonal", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (processpersonalprop != null && processpersonalprop.Value != null && !string.IsNullOrWhiteSpace(processpersonalprop.Value.ToString()))
            {
                if (bool.TryParse(processpersonalprop.Value.ToString(), out processpersonal))
                {
                    InputValues.ProcessPersonal = processpersonal;
                }
            }

            return InputValues;
        }
        public static RESTSearchResultsSerialized ExecuteSharePointSearchRaw(Property[] inputs, RequiredProperties required, Configuration Configuration, ServiceAssemblyBase serviceBroker)
        {
            // Raw search = append input to end of querytext
            SearchInputs SearchInputs = new SearchInputs();
            string search = string.Empty;
            var searchProp = inputs.Where(p => p.Name.Equals("search", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            if (searchProp != null && searchProp.Value != null && !string.IsNullOrWhiteSpace(searchProp.Value.ToString()))
            {
                search = searchProp.Value.ToString();
                SearchInputs.Search = search;
            }
            else
            {
                throw new Exception("Search is a required property");
            }

            string RequestUri = Configuration.SiteUrl + "/_api/search/query?querytext=" + search;

            return ProcessResults(ExecuteRESTRequest(RequestUri, serviceBroker), SearchInputs);
        }
        public void GetAttachment(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();
            
            Helper h = new Helper(serviceBroker);

            string mailbox = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            string uid = string.Empty;
            string subjectfilter = string.Empty;
            int index = -1;
            uid = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();
            index = int.Parse(inputs.Where(p => p.Name.Equals("attachmentindex")).FirstOrDefault().Value.ToString());

            AE.Net.Mail.MailMessage m = null;
            List<AE.Net.Mail.Attachment> attachments = new List<AE.Net.Mail.Attachment>();

            try
            {
                using (var ic = h.GetImapClient())
                {
                    m = ic.GetMessage(uid, false);

                    if (m == null)
                    {
                        return;
                    }

                    attachments = m.Attachments as List<AE.Net.Mail.Attachment>;

                    AE.Net.Mail.Attachment a = null;

                    if (index == -1 || index > attachments.Count)
                    {
                        return;
                    }
                    a = attachments[index];

                    if (a == null)
                    {
                        return;
                    }

                    returns.Where(p => p.Name.ToLower().Equals("body")).FirstOrDefault().Value = a.Body;
                    returns.Where(p => p.Name.ToLower().Equals("charset")).FirstOrDefault().Value = a.Charset;
                    returns.Where(p => p.Name.ToLower().Equals("contenttransferencoding")).FirstOrDefault().Value = a.ContentTransferEncoding;
                    returns.Where(p => p.Name.ToLower().Equals("contenttype")).FirstOrDefault().Value = a.ContentType;
                    returns.Where(p => p.Name.ToLower().Equals("filename")).FirstOrDefault().Value = a.Filename;
                    returns.Where(p => p.Name.ToLower().Equals("rawheaders")).FirstOrDefault().Value = a.RawHeaders;
                    returns.Where(p => p.Name.ToLower().Equals("onserver")).FirstOrDefault().Value = a.OnServer;
                    returns.Where(p => p.Name.ToLower().Equals("mailbox")).FirstOrDefault().Value = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
                    returns.Where(p => p.Name.ToLower().Equals("uid")).FirstOrDefault().Value = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();;
                    returns.Where(p => p.Name.ToLower().Equals("attachmentindex")).FirstOrDefault().Value = inputs.Where(p => p.Name.Equals("attachmentindex")).FirstOrDefault().Value.ToString();;

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            serviceObject.Properties.BindPropertiesToResultTable();

        }
        public void ExecuteCreateTask(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            Functions.CRMFunctions CRMFunctions = new Functions.CRMFunctions(Utilities.FunctionsUtils.GetCRMConfig(serviceBroker.Service.ServiceConfiguration));

            Functions.CRMTask CRMTaskInput = new Functions.CRMTask();
            Functions.CRMTask CRMTaskResult = null;

            try
            {

                PropertyInfo[] PropInfoCRMTask = CRMTaskResult.GetType().GetProperties(BindingFlags.Public);

                foreach (Property prop in inputs)
                {
                    if (prop.Value != null)
                    {
                        //PropertyInfo RefProp = PropInfoCRMTask.Where(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)).First();
                        PropertyInfo RefProp = PropInfoCRMTask.GetType().GetProperty(prop.Name);
                        if (RefProp != null)
                        {
                            //prop.Value = Utilities.ReflectionUtils.GetPropValue(CRMTaskResult, RefProp.Name);
                            Utilities.ReflectionUtils.SetPropValue<Functions.CRMTask>(CRMTaskInput, prop.Name, prop.Value);

                        }
                    }
                }


                //required
                //CRMTaskInput.Category = inputs.Where(p => p.Name.Equals("category", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                //CRMTaskInput.Description = inputs.Where(p => p.Name.Equals("description", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                ////required
                //CRMTaskInput.DueDate = DateTime.Parse(inputs.Where(p => p.Name.Equals("duedate", StringComparison.OrdinalIgnoreCase)).First().Value.ToString());

                ////required
                //CRMTaskInput.Duration = int.Parse(inputs.Where(p => p.Name.Equals("duration", StringComparison.OrdinalIgnoreCase)).First().Value.ToString());
                
                //CRMTaskInput.OwnerFQN = inputs.Where(p => p.Name.Equals("ownerfqn", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                //CRMTaskInput.Owner = inputs.Where(p => p.Name.Equals("owner", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                //CRMTaskInput.OwnerId = inputs.Where(p => p.Name.Equals("ownerid", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                ////required
                //CRMTaskInput.Priority = int.Parse(inputs.Where(p => p.Name.Equals("priority", StringComparison.OrdinalIgnoreCase)).First().Value.ToString());
                
                //CRMTaskInput.Regarding = inputs.Where(p => p.Name.Equals("regarding", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                //CRMTaskInput.RegardingId = inputs.Where(p => p.Name.Equals("regardingid", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                ////required
                //CRMTaskInput.State = int.Parse(inputs.Where(p => p.Name.Equals("state", StringComparison.OrdinalIgnoreCase)).First().Value.ToString());
                
                ////required
                //CRMTaskInput.Status = int.Parse(inputs.Where(p => p.Name.Equals("status", StringComparison.OrdinalIgnoreCase)).First().Value.ToString());
                
                ////required
                //CRMTaskInput.Subcategory = inputs.Where(p => p.Name.Equals("subcategory", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                ////required
                //CRMTaskInput.Subject = inputs.Where(p => p.Name.Equals("subject", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                
                //CRMTaskInput.K2SerialNumber = inputs.Where(p => p.Name.Equals("k2serialnumber", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                //CRMTaskInput.K2ProcessName = inputs.Where(p => p.Name.Equals("k2processname", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();
                //CRMTaskInput.K2ActivityName = inputs.Where(p => p.Name.Equals("k2activityname", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();

                //int procInstId;
                //if (int.TryParse(inputs.Where(p => p.Name.Equals("k2processinstanceid", StringComparison.OrdinalIgnoreCase)).First().Value.ToString(), out procInstId))
                //{
                //    CRMTaskInput.K2ProcessInstanceId = procInstId;
                //}
                
                CRMTaskResult = CRMFunctions.CRMCreateTask(CRMTaskInput);

                //List<string> OProps = new List<string>();
                //OProps.Where(p => p == "").First();

                if (CRMTaskResult != null)
                {

                    //foreach(PropertyInfo prop in CRMTaskResult.GetType().GetProperties(BindingFlags.Public))
                    foreach(Property prop in returns)
                    {
                        //PropertyInfo RefProp = PropInfoCRMTask.Where(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)).First();
                        PropertyInfo RefProp = PropInfoCRMTask.GetType().GetProperty(prop.Name);
                        if( RefProp != null)
                        {
                            prop.Value = Utilities.ReflectionUtils.GetPropValue(CRMTaskResult, RefProp.Name);
                        }

                        //PropertyInfo aa = PropInfoCRMTask.Where(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)).First();


                        //if (returns.Where(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)).First() != null)
                        //{
                        //    returns.Where(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)).First().Value = Utilities.ReflectionUtils.GetPropValue(CRMTaskResult, prop.Name);
                        //}

                    }
                    returns.Where(p => p.Name.Equals("responsestatus")).First().Value = ResponseStatus.Success;
                }
                else
                {
                    throw new Exception("CRMTaskResult is null.");
                }

            }
            catch (Exception ex)
            {
                returns.Where(p => p.Name.Equals("responsestatus")).First().Value = ResponseStatus.Error;
                returns.Where(p => p.Name.Equals("responsestatusdescription")).First().Value = ex.Message;
            }

            serviceObject.Properties.BindPropertiesToResultTable();
        }
        public void ExecuteSearch(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();
            System.Data.DataRow dr;
            try
            {
                RESTSearchResultsSerialized SerializedResults = null;

                // if deserializesearchresults
                if (serviceObject.Methods[0].Name.StartsWith("deserialize"))
                {
                    Property SerializedProp = inputs.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First();
                    string json = string.Empty;
                    json = SerializedProp.Value.ToString();

                    SerializedResults = JsonConvert.DeserializeObject<RESTSearchResultsSerialized>(json.Trim());

                    if (string.IsNullOrWhiteSpace(json) || SerializedResults == null)
                    {
                        throw new Exception("Failed to deserialize search results");
                    }
                }

                if (serviceObject.Methods[0].Name.Equals("spsearch") || serviceObject.Methods[0].Name.Equals("spsearchdocuments"))
                {
                    // if Search
                    SerializedResults = Utilities.BrokerUtils.ExecuteSharePointSearch(inputs, required, Configuration, serviceBroker);
                }

                if (serviceObject.Methods[0].Name.Equals("spsearchraw"))
                {
                    // if Search Raw Read
                    SerializedResults = Utilities.BrokerUtils.ExecuteSharePointSearchRaw(inputs, required, Configuration, serviceBroker);
                }


                if (serviceObject.Methods[0].Name.Equals("spsearchusers"))
                {
                    // if Search
                    SerializedResults = Utilities.BrokerUtils.ExecuteSharePointUserSearch(inputs, required, Configuration, serviceBroker);
                }


                if (SerializedResults != null)
                {
                    if (SerializedResults.SearchResults == null || SerializedResults.SearchResults.Rows == null)
                    {
                        SerializedResults.SearchResults = new ResultTable();

                        //SerializedResults.SearchResults.Rows.Add(new ResultRow());
                    }
                    
                    foreach (ResultRow result in SerializedResults.SearchResults.Rows)
                    {
                        dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.Search))
                        {
                            dr["search"] = SerializedResults.Inputs.Search;
                        }

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.SiteUrl))
                        {
                            dr["searchsiteurl"] = SerializedResults.Inputs.Search;
                        }

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.FileExtensionsString))
                        {
                            dr["fileextensionsfilter"] = SerializedResults.Inputs.FileExtensionsString;
                        }

                        if (SerializedResults.Inputs.SourceId != null && SerializedResults.Inputs.SourceId != Guid.Empty)
                        {
                            dr["sourceid"] = SerializedResults.Inputs.SourceId;
                        }

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.SortString))
                        {
                            dr["sort"] = SerializedResults.Inputs.SortString;
                        }

                        if (SerializedResults.Inputs.StartRow.HasValue && SerializedResults.Inputs.StartRow.Value > -1)
                        {
                            dr["startrow"] = SerializedResults.Inputs.StartRow.Value;
                        }

                        if (SerializedResults.Inputs.RowLimit.HasValue && SerializedResults.Inputs.RowLimit.Value > 0)
                        {
                            dr["rowlimit"] = SerializedResults.Inputs.RowLimit.Value;
                        }

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.Properties))
                        {
                            dr["properties"] = SerializedResults.Inputs.Properties;
                        }

                        if (SerializedResults.Inputs.EnableStemming.HasValue && SerializedResults.Inputs.EnableStemming.Value)
                        {
                            dr["enablestemming"] = SerializedResults.Inputs.EnableStemming.Value;
                        }

                        if (SerializedResults.Inputs.TrimDuplicates.HasValue && SerializedResults.Inputs.TrimDuplicates.Value)
                        {
                            dr["trimduplicates"] = SerializedResults.Inputs.TrimDuplicates.Value;
                        }

                        if (SerializedResults.Inputs.EnableQueryRules.HasValue && SerializedResults.Inputs.EnableQueryRules.Value)
                        {
                            dr["enablequeryrules"] = SerializedResults.Inputs.EnableQueryRules.Value;
                        }

                        if (SerializedResults.Inputs.ProcessBestBets.HasValue && SerializedResults.Inputs.ProcessBestBets.Value)
                        {
                            dr["processbestbets"] = SerializedResults.Inputs.ProcessBestBets.Value;
                        }

                        if (SerializedResults.Inputs.ProcessPersonal.HasValue && SerializedResults.Inputs.ProcessPersonal.Value)
                        {
                            dr["processpersonal"] = SerializedResults.Inputs.ProcessPersonal.Value;
                        }

                        if (SerializedResults.Inputs.EnableNicknames.HasValue && SerializedResults.Inputs.EnableNicknames.Value)
                        {
                            dr["enablenicknames"] = SerializedResults.Inputs.EnableNicknames.Value;
                        }

                        if (SerializedResults.Inputs.EnablePhonetic.HasValue && SerializedResults.Inputs.EnablePhonetic.Value)
                        {
                            dr["enablephonetic"] = SerializedResults.Inputs.EnablePhonetic.Value;
                        }

                        if (SerializedResults.ExecutionTime.HasValue)
                        {
                            dr["executiontime"] = SerializedResults.ExecutionTime.Value;
                        }

                        if (SerializedResults.ResultRows.HasValue)
                        {
                            dr["resultrows"] = SerializedResults.ResultRows.Value;
                        }
                        if (SerializedResults.TotalRows.HasValue)
                        {
                            dr["totalrows"] = SerializedResults.TotalRows.Value;
                        }

                        List<string> missingprops = new List<string>();
                        foreach (ResultCell cell in result.Cells)
                        {
                            if (dr.Table.Columns.Contains(cell.Key.ToLower()))
                            {
                                if (cell.Value != null)
                                {
                                    dr[cell.Key.ToLower()] = cell.Value;
                                }
                            }
                            else
                            {
                                missingprops.Add(cell.Key);
                            }
                        }

                        dr["responsestatus"] = ResponseStatus.Success;
                        serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                    }
                }
                else
                {
                    throw new Exception("No results returned.");
                }

            }
            catch (Exception ex)
            {
                dr = serviceBroker.ServicePackage.ResultTable.NewRow();
                dr["responsestatus"] = ResponseStatus.Error;
                dr["responsestatusdescription"] = ex.Message;
                serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
            }

            //serviceObject.Properties.BindPropertiesToResultTable();
        }
        public void GetAllAttachments(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            System.Data.DataRow dr;
            Helper h = new Helper(serviceBroker);

            string mailbox = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            string uid = string.Empty;
            string subjectfilter = string.Empty;

            uid = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();

            AE.Net.Mail.MailMessage m = null;
            List<AE.Net.Mail.Attachment> attachments = new List<AE.Net.Mail.Attachment>();

            try
            {
                using (var ic = h.GetImapClient())
                {
                    m = ic.GetMessage(uid, false);

                    if (m == null)
                    {
                        return;
                    }

                    attachments = m.Attachments as List<AE.Net.Mail.Attachment>;

                    foreach (Attachment a in attachments)
                    {
                        dr = serviceBroker.ServicePackage.ResultTable.NewRow();
                        
                        dr["body"] = a.Body;
                        dr["charset"] = a.Charset;
                        dr["contenttransferencoding"] = a.ContentTransferEncoding;
                        dr["contenttype"] = a.ContentType;
                        dr["filename"] = a.Filename;
                        dr["rawheaders"] = a.RawHeaders;
                        dr["onserver"] = a.OnServer;

                        dr["mailbox"] = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
                        dr["uid"] = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();

                        serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                    }

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            
        }
        /// <summary>
        /// Executes the Service Object method and returns any data.
        /// </summary>
        /// <param name="inputs">A Property[] array containing all the allowed input properties.</param>
        /// <param name="required">A RequiredProperties collection containing the required properties.</param>
        /// <param name="returns">A Property[] array containing all the allowed return properties.</param>
        /// <param name="methodType">A MethoType indicating what type of Service Object method was called.</param>
        /// <param name="serviceObject">A ServiceObject containing populated properties for use with the method call.</param>
        public void Execute(Property[] inputs, RequiredProperties required, Property[] returns, SourceCode.SmartObjects.Services.ServiceSDK.Types.MethodType methodType, ServiceObject serviceObject)
        {
            #region Get All Field Values

            if (serviceObject.Methods[0].Name.Equals("getallfieldvalues"))
            {
                serviceObject.Properties.InitResultTable();

                // get input field value
                string pdfuri = inputs.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value.ToString();

                PDFInfo info = new PDFInfo();
                Dictionary<string, PDFField> fields = new Dictionary<string, PDFField>();

                try
                {
                    using (PdfReader doc = new PdfReader(pdfUri))
                    {
                        // discover pdf doc
                        info = GetPDFDoucmentInformation(doc);
                        fields = GetPDFFormFields(doc, true);
                    }
                }
                catch(Exception ex)
                {
                    throw new Exception(string.Format("Error retrieving PDF document from {0}. Exception: {1}", pdfuri, ex.Message));
                }

                returns.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value = pdfuri;

                foreach(Property prop in returns)
                {
                    PDFField fieldvalue = new PDFField();

                    string fullname = string.Empty;

                    object pfn = prop.MetaData.ServiceProperties["pdffullname"];
                    if (pfn == null)
                    {
                        fullname = prop.Name;
                    }
                    else
                    {
                        fullname = pfn.ToString();
                    }

                    if (fields.TryGetValue(fullname, out fieldvalue))
                    {
                        prop.Value = fieldvalue.FieldValue;
                    }
                }

                Type type = typeof(PDFInfo);
                PropertyInfo[] props = type.GetProperties();
                foreach (var p in props)
                {
                    object v = info.GetType().GetProperty(p.Name).GetValue(info, null);
                    if (v != null)
                    {
                        string value = v.ToString();
                        returns.Where(q => q.Name.Equals(p.Name)).First().Value = value;
                    }
                }

                serviceObject.Properties.BindPropertiesToResultTable();

            }

            #endregion Get All Field Values

            #region Contains Signatures

            if (serviceObject.Methods[0].Name.Equals("containssignatures"))
            {
                serviceObject.Properties.InitResultTable();

                // get input field value
                string pdfuri = inputs.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value.ToString();

                PDFInfo info = new PDFInfo();
                Dictionary<string, PDFField> fields = new Dictionary<string, PDFField>();

                bool containssigs = false;

                try
                {
                    using (PdfReader doc = new PdfReader(pdfUri))
                    {
                        fields = GetPDFFormFields(doc, true);
                        containssigs = ContainsSignatures(fields);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error retrieving PDF document from {0}. Exception: {1}", pdfuri, ex.Message));
                }

                returns.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value = pdfuri;
                returns.Where(p => p.Name.Equals("containssignatures")).FirstOrDefault().Value = containssigs;

                serviceObject.Properties.BindPropertiesToResultTable();

            }

            #endregion Contains Signatures

            #region Contains Unsigned Signatures

            if (serviceObject.Methods[0].Name.Equals("containsunsignedsignatures"))
            {
                serviceObject.Properties.InitResultTable();

                // get input field value
                string pdfuri = inputs.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value.ToString();

                PDFInfo info = new PDFInfo();
                Dictionary<string, PDFField> fields = new Dictionary<string, PDFField>();

                bool containsunsignedsigs = false;

                try
                {
                    using (PdfReader doc = new PdfReader(pdfUri))
                    {
                        containsunsignedsigs = ContainsBlankSignatures(doc);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error retrieving PDF document from {0}. Exception: {1}", pdfuri, ex.Message));
                }

                returns.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value = pdfuri;
                returns.Where(p => p.Name.Equals("containsunsignedsignatures")).FirstOrDefault().Value = containsunsignedsigs;

                serviceObject.Properties.BindPropertiesToResultTable();

            }

            #endregion Contains Signatures

            #region Update PDF Field

            if (serviceObject.Methods[0].Name.Equals("updatepdffields"))
            {
                serviceObject.Properties.InitResultTable();

                // get input field value
                string pdfuri = inputs.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value.ToString();
                bool base64 = false;
                string base64temp = inputs.Where(p => p.Name.Equals("returnbase64")).FirstOrDefault().Value.ToString();
                bool.TryParse(base64temp, out base64);

                string workingFolder = serviceBroker.Service.ServiceConfiguration["WorkingFolder"].ToString();
                if (workingFolder.LastIndexOf(@"\") != workingFolder.Length - 1)
                {
                    workingFolder += @"\";
                }
                string filename = Guid.NewGuid().ToString()+".pdf";
                string workingPath = workingFolder + filename;

                PDFInfo info = new PDFInfo();
                Dictionary<string, PDFField> fields = new Dictionary<string, PDFField>();

                Dictionary<string, string> updates = new Dictionary<string, string>();
                foreach (Property prop in inputs)
                {
                    object pfn = prop.MetaData.ServiceProperties["pdffullname"];
                    if (!prop.Name.Equals("pdfuri") && pfn != null)
                    {
                        if (prop.Value != null)
                        {
                            updates.Add(pfn.ToString(), prop.Value.ToString());
                        }
                    }
                }

                if (updates.Count > 0)
                {
                    // call update method
                    using (PdfReader doc = new PdfReader(pdfuri))
                    {
                        // last parameter ensures that extended document properties are retained

                        using (PdfStamper pdfStamper = new PdfStamper(doc, new FileStream(workingPath, FileMode.Create), '\0', true))
                        {
                            AcroFields pdfFormFields = pdfStamper.AcroFields;
                            foreach (KeyValuePair<string, string> val in updates)
                            {
                                pdfFormFields.SetField(val.Key, val.Value);
                            }
                            pdfStamper.FormFlattening = false;
                            pdfStamper.Close();
                        }
                    }
                }

                returns.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value = pdfuri;
                returns.Where(p => p.Name.Equals("returnpath")).FirstOrDefault().Value = workingPath;
                returns.Where(p => p.Name.Equals("returnbase64")).FirstOrDefault().Value = base64;

                // read created doc
                try
                {
                    using (PdfReader doc = new PdfReader(workingPath))
                    {
                        // discover pdf doc
                        info = GetPDFDoucmentInformation(doc);
                        fields = GetPDFFormFields(doc, true);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error retrieving PDF document from {0}. Exception: {1}", workingPath, ex.Message));
                }

                foreach (Property prop in returns)
                {
                    PDFField fieldvalue = new PDFField();

                    string fullname = string.Empty;

                    object pfn = prop.MetaData.ServiceProperties["pdffullname"];
                    if (pfn == null)
                    {
                        fullname = prop.Name;
                    }
                    else
                    {
                        fullname = pfn.ToString();
                    }

                    if (fields.TryGetValue(fullname, out fieldvalue))
                    {
                        prop.Value = fieldvalue.FieldValue;
                    }
                }

                Type type = typeof(PDFInfo);
                PropertyInfo[] props = type.GetProperties();
                foreach (var p in props)
                {
                    object v = info.GetType().GetProperty(p.Name).GetValue(info, null);
                    if (v != null)
                    {
                        string value = v.ToString();
                        returns.Where(q => q.Name.Equals(p.Name)).First().Value = value;
                    }
                }

                // get base64 of file
                if (base64)
                {
                    FileStream fs = new FileStream(workingPath, FileMode.Open, FileAccess.Read);
                    byte[] filebytes = new byte[fs.Length];
                    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
                    string encodedData = Convert.ToBase64String(filebytes);
                    returns.Where(p => p.Name.Equals("base64pdf")).FirstOrDefault().Value = encodedData;
                }

                serviceObject.Properties.BindPropertiesToResultTable();
                return;
            }

            #endregion Update PDF Field

            #region Generate Create Table SQL

            if (serviceObject.Methods[0].Name.Equals("generatecreatetablesql"))
            {
                serviceObject.Properties.InitResultTable();

                string pdfuri = serviceBroker.Service.ServiceConfiguration["pdfUri"].ToString();

                PDFInfo info = new PDFInfo();
                Dictionary<string, PDFField> fields = new Dictionary<string, PDFField>();

                string sql = string.Empty;

                try
                {
                    using (PdfReader doc = new PdfReader(pdfUri))
                    {
                        info = GetPDFDoucmentInformation(doc);
                        fields = GetPDFFormFields(doc, false);
                        sql = GenerateCreateTableSQL(info, fields);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error generating create table SQL from {0}. Exception: {1}", pdfuri, ex.Message));
                }

                returns.Where(p => p.Name.Equals("generatedsql")).FirstOrDefault().Value = sql;

                serviceObject.Properties.BindPropertiesToResultTable();

            }

            #endregion Generate Create Table SQL

            #region Copy Form Data to SmartObject

            if (serviceObject.Methods[0].Name.Equals("copyformdatatosmartobject"))
            {
                serviceObject.Properties.InitResultTable();

                string pdfuri = inputs.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value.ToString();
                string smoname = inputs.Where(p => p.Name.Equals("formstoresmartobjectname")).FirstOrDefault().Value.ToString();
                string smometh = inputs.Where(p => p.Name.Equals("formstoremethodname")).FirstOrDefault().Value.ToString();
                string returnprop = inputs.Where(p => p.Name.Equals("returnidpropertyname")).FirstOrDefault().Value.ToString();

                string returnvalue = string.Empty;

                PDFInfo info = new PDFInfo();
                Dictionary<string, PDFField> fields = new Dictionary<string, PDFField>();

                try
                {
                    using (PdfReader doc = new PdfReader(pdfUri))
                    {
                        info = GetPDFDoucmentInformation(doc);
                        fields = GetPDFFormFields(doc, true);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error retrieving PDF document from {0}. Exception: {1}", pdfuri, ex.Message));
                }

                string returnId = string.Empty;
                try
                {
                    returnId = Utilities.SmartObjectUtils.CreateDataFromPDFForm(smoname, smometh, returnprop, info, fields);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error updated SmartObject from PDF document from {0}. Exception: {1}", pdfuri, ex.Message));
                }

                returns.Where(p => p.Name.Equals("pdfuri")).FirstOrDefault().Value = pdfuri;
                returns.Where(p => p.Name.Equals("formstoresmartobjectname")).FirstOrDefault().Value = smoname;
                returns.Where(p => p.Name.Equals("formstoremethodname")).FirstOrDefault().Value = smometh;
                returns.Where(p => p.Name.Equals("returnidpropertyname")).FirstOrDefault().Value = returnprop;
                returns.Where(p => p.Name.Equals("returnid")).FirstOrDefault().Value = returnId;

                serviceObject.Properties.BindPropertiesToResultTable();

            }

            #endregion Copy Form Data to SmartObject
        }
        public void ExecuteSearchRead(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            try
            {
                RESTSearchResultsSerialized SerializedResults = new RESTSearchResultsSerialized();


                if (serviceObject.Methods[0].Name.Equals("spsearchread") || serviceObject.Methods[0].Name.Equals("spsearchdocumentsread"))
                {
                    SerializedResults = Utilities.BrokerUtils.ExecuteSharePointSearch(inputs, required, Configuration, serviceBroker);
                }

                if (serviceObject.Methods[0].Name.Equals("spsearchrawread"))
                {
                    SerializedResults = Utilities.BrokerUtils.ExecuteSharePointSearchRaw(inputs, required, Configuration, serviceBroker);
                }

                if (serviceObject.Methods[0].Name.Equals("spsearchusersread"))
                {
                    SerializedResults = Utilities.BrokerUtils.ExecuteSharePointUserSearch(inputs, required, Configuration, serviceBroker);
                }


                if (SerializedResults != null)
                {
                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.Search))
                    {
                        returns.Where(p => p.Name.Equals("search", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.Search;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.SiteUrl))
                    {
                        returns.Where(p => p.Name.Equals("searchsiteurl", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.SiteUrl;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.FileExtensionsString))
                    {
                        returns.Where(p => p.Name.Equals("fileextensionsfilter", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.FileExtensionsString;
                    }

                    if (SerializedResults.Inputs.SourceId != null && SerializedResults.Inputs.SourceId != Guid.Empty)
                    {
                        returns.Where(p => p.Name.Equals("sourceid", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.SourceId;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.SortString))
                    {
                        returns.Where(p => p.Name.Equals("sort", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.SortString;
                    }

                    if (SerializedResults.Inputs.StartRow.HasValue && SerializedResults.Inputs.StartRow.Value > -1)
                    {
                        returns.Where(p => p.Name.Equals("startrow", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.StartRow.Value;
                    }

                    if (SerializedResults.Inputs.RowLimit.HasValue && SerializedResults.Inputs.RowLimit.Value > 0)
                    {
                        returns.Where(p => p.Name.Equals("rowlimit", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.RowLimit.Value;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.Properties))
                    {
                        returns.Where(p => p.Name.Equals("properties", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.Properties;
                    }

                    if (SerializedResults.Inputs.EnableStemming.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("enablestemming", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.EnableStemming.Value;
                    }

                    if (SerializedResults.Inputs.TrimDuplicates.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("trimduplicates", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.TrimDuplicates.Value;
                    }

                    if (SerializedResults.Inputs.EnableQueryRules.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("enablequeryrules", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.EnableQueryRules.Value;
                    }

                    if (SerializedResults.Inputs.ProcessBestBets.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("processbestbets", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.ProcessBestBets.Value;
                    }

                    if (SerializedResults.Inputs.ProcessPersonal.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("processpersonal", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.ProcessPersonal.Value;
                    }

                    if (SerializedResults.Inputs.EnableNicknames.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("enablenicknames", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.EnableNicknames.Value;
                    }

                    if (SerializedResults.Inputs.EnablePhonetic.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("enablephonetic", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.EnablePhonetic.Value;
                    }

                    if (SerializedResults.ExecutionTime.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("executiontime", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.ExecutionTime.Value;
                    }

                    if (SerializedResults.ResultRows.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("resultrows", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.ResultRows.Value;
                    }

                    if (SerializedResults.TotalRows.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("totalrows", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.TotalRows.Value;
                    }

                    string resultsJson = JsonConvert.SerializeObject(SerializedResults);

                    returns.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First().Value = resultsJson;

                    returns.Where(p => p.Name.Equals("responsestatus", StringComparison.OrdinalIgnoreCase)).First().Value = ResponseStatus.Success;
                }
                else
                {
                    throw new Exception("No results returned.");
                }
            }
            catch (Exception ex)
            {
                returns.Where(p => p.Name.Equals("responsestatus", StringComparison.OrdinalIgnoreCase)).First().Value = ResponseStatus.Error;
                returns.Where(p => p.Name.Equals("responsestatusdescription", StringComparison.OrdinalIgnoreCase)).First().Value = ex.Message;
            }
            serviceObject.Properties.BindPropertiesToResultTable();
        }
        public SearchInputs GetInputs(Property[] inputs)
        {
            SearchInputs InputValues = new SearchInputs();

            string search = string.Empty;
            var searchProp = inputs.Where(p => p.Name.Equals("search", StringComparison.OrdinalIgnoreCase)).First();
            if (searchProp != null && searchProp.Value != null && !string.IsNullOrWhiteSpace(searchProp.Value.ToString()))
            {
                search = searchProp.Value.ToString();
                InputValues.Search = search;
            }
            else
            {
                throw new Exception("Search is a required property");
            }

            int startRow = -1;
            var startRowProp = inputs.Where(p => p.Name.Equals("startrow", StringComparison.OrdinalIgnoreCase)).First();
            if (startRowProp != null && startRowProp.Value != null && !string.IsNullOrWhiteSpace(startRowProp.Value.ToString()))
            {
                if (int.TryParse(startRowProp.Value.ToString(), out startRow) && startRow > -1)
                {
                    InputValues.StartRow = startRow;
                }
            }

            int rowLimit = -1;
            var rowLimitProp = inputs.Where(p => p.Name.Equals("rowlimit", StringComparison.OrdinalIgnoreCase)).First();
            if (rowLimitProp != null && rowLimitProp.Value != null && !string.IsNullOrWhiteSpace(rowLimitProp.Value.ToString()))
            {
                if (int.TryParse(rowLimitProp.Value.ToString(), out rowLimit) && rowLimit > 0)
                {
                    InputValues.RowLimit = rowLimit;
                }
            }

            Guid sourceid = Guid.Empty;
            var sourceidProp = inputs.Where(p => p.Name.Equals("sourceid", StringComparison.OrdinalIgnoreCase)).First();
            if (sourceidProp != null && sourceidProp.Value != null && !string.IsNullOrWhiteSpace(sourceidProp.Value.ToString()))
            {
                if (Guid.TryParse(sourceidProp.Value.ToString(), out sourceid))
                {
                    InputValues.SourceId = sourceid;
                }
            }

            bool enablenicknames = false;
            var enablenicknamesProp = inputs.Where(p => p.Name.Equals("enablenicknames", StringComparison.OrdinalIgnoreCase)).First();
            if (enablenicknamesProp != null && enablenicknamesProp.Value != null && !string.IsNullOrWhiteSpace(enablenicknamesProp.Value.ToString()))
            {
                if (bool.TryParse(enablenicknamesProp.Value.ToString(), out enablenicknames))
                {
                    InputValues.EnableNicknames = enablenicknames;
                }
            }

            bool enablephonetic = false;
            var enablephoneticProp = inputs.Where(p => p.Name.Equals("enablephonetic", StringComparison.OrdinalIgnoreCase)).First();
            if (enablephoneticProp != null && enablephoneticProp.Value != null && !string.IsNullOrWhiteSpace(enablephoneticProp.Value.ToString()))
            {
                if (bool.TryParse(enablephoneticProp.Value.ToString(), out enablephonetic))
                {
                    InputValues.EnablePhonetic = enablephonetic;
                }
            }

            string sorts = string.Empty;
            Dictionary<string, SortDirection> sort = new Dictionary<string, SortDirection>();
            var sortProp = inputs.Where(p => p.Name.Equals("sort", StringComparison.OrdinalIgnoreCase)).First();
            if (sortProp != null && sortProp.Value != null && !string.IsNullOrWhiteSpace(sortProp.Value.ToString()))
            {
                sorts = sortProp.Value.ToString();
                string[] sortsArray = sorts.Split(';');
                foreach (string s in sortsArray)
                {
                    string[] ss = s.Split(',');
                    string prop = string.Empty;
                    Microsoft.SharePoint.Client.Search.Query.SortDirection direction;
                    if (ss.Length > 1)
                    {
                        // JJK: can we check if the supplied property exists?
                        prop = ss[0].Trim();
                        string dir = ss[1].Trim();
                        switch (dir.ToLower())
                        {
                            case "descending":
                            case "desc":
                            case "des":
                                direction = SortDirection.Descending;
                                break;
                            case "ascending":
                            case "asc":
                                direction = SortDirection.Ascending;
                                break;
                            default:
                                direction = SortDirection.Ascending;
                                break;
                        }

                        if (!string.IsNullOrWhiteSpace(prop))
                        {
                            sort.Add(prop, direction);
                        }
                    }
                }
                //returns.Where(p => p.Name.Equals("sort", StringComparison.OrdinalIgnoreCase)).First().Value = sorts;
            }
            InputValues.SortString = sorts;
            if (sort.Count > 0)
            {
                //InputValues.Sort = sort;
            }

            return InputValues;
        }
        public void ExecuteGetUser(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            Functions.CRMFunctions CRMFunctions = new Functions.CRMFunctions(Utilities.FunctionsUtils.GetCRMConfig(serviceBroker.Service.ServiceConfiguration));

            Functions.CRMUser CRMUserInput = new Functions.CRMUser();
            Functions.CRMUser CRMUserResult = null;
            
            try
            {
                CRMUserInput.UserFQN = inputs.Where(p => p.Name.Equals("userfqn", StringComparison.OrdinalIgnoreCase)).First().Value.ToString();

                CRMUserResult = CRMFunctions.CRMGetUser(CRMUserInput);

                if (CRMUserResult != null)
                {
                    returns.Where(p => p.Name.Equals("userfqn")).First().Value = CRMUserInput.UserFQN;
                    returns.Where(p => p.Name.Equals("userid")).First().Value = CRMUserResult.UserId;
                    returns.Where(p => p.Name.Equals("responsestatus")).First().Value = ResponseStatus.Success;
                }
                else
                {
                    throw new Exception("CRMUserResult is null.");
                }

            }
            catch (Exception ex)
            {
                returns.Where(p => p.Name.Equals("responsestatus")).First().Value = ResponseStatus.Error;
                returns.Where(p => p.Name.Equals("responsestatusdescription")).First().Value = ex.Message;
            }
                        
            serviceObject.Properties.BindPropertiesToResultTable();
        }
        // deprecated
        public void ExecuteDeserializeSearchResults(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();
            System.Data.DataRow dr;

            string json = string.Empty;

            try
            {
                Property SerializedProp = inputs.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First();
                if (SerializedProp != null && SerializedProp.Value != null)
                {
                    json = SerializedProp.Value.ToString();
                }

                //IEnumerable<IDictionary<string, object>> searchResults = JsonConvert.DeserializeObject<IEnumerable<IDictionary<string, object>>>(json.Trim());

                SearchResultsSerialized SerializedSearch = JsonConvert.DeserializeObject<SearchResultsSerialized>(json.Trim());

                if (string.IsNullOrWhiteSpace(json) || SerializedSearch == null)
                {
                    throw new Exception("Failed to deserialize search results");
                }

                foreach (IDictionary<string, object> result in SerializedSearch.SearchResults)
                {
                    dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                    if (!string.IsNullOrWhiteSpace(SerializedSearch.Inputs.Search))
                    {
                        dr["search"] = SerializedSearch.Inputs.Search;
                    }

                    if (SerializedSearch.Inputs.StartRow.HasValue && SerializedSearch.Inputs.StartRow.Value > -1)
                    {
                        dr["startrow"] = SerializedSearch.Inputs.StartRow.Value;
                    }

                    if (SerializedSearch.Inputs.RowLimit.HasValue && SerializedSearch.Inputs.RowLimit.Value > 0)
                    {
                        dr["rowlimit"] = SerializedSearch.Inputs.RowLimit.Value;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedSearch.Inputs.SortString))
                    {
                        dr["sort"] = SerializedSearch.Inputs.SortString;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedSearch.Inputs.SortString))
                    {
                        dr["sourceid"] = SerializedSearch.Inputs.SourceId;
                    }

                    if (SerializedSearch.ExecutionTime.HasValue)
                    {
                        dr["executiontime"] = SerializedSearch.ExecutionTime;
                    }

                    if (SerializedSearch.ResultRows.HasValue)
                    {
                        dr["resultrows"] = SerializedSearch.ResultRows;
                    }
                    if (SerializedSearch.TotalRows.HasValue)
                    {
                        dr["totalrows"] = SerializedSearch.TotalRows;
                    }
                    dr["resulttitle"] = SerializedSearch.ResultTitle;
                    dr["resulttitleurl"] = SerializedSearch.ResultTitleUrl;
                    dr["tabletype"] = SerializedSearch.TableType;
                    dr["spellingsuggestions"] = SerializedSearch.SpellingSuggestions;

                    foreach (string s in result.Keys)
                    {
                        if (result[s] != null)
                        {
                            dr[s.ToLower()] = result[s];
                        }
                    }
                    dr["responsestatus"] = ResponseStatus.Success;
                    serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
                dr = serviceBroker.ServicePackage.ResultTable.NewRow();
                dr["responsestatus"] = ResponseStatus.Error;
                dr["responsestatusdescription"] = ex.Message;
                serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
            }
            //serviceObject.Properties.BindPropertiesToResultTable();
        }
        public void ExecuteSearchRead(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            try
            {
                //SearchInputs SearchInputs = GetInputs(inputs);
                RESTSearchResultsSerialized SerializedResults = new RESTSearchResultsSerialized();

                SerializedResults = ExecuteSharePointSearch(inputs, required, returns, methodType, serviceObject);

                if (SerializedResults != null)
                {
                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.Search))
                    {
                        returns.Where(p => p.Name.Equals("search", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.Search;
                    }

                    if (SerializedResults.Inputs.StartRow.HasValue && SerializedResults.Inputs.StartRow.Value > -1)
                    {
                        returns.Where(p => p.Name.Equals("startrow", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.StartRow.Value;
                    }

                    if (SerializedResults.Inputs.RowLimit.HasValue && SerializedResults.Inputs.RowLimit.Value > 0)
                    {
                        returns.Where(p => p.Name.Equals("rowlimit", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.RowLimit.Value;
                    }

                    if (SerializedResults.Inputs.SourceId != null && SerializedResults.Inputs.SourceId != Guid.Empty)
                    {
                        returns.Where(p => p.Name.Equals("sourceid", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.SourceId;
                    }

                    if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.SortString))
                    {
                        returns.Where(p => p.Name.Equals("sort", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.SortString;
                    }

                    if (SerializedResults.Inputs.EnableNicknames.HasValue && SerializedResults.Inputs.EnableNicknames.Value)
                    {
                        returns.Where(p => p.Name.Equals("enablenicknames", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.EnableNicknames.Value;
                    }

                    if (SerializedResults.Inputs.EnablePhonetic.HasValue && SerializedResults.Inputs.EnablePhonetic.Value)
                    {
                        returns.Where(p => p.Name.Equals("enablephonetic", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.Inputs.EnablePhonetic.Value;
                    }

                    if (SerializedResults.ExecutionTime.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("executiontime", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.ExecutionTime.Value;
                    }

                    if (SerializedResults.ResultRows.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("resultrows", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.ResultRows.Value;
                    }

                    if (SerializedResults.TotalRows.HasValue)
                    {
                        returns.Where(p => p.Name.Equals("totalrows", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.TotalRows.Value;
                    }

                    returns.Where(p => p.Name.Equals("resulttitle", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.ResultTitle;
                    returns.Where(p => p.Name.Equals("resulttitleurl", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.ResultTitleUrl;
                    returns.Where(p => p.Name.Equals("tabletype", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.TableType;
                    returns.Where(p => p.Name.Equals("spellingsuggestions", StringComparison.OrdinalIgnoreCase)).First().Value = SerializedResults.SpellingSuggestions;

                    //string resultsJson = JsonConvert.SerializeObject(results.Value[0].ResultRows);
                    string resultsJson = JsonConvert.SerializeObject(SerializedResults);

                    returns.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First().Value = resultsJson;

                    returns.Where(p => p.Name.Equals("responsestatus", StringComparison.OrdinalIgnoreCase)).First().Value = ResponseStatus.Success;
                }
                else
                {
                    throw new Exception("No results returned.");
                }
            }
            catch (Exception ex)
            {
                returns.Where(p => p.Name.Equals("responsestatus", StringComparison.OrdinalIgnoreCase)).First().Value = ResponseStatus.Error;
                returns.Where(p => p.Name.Equals("responsestatusdescription", StringComparison.OrdinalIgnoreCase)).First().Value = ex.Message;
            }
            serviceObject.Properties.BindPropertiesToResultTable();
        }
        public void ExecuteSearch(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();
            System.Data.DataRow dr;
            try
            {
                RESTSearchResultsSerialized SerializedResults = null;

                // if deserializesearchresults
                var sps = inputs.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase));
                if (sps.Count() > 0 && inputs.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First() != null && inputs.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First().Value != null)
                {
                    Property SerializedProp = inputs.Where(p => p.Name.Equals("serializedresults", StringComparison.OrdinalIgnoreCase)).First();
                    //if (SerializedProp != null && SerializedProp.Value != null)
                    //{
                    string json = string.Empty;
                    json = SerializedProp.Value.ToString();

                    //IEnumerable<IDictionary<string, object>> searchResults = JsonConvert.DeserializeObject<IEnumerable<IDictionary<string, object>>>(json.Trim());

                    SerializedResults = JsonConvert.DeserializeObject<RESTSearchResultsSerialized>(json.Trim());

                    if (string.IsNullOrWhiteSpace(json) || SerializedResults == null)
                    {
                        throw new Exception("Failed to deserialize search results");
                    }
                    //}
                }
                else
                {
                    // if Search
                    SerializedResults = ExecuteSharePointSearch(inputs, required, returns, methodType, serviceObject);
                }

                if (SerializedResults != null)
                {
                    // needs updating for REST
                    foreach (ResultRow result in SerializedResults.SearchResults.Rows)
                    {
                        dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.Search))
                        {
                            dr["search"] = SerializedResults.Inputs.Search;
                        }

                        if (SerializedResults.Inputs.StartRow.HasValue && SerializedResults.Inputs.StartRow.Value > -1)
                        {
                            dr["startrow"] = SerializedResults.Inputs.StartRow.Value;
                        }

                        if (SerializedResults.Inputs.RowLimit.HasValue && SerializedResults.Inputs.RowLimit.Value > 0)
                        {
                            dr["rowlimit"] = SerializedResults.Inputs.RowLimit.Value;
                        }

                        if (SerializedResults.Inputs.SourceId != null && SerializedResults.Inputs.SourceId != Guid.Empty)
                        {
                            dr["sourceid"] = SerializedResults.Inputs.SourceId;
                        }

                        if (!string.IsNullOrWhiteSpace(SerializedResults.Inputs.SortString))
                        {
                            dr["sort"] = SerializedResults.Inputs.SortString;
                        }

                        if (SerializedResults.Inputs.EnableNicknames.HasValue && SerializedResults.Inputs.EnableNicknames.Value)
                        {
                            dr["enablenicknames"] = SerializedResults.Inputs.EnableNicknames.Value;
                        }

                        if (SerializedResults.Inputs.EnablePhonetic.HasValue && SerializedResults.Inputs.EnablePhonetic.Value)
                        {
                            dr["enablephonetic"] = SerializedResults.Inputs.EnablePhonetic.Value;
                        }

                        if (SerializedResults.ExecutionTime.HasValue)
                        {
                            dr["executiontime"] = SerializedResults.ExecutionTime.Value;
                        }

                        if (SerializedResults.ResultRows.HasValue)
                        {
                            dr["resultrows"] = SerializedResults.ResultRows.Value;
                        }
                        if (SerializedResults.TotalRows.HasValue)
                        {
                            dr["totalrows"] = SerializedResults.TotalRows.Value;
                        }
                        dr["resulttitle"] = SerializedResults.ResultTitle;
                        dr["resulttitleurl"] = SerializedResults.ResultTitleUrl;
                        dr["tabletype"] = SerializedResults.TableType;
                        dr["spellingsuggestions"] = SerializedResults.SpellingSuggestions;


                        List<string> missingprops = new List<string>();
                        foreach (ResultCell cell in result.Cells)
                        {
                            if (dr.Table.Columns.Contains(cell.Key.ToLower()))
                            {
                                if (cell.Value != null)
                                {
                                    dr[cell.Key.ToLower()] = cell.Value;
                                }
                            }
                            else
                            {
                                missingprops.Add(cell.Key);
                            }
                        }

                        dr["responsestatus"] = ResponseStatus.Success;
                        serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                    }
                }
                else
                {
                    throw new Exception("No results returned.");
                }

            }
            catch (Exception ex)
            {
                dr = serviceBroker.ServicePackage.ResultTable.NewRow();
                dr["responsestatus"] = ResponseStatus.Error;
                dr["responsestatusdescription"] = ex.Message;
                serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
            }

            //serviceObject.Properties.BindPropertiesToResultTable();
        }
        public void GetMessageBy(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            Helper h = new Helper(serviceBroker);

            string mailbox = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            string uid = string.Empty;
            string subjectfilter = string.Empty;                

            AE.Net.Mail.MailMessage m = null;
            try
            {
                using (var ic = h.GetImapClient())
                {

                    switch (serviceObject.Methods[0].Name.ToLower())
                    {
                        case "getmessagebyuid":
                            uid = inputs.Where(p => p.Name.Equals("uid")).FirstOrDefault().Value.ToString();
                            m = ic.GetMessage(uid, false);
                            break;
                        case "getmessagebysubject":
                            subjectfilter = inputs.Where(p => p.Name.Equals("subjectfilter")).FirstOrDefault().Value.ToString();
                            Lazy<AE.Net.Mail.MailMessage>[] mm = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.Subject(subjectfilter)));
                            Lazy<AE.Net.Mail.MailMessage> lm = mm.OrderByDescending(p => p.Value.Date).Where(p => p.Value.Subject.ToLower().Equals(subjectfilter)).FirstOrDefault();

                            if (lm != null && lm.Value != null)
                            {
                                m = lm.Value;
                            }
                            
                            break;
                    }

                    // = ic.GetMessage(uid, false);

                    if (m == null)
                    {
                        return;
                    }                    

                    returns.Where(p => p.Name.ToLower().Equals("bcc")).FirstOrDefault().Value = GetAddresses(m.Bcc);
                    returns.Where(p => p.Name.ToLower().Equals("body")).FirstOrDefault().Value = m.Body;
                    returns.Where(p => p.Name.ToLower().Equals("cc")).FirstOrDefault().Value = GetAddresses(m.Cc);
                    returns.Where(p => p.Name.ToLower().Equals("date")).FirstOrDefault().Value = m.Date;
                    returns.Where(p => p.Name.ToLower().Equals("from")).FirstOrDefault().Value = m.From != null ? m.From.Address : "";
                    returns.Where(p => p.Name.ToLower().Equals("importance")).FirstOrDefault().Value = m.Importance.ToString();
                    returns.Where(p => p.Name.ToLower().Equals("replyto")).FirstOrDefault().Value = GetAddresses(m.ReplyTo);
                    returns.Where(p => p.Name.ToLower().Equals("sender")).FirstOrDefault().Value = m.Sender != null ? m.Sender.Address : "";
                    returns.Where(p => p.Name.ToLower().Equals("size")).FirstOrDefault().Value = m.Size;
                    returns.Where(p => p.Name.ToLower().Equals("subject")).FirstOrDefault().Value = m.Subject;
                    returns.Where(p => p.Name.ToLower().Equals("to")).FirstOrDefault().Value = GetAddresses(m.To);
                    returns.Where(p => p.Name.ToLower().Equals("uid")).FirstOrDefault().Value = m.Uid;
                    //returns.Where(p => p.Name.ToLower().Equals("rawmessage")).FirstOrDefault().Value = m.RawBody;
                    //returns.Where(p => p.Name.ToLower().Equals("base64emlmessage")).FirstOrDefault().Value = m.Base64Body;
                    returns.Where(p => p.Name.ToLower().Equals("attachmentscount")).FirstOrDefault().Value = m.Attachments != null ? m.Attachments.Count : 0;

                    returns.Where(p => p.Name.ToLower().Equals("mailbox")).FirstOrDefault().Value = mailbox;
                    returns.Where(p => p.Name.ToLower().Equals("uid")).FirstOrDefault().Value = uid;
                    returns.Where(p => p.Name.ToLower().Equals("subjectfilter")).FirstOrDefault().Value = subjectfilter;

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            serviceObject.Properties.BindPropertiesToResultTable();
        }
        public void GetMessages(Property[] inputs, RequiredProperties required, Property[] returns, MethodType methodType, ServiceObject serviceObject)
        {
            serviceObject.Properties.InitResultTable();

            System.Data.DataRow dr;
            Helper h = new Helper(serviceBroker);

            string subjectfilter = string.Empty;
            string bodyfilter = string.Empty;
            string fromfilter = string.Empty;

            string startindex = string.Empty;
            string numberofmessages = string.Empty;

            string mailbox = inputs.Where(p => p.Name.Equals("mailbox")).FirstOrDefault().Value.ToString();
            bool headersonly = bool.Parse(inputs.Where(p => p.Name.Equals("headersonly")).FirstOrDefault().Value.ToString());
            bool setseen = bool.Parse(inputs.Where(p => p.Name.Equals("setseen")).FirstOrDefault().Value.ToString()); ;
            AE.Net.Mail.MailMessage mtemp = new AE.Net.Mail.MailMessage();
            try
            {
                using (var ic = h.GetImapClient())
                {

                    AE.Net.Mail.MailMessage[] m = null;
                    Lazy<AE.Net.Mail.MailMessage>[] mm = null;

                    bool isLazy = false;

                    switch (serviceObject.Methods[0].Name.ToLower())
                    {
                        case "getallmessages":
                            m = ic.GetMessages(0, ic.GetMessageCount(), headersonly, setseen);
                            isLazy = false;
                            break;
                        case "getmessages":
                            startindex = inputs.Where(p => p.Name.Equals("startindex")).FirstOrDefault().Value.ToString();
                            numberofmessages = inputs.Where(p => p.Name.Equals("numberofmessages")).FirstOrDefault().Value.ToString();
                            m = ic.GetMessages(int.Parse(startindex), int.Parse(numberofmessages), headersonly, setseen);                          
                            isLazy = false;
                            break;
                        case "searchmessagesbysubject":
                            subjectfilter = inputs.Where(p => p.Name.Equals("subjectfilter")).FirstOrDefault().Value.ToString();
                            mm = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.Subject(subjectfilter)));
                            isLazy = true;
                            break;
                        case "searchmessagesbybody":
                            bodyfilter = inputs.Where(p => p.Name.Equals("bodyfilter")).FirstOrDefault().Value.ToString();
                            mm = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.Body(bodyfilter))).ToArray();
                            isLazy = true;
                            break;
                        case "searchmessagesbyfrom":
                            fromfilter = inputs.Where(p => p.Name.Equals("fromfilter")).FirstOrDefault().Value.ToString();
                            mm = ic.SearchMessages(SearchCondition.Undeleted().And(SearchCondition.From(fromfilter))).ToArray();
                            isLazy = true;
                            break;                            
                    }

                    //AE.Net.Mail.MailMessage[] mm = ic.GetMessages(0, ic.GetMessageCount(), headersonly, setseen);

                    if (isLazy)
                    {
                        foreach (System.Lazy<AE.Net.Mail.MailMessage> msg in mm)
                        {
                            AE.Net.Mail.MailMessage mmsg = msg.Value;
                            dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                            MapMailMessage(dr, mmsg);
                            
                            dr["mailbox"] = mailbox;
                            dr["headersonly"] = headersonly;
                            dr["setseen"] = setseen;

                            switch (serviceObject.Methods[0].Name.ToLower())
                            {
                                case "searchmessagesbysubject":
                                    dr["subjectfilter"] = subjectfilter;
                                    break;
                                case "searchmessagesbybody":
                                    dr["bodyfilter"] = bodyfilter;
                                    break;
                                case "searchmessagesbyfrom":
                                    dr["fromfilter"] = fromfilter;
                                    break;
                            }


                            dr["startindex"] = startindex;
                            dr["numberofmessages"] = numberofmessages;

                            serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                        }
                    }
                    else
                    {
                        foreach (AE.Net.Mail.MailMessage msg in m.OrderByDescending(p => p.Date))
                        {
                            mtemp = msg;
                            dr = serviceBroker.ServicePackage.ResultTable.NewRow();

                            MapMailMessage(dr, msg);

                            dr["mailbox"] = mailbox;
                            dr["headersonly"] = headersonly;
                            dr["setseen"] = setseen;
                            switch (serviceObject.Methods[0].Name.ToLower())
                            {
                                case "searchmessagesbysubject":
                                    dr["subjectfilter"] = subjectfilter;
                                    break;
                                case "searchmessagesbybody":
                                    dr["bodyfilter"] = bodyfilter;
                                    break;
                                case "searchmessagesbyfrom":
                                    dr["fromfilter"] = fromfilter;
                                    break;
                            }
                            dr["startindex"] = startindex;
                            dr["numberofmessages"] = numberofmessages;

                            serviceBroker.ServicePackage.ResultTable.Rows.Add(dr);
                        }
                    }

                    ic.Disconnect();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(mtemp.Subject);
                //serviceObject.Properties.BindPropertiesToResultTable();
            }
            //serviceObject.Properties.BindPropertiesToResultTable();
        }