public static ViewsRelationsObj getRelationObj(ViewExcelSheetsInfo sheetView, string entity, string fromAttribute)
        {
            ViewsRelationsObj obj = sheetView.relationsList.Where(x => x.relationFrom != null && x.entity.Equals(entity, StringComparison.InvariantCultureIgnoreCase) &&
                                                                  x.relationFrom.Equals(fromAttribute, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

            if (obj == null)
            {
                ViewsRelationsObj             mainobj = sheetView.relationsList.Where(x => x.relationAlias == null).FirstOrDefault();
                OneToManyRelationshipMetadata rel     = mainobj.entityMetadata.ManyToOneRelationships
                                                        .Where(x => x.ReferencedEntity.Equals(entity, StringComparison.InvariantCultureIgnoreCase) &&
                                                               x.ReferencingAttribute.Equals(fromAttribute, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (rel != null)
                {
                    obj = new ViewsRelationsObj()
                    {
                        entity         = entity.ToLower(),
                        entityMetadata = GlobalOperations.Instance.CRMOpHelper.RetriveEntityAtrribute(entity),
                        relationAlias  = string.Concat("a_", Guid.NewGuid().ToString().Replace("-", "")).ToLower(),
                        relationFrom   = rel.ReferencedAttribute.ToLower(),
                        relationTo     = fromAttribute.ToLower()
                    };
                    sheetView.relationsList.Add(obj);
                }
            }
            return(obj);
        }
        public static void getFechAndLayouXml(ExcelMatrix dataMatrix, ViewExcelSheetsInfo sheetView, out string fetchXml, out string viewXml)
        {
            List <ViewFeo> viewFeoList = new List <ViewFeo>();

            for (int i = 0; i < dataMatrix.numberofElements; i++)
            {
                string[] row           = dataMatrix.getRow(i);
                string[] values        = getEntityRelation(row[ExcelColumsDefinition.VIEWATTRIBUTEENTITY]);
                string   attributeName = row[ExcelColumsDefinition.VIEWATTRIBUTENAME];
                if (attributeName.LastIndexOf("-") >= 0)
                {
                    attributeName = attributeName.Substring(attributeName.LastIndexOf("-") + 1, attributeName.Length - attributeName.LastIndexOf("-") - 1);
                    attributeName = attributeName.Trim();
                }
                string attributeEntity            = string.Empty;
                string attributeRelationAttribute = string.Empty;
                if (values != null && values.Count() == 2)
                {
                    attributeEntity            = values[0];
                    attributeRelationAttribute = values[1];
                }
                string            attributewidth = row[ExcelColumsDefinition.VIEWATTRIBUTEWIDTH];
                ViewsRelationsObj obj            = null;
                if (!string.IsNullOrEmpty(attributeEntity))
                {
                    obj = sheetView.relationsList.Where(x => x.relationAlias != null && x.entity.Equals(attributeEntity, StringComparison.InvariantCultureIgnoreCase) &&
                                                        x.relationTo.Equals(attributeRelationAttribute, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                }
                else
                {
                    obj             = sheetView.relationsList.Where(x => x.relationAlias == null).FirstOrDefault();
                    attributeEntity = obj.entity;
                }

                ViewFeo viewFeo = new ViewFeo()
                {
                    AttributeName   = attributeName,
                    AttributeEntity = attributeEntity,
                    AttributeWidth  = attributewidth,
                    AttributeObj    = obj,
                };
                if (obj == null)
                {
                    setAttributesObj(viewFeo, sheetView.relationsList);
                }
                viewFeoList.Add(viewFeo);
            }
            viewXml = getViewXmlString(viewFeoList, sheetView.viewObj);
            removeUnnecessaryLinksAttributes(sheetView.viewObj, sheetView);
            fetchXml = getFecthXmlString(viewFeoList, sheetView.fetchObj);
        }
        public void CreatenNewViewSheet(string viewName, string viewDescription, Guid entity)
        {
            EntityMetadata etMetadata            = GlobalOperations.Instance.CRMOpHelper.RetriveEntityAtrribute(entity);
            IEnumerable <AttributeMetadata> attr = etMetadata.Attributes.Where(x => x.AttributeType != null && x.AttributeType == AttributeTypeCode.Lookup);
            GlobalApplicationData           data = GlobalApplicationData.Instance;
            string sheetName = string.Format("{0} - {1}", viewName, etMetadata.LogicalName.ToString());

            CreatenNewExcelSheet(sheetName, new ViewExcelSheetsInfo(Guid.NewGuid(), viewName, viewDescription, etMetadata.LogicalName, entity));
            ViewXml.GenerateNewFechXml((ViewExcelSheetsInfo)data.eSheetsInfomation.getCurrentSheet(), etMetadata);
            ViewExcelSheetsInfo currentSheet = ((ViewExcelSheetsInfo)data.eSheetsInfomation.getCurrentSheet());

            currentSheet.language      = GlobalApplicationData.Instance.currentLanguage;
            currentSheet.relationsList = ViewXml.GenerateViewRelatedObj(currentSheet);
            GlobalOperations.Instance.ExcelOperations.RefreshViewSheet(data.eSheetsInfomation.getCurrentSheet(), attr);
        }
        public static List <ViewsRelationsObj> GenerateViewRelatedObj(ViewExcelSheetsInfo sheetView)
        {
            List <ViewsRelationsObj> listObj = new List <ViewsRelationsObj>();

            if (sheetView.viewObj != null && sheetView.viewObj.row != null && sheetView.viewObj.row.cell != null)
            {
                foreach (var row in sheetView.viewObj.row.cell)
                {
                    if (row != null)
                    {
                        updateViewRelatedObj(sheetView.fetchObj, row.name, listObj);
                    }
                }
            }
            return(listObj);
        }
        public void CreatenNewViewSheet(Guid viewId, Guid entity)
        {
            Entity         view                  = CRMOpHelper.GetView(viewId);
            EntityMetadata etMetadata            = CRMOpHelper.RetriveEntityAtrribute(entity);
            IEnumerable <AttributeMetadata> attr = etMetadata.Attributes.Where(x => x.AttributeType != null && x.AttributeType == AttributeTypeCode.Lookup);

            if (view != null && view.Contains("name") && view.Contains("layoutxml") && view.Contains("returnedtypecode") && view.Contains("fetchxml"))
            {
                GlobalApplicationData data      = GlobalApplicationData.Instance;
                string sheetName                = string.Format("{0} - {1}", view["name"].ToString(), view["returnedtypecode"].ToString());
                savedqueryLayoutxmlGrid viewObj = FormXmlMapper.MapViewXmlToObj(view.Attributes["layoutxml"].ToString());
                FetchType fatchObj              = FormXmlMapper.MapFetchXmlToObj(view.Attributes["fetchxml"].ToString());
                CreatenNewExcelSheet(sheetName, new ViewExcelSheetsInfo(viewId, view.Attributes["layoutxml"].ToString(), view.Attributes["fetchxml"].ToString(), viewObj, fatchObj, entity, etMetadata.LogicalName));
                ViewExcelSheetsInfo currentSheet = ((ViewExcelSheetsInfo)data.eSheetsInfomation.getCurrentSheet());
                currentSheet.language      = GlobalApplicationData.Instance.currentLanguage;
                currentSheet.relationsList = ViewXml.GenerateViewRelatedObj(currentSheet);
                ExcelOperations.RefreshViewSheet(data.eSheetsInfomation.getCurrentSheet(), attr);
            }
        }
        public static void GenerateNewFechXml(ViewExcelSheetsInfo sheetView, EntityMetadata etMetadata)
        {
            FetchEntityType et = new FetchEntityType();

            et.name  = etMetadata.LogicalName;
            et.Items = new object[3] {
                new FetchOrderType()
                {
                    attribute = etMetadata.PrimaryIdAttribute, descending = false
                }, new FetchAttributeType()
                {
                    name = etMetadata.PrimaryIdAttribute
                }, new FetchAttributeType()
                {
                    name = etMetadata.PrimaryNameAttribute
                }
            };
            sheetView.fetchObj.Items        = new object[] { et };
            sheetView.fetchObj.version      = "1.0";
            sheetView.fetchObj.outputformat = FetchTypeOutputformat.xmlplatform;
            sheetView.fetchObj.mapping      = FetchTypeMapping.logical;
            savedqueryLayoutxmlGridRowCell[] cells = new savedqueryLayoutxmlGridRowCell[1] {
                new savedqueryLayoutxmlGridRowCell()
                {
                    name = etMetadata.PrimaryNameAttribute, width = "150"
                }
            };
            sheetView.viewObj.row = new savedqueryLayoutxmlGridRow()
            {
                cell = cells, name = "result", id = etMetadata.PrimaryIdAttribute
            };
            sheetView.viewObj.select  = "1";
            sheetView.viewObj.preview = "1";
            sheetView.viewObj.@object = etMetadata.ObjectTypeCode.ToString();
            sheetView.viewObj.icon    = "1";
            sheetView.viewObj.jump    = etMetadata.PrimaryNameAttribute;
            sheetView.viewObj.name    = "resultset";
        }
        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            int i = 0;

            foreach (var item in operationList)
            {
                if (item.executeOperation)
                {
                    GlobalOperations.Instance.CRMOpHelper.executeOpertionsCrm(item);
                    i++;
                }
                worker.ReportProgress((int)(((double)i / operationList.Count()) * 100));
            }

            ExcelSheetInfo currentsheet = GlobalApplicationData.Instance.eSheetsInfomation.getCurrentSheet();

            if (currentsheet != null)
            {
                switch (currentsheet.sheetType)
                {
                case ExcelSheetInfo.ExcelSheetType.view:
                {
                    ViewExcelSheetsInfo viewSheet = (ViewExcelSheetsInfo)currentsheet;
                    if (viewSheet.isNew == true && operationList.First().operationSucceded)
                    {
                        if (operationList.Count() > 0 && operationList.First().orgResponse != null && operationList.First().orgResponse is CreateResponse)
                        {
                            viewSheet.viewId = ((CreateResponse)operationList.First().orgResponse).id;
                        }
                        viewSheet.isNew = false;
                    }
                    break;
                }
                }
            }
        }
        private static void removeUnnecessaryLinksAttributes(savedqueryLayoutxmlGrid viewFeo, ViewExcelSheetsInfo excelData)
        {
            FetchEntityType   currentEt = excelData.fetchObj.Items.Where(x => x is FetchEntityType).Select(x => (FetchEntityType)x).FirstOrDefault();
            ViewsRelationsObj obj       = excelData.relationsList.Where(x => x.relationAlias == null).FirstOrDefault();

            if (currentEt != null && obj != null)
            {
                List <object> array = currentEt.Items.ToList();
                for (int i = array.Count - 1; i > -1; i--)
                {
                    object currentItem = array[i];
                    if (currentItem is FetchLinkEntityType)
                    {
                        FetchLinkEntityType link = currentItem as FetchLinkEntityType;
                        removeUnnecessaryAttributesInner(link, viewFeo);
                        if (link == null || link.visible == false)
                        {
                            if (link == null || link.Items.Count() == 0)
                            {
                                array.RemoveAt(i);
                            }
                        }
                    }
                    else if (currentItem is FetchAttributeType)
                    {
                        FetchAttributeType attr = currentItem as FetchAttributeType;
                        if (!(viewFeo.row.cell.Where(x => x.name == attr.name).Count() > 0) && attr.name != obj.entityMetadata.PrimaryIdAttribute)
                        {
                            array.RemoveAt(i);
                        }
                    }
                }
                currentEt.Items = array.ToArray();
            }
        }
        public static IEnumerable <CrmOperation> generateCrmOperationRequest(ExcelMatrix dataMatrix, ViewExcelSheetsInfo sheetView)
        {
            List <CrmOperation> crmOp = new List <CrmOperation>();

            try
            {
                string fetchXml;
                string viewXml;
                getFechAndLayouXml(dataMatrix, sheetView, out fetchXml, out viewXml);
                if (sheetView.isNew)
                {
                    crmOp.Add(generateUpdateRequest(viewXml, fetchXml, sheetView.name, sheetView.description, sheetView.entity));
                }
                else
                {
                    crmOp.Add(generateUpdateRequest(viewXml, fetchXml, sheetView.viewId));
                }
            }
            catch (Exception ex)
            {
                crmOp.Add(new CrmOperation(CrmOperation.CrmOperationType.error, CrmOperation.CrmOperationTarget.none, null, "Generic error"));
            }
            return(crmOp);
        }